blob: d0e74c1fa07e35fdd78f4df166a73e1522201321 [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 Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattner79a42ac2006-12-19 21:40:18 +000064namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000109
Chris Lattner99f48c62002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000112 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000114
Chris Lattnerf12cc842002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000119 }
120
Chris Lattner69193f92004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattner260ab202002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000129 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000146 Instruction *visitFCmpInst(FCmpInst &I);
147 Instruction *visitICmpInst(ICmpInst &I);
148 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000149
Reid Spencer266e42b2006-12-23 06:05:41 +0000150 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000155 Instruction *commonCastTransforms(CastInst &CI);
156 Instruction *commonIntCastTransforms(CastInst &CI);
157 Instruction *visitTrunc(CastInst &CI);
158 Instruction *visitZExt(CastInst &CI);
159 Instruction *visitSExt(CastInst &CI);
160 Instruction *visitFPTrunc(CastInst &CI);
161 Instruction *visitFPExt(CastInst &CI);
162 Instruction *visitFPToUI(CastInst &CI);
163 Instruction *visitFPToSI(CastInst &CI);
164 Instruction *visitUIToFP(CastInst &CI);
165 Instruction *visitSIToFP(CastInst &CI);
166 Instruction *visitPtrToInt(CastInst &CI);
167 Instruction *visitIntToPtr(CastInst &CI);
168 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000169 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000171 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 Instruction *visitCallInst(CallInst &CI);
173 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitPHINode(PHINode &PN);
175 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000176 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000177 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000178 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000179 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000180 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000181 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000182 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000183 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000184 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000185
186 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000187 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000188
Chris Lattner970c33a2003-06-19 17:00:31 +0000189 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000190 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000191 bool transformConstExprCastCall(CallSite CS);
192
Chris Lattner69193f92004-04-05 01:30:19 +0000193 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 // InsertNewInstBefore - insert an instruction New before instruction Old
195 // in the program. Add the new instruction to the worklist.
196 //
Chris Lattner623826c2004-09-28 21:48:02 +0000197 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000198 assert(New && New->getParent() == 0 &&
199 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000200 BasicBlock *BB = Old.getParent();
201 BB->getInstList().insert(&Old, New); // Insert inst
202 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000203 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000204 }
205
Chris Lattner7e794272004-09-24 15:21:34 +0000206 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207 /// This also adds the cast to the worklist. Finally, this returns the
208 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000209 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000211 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212
Chris Lattnere79d2492006-04-06 19:19:17 +0000213 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000214 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000215
Reid Spencer13bc5d72006-12-12 09:18:51 +0000216 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000217 WorkList.push_back(C);
218 return C;
219 }
220
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000221 // ReplaceInstUsesWith - This method is to be used when an instruction is
222 // found to be dead, replacable with another preexisting expression. Here
223 // we add all uses of I to the worklist, replace all uses of I with the new
224 // value, then return I, so that the inst combiner will know that I was
225 // modified.
226 //
227 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000228 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000229 if (&I != V) {
230 I.replaceAllUsesWith(V);
231 return &I;
232 } else {
233 // If we are replacing the instruction with itself, this must be in a
234 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000235 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000236 return &I;
237 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000238 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000239
Chris Lattner2590e512006-02-07 06:56:34 +0000240 // UpdateValueUsesWith - This method is to be used when an value is
241 // found to be replacable with another preexisting expression or was
242 // updated. Here we add all uses of I to the worklist, replace all uses of
243 // I with the new value (unless the instruction was just updated), then
244 // return true, so that the inst combiner will know that I was modified.
245 //
246 bool UpdateValueUsesWith(Value *Old, Value *New) {
247 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
248 if (Old != New)
249 Old->replaceAllUsesWith(New);
250 if (Instruction *I = dyn_cast<Instruction>(Old))
251 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000252 if (Instruction *I = dyn_cast<Instruction>(New))
253 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000254 return true;
255 }
256
Chris Lattner51ea1272004-02-28 05:22:00 +0000257 // EraseInstFromFunction - When dealing with an instruction that has side
258 // effects or produces a void value, we can't rely on DCE to delete the
259 // instruction. Instead, visit methods should return the value returned by
260 // this function.
261 Instruction *EraseInstFromFunction(Instruction &I) {
262 assert(I.use_empty() && "Cannot erase instruction that is used!");
263 AddUsesToWorkList(I);
264 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000265 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000266 return 0; // Don't do anything with FI
267 }
268
Chris Lattner3ac7c262003-08-13 20:16:26 +0000269 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000270 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271 /// InsertBefore instruction. This is specialized a bit to avoid inserting
272 /// casts that are known to not do anything...
273 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000274 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000276 Instruction *InsertBefore);
277
Reid Spencer266e42b2006-12-23 06:05:41 +0000278 /// SimplifyCommutative - This performs a few simplifications for
279 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000281
Reid Spencer266e42b2006-12-23 06:05:41 +0000282 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283 /// most-complex to least-complex order.
284 bool SimplifyCompare(CmpInst &I);
285
Chris Lattner0157e7f2006-02-11 09:31:47 +0000286 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
287 uint64_t &KnownZero, uint64_t &KnownOne,
288 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000289
Chris Lattner2deeaea2006-10-05 06:55:50 +0000290 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291 uint64_t &UndefElts, unsigned Depth = 0);
292
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000293 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294 // PHI node as operand #0, see if we can fold the instruction into the PHI
295 // (which is only possible if all operands to the PHI are constants).
296 Instruction *FoldOpIntoPhi(Instruction &I);
297
Chris Lattner7515cab2004-11-14 19:13:23 +0000298 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299 // operator and they all are only used by the PHI, PHI together their
300 // inputs, and do the operation once, to the result of the PHI.
301 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000302 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303
304
Chris Lattnerba1cb382003-09-19 17:17:26 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000307
308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000311 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000313 Instruction *MatchBSwap(BinaryOperator &I);
314
Reid Spencer74a528b2006-12-13 18:21:21 +0000315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000316 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000317
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000319}
320
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000322// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000326 return 3;
327 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000331}
Chris Lattner260ab202002-04-18 17:39:14 +0000332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// isOnlyUse - Return true if this instruction will be deleted if we stop using
334// it.
335static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000336 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337}
338
Chris Lattnere79e8542004-02-23 06:38:22 +0000339// getPromotedType - Return the specified type promoted as it would be to pass
340// though a va_arg area...
341static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000342 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000343 case Type::SByteTyID:
344 case Type::ShortTyID: return Type::IntTy;
345 case Type::UByteTyID:
346 case Type::UShortTyID: return Type::UIntTy;
347 case Type::FloatTyID: return Type::DoubleTy;
348 default: return Ty;
349 }
350}
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
393 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000394 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000395 return false;
396
Chris Lattner99155be2006-05-25 23:24:33 +0000397 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000398 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000399 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000400 return false;
401 return true;
402}
403
404/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
405/// InsertBefore instruction. This is specialized a bit to avoid inserting
406/// casts that are known to not do anything...
407///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000408Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
409 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410 Instruction *InsertBefore) {
411 if (V->getType() == DestTy) return V;
412 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000413 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414
Reid Spencer13bc5d72006-12-12 09:18:51 +0000415 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000416}
417
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000418// SimplifyCommutative - This performs a few simplifications for commutative
419// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000420//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421// 1. Order operands such that they are listed from right (least complex) to
422// left (most complex). This puts constants before unary operators before
423// binary operators.
424//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000425// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
426// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000428bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000429 bool Changed = false;
430 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
431 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000432
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000433 if (!I.isAssociative()) return Changed;
434 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
436 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
437 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000438 Constant *Folded = ConstantExpr::get(I.getOpcode(),
439 cast<Constant>(I.getOperand(1)),
440 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000441 I.setOperand(0, Op->getOperand(0));
442 I.setOperand(1, Folded);
443 return true;
444 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
445 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
446 isOnlyUse(Op) && isOnlyUse(Op1)) {
447 Constant *C1 = cast<Constant>(Op->getOperand(1));
448 Constant *C2 = cast<Constant>(Op1->getOperand(1));
449
450 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000451 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000452 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
453 Op1->getOperand(0),
454 Op1->getName(), &I);
455 WorkList.push_back(New);
456 I.setOperand(0, New);
457 I.setOperand(1, Folded);
458 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000459 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000461 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000462}
Chris Lattnerca081252001-12-14 16:52:21 +0000463
Reid Spencer266e42b2006-12-23 06:05:41 +0000464/// SimplifyCompare - For a CmpInst this function just orders the operands
465/// so that theyare listed from right (least complex) to left (most complex).
466/// This puts constants before unary operators before binary operators.
467bool InstCombiner::SimplifyCompare(CmpInst &I) {
468 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
469 return false;
470 I.swapOperands();
471 // Compare instructions are not associative so there's nothing else we can do.
472 return true;
473}
474
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
476// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000477//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000478static inline Value *dyn_castNegVal(Value *V) {
479 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000480 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000481
Chris Lattner9ad0d552004-12-14 20:08:06 +0000482 // Constants can be considered to be negated values if they can be folded.
483 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
484 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000486}
487
Chris Lattnerbb74e222003-03-10 23:06:50 +0000488static inline Value *dyn_castNotVal(Value *V) {
489 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000490 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000491
492 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000493 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000494 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495 return 0;
496}
497
Chris Lattner7fb29e12003-03-11 00:12:48 +0000498// dyn_castFoldableMul - If this value is a multiply that can be folded into
499// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000500// non-constant operand of the multiply, and set CST to point to the multiplier.
501// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000504 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000506 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000507 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000508 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000509 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000510 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000511 // The multiplier is really 1 << CST.
512 Constant *One = ConstantInt::get(V->getType(), 1);
513 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
514 return I->getOperand(0);
515 }
516 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000517 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000518}
Chris Lattner31ae8632002-08-14 17:51:49 +0000519
Chris Lattner0798af32005-01-13 20:14:25 +0000520/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
521/// expression, return it.
522static User *dyn_castGetElementPtr(Value *V) {
523 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
524 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
525 if (CE->getOpcode() == Instruction::GetElementPtr)
526 return cast<User>(V);
527 return false;
528}
529
Chris Lattner623826c2004-09-28 21:48:02 +0000530// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000531static ConstantInt *AddOne(ConstantInt *C) {
532 return cast<ConstantInt>(ConstantExpr::getAdd(C,
533 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000534}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000535static ConstantInt *SubOne(ConstantInt *C) {
536 return cast<ConstantInt>(ConstantExpr::getSub(C,
537 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000538}
539
Chris Lattner0157e7f2006-02-11 09:31:47 +0000540/// GetConstantInType - Return a ConstantInt with the specified type and value.
541///
Chris Lattneree0f2802006-02-12 02:07:56 +0000542static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000543 if (Ty->isUnsigned())
544 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000545 else if (Ty->getTypeID() == Type::BoolTyID)
546 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000547 int64_t SVal = Val;
548 SVal <<= 64-Ty->getPrimitiveSizeInBits();
549 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000550 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000551}
552
553
Chris Lattner4534dd592006-02-09 07:38:58 +0000554/// ComputeMaskedBits - Determine which of the bits specified in Mask are
555/// known to be either zero or one and return them in the KnownZero/KnownOne
556/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
557/// processing.
558static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
559 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000560 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
561 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000562 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000563 // optimized based on the contradictory assumption that it is non-zero.
564 // Because instcombine aggressively folds operations with undef args anyway,
565 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000566 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
567 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000568 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000569 KnownZero = ~KnownOne & Mask;
570 return;
571 }
572
573 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000574 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000575 return; // Limit search depth.
576
577 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000578 Instruction *I = dyn_cast<Instruction>(V);
579 if (!I) return;
580
Chris Lattnerfb296922006-05-04 17:33:35 +0000581 Mask &= V->getType()->getIntegralTypeMask();
582
Chris Lattner0157e7f2006-02-11 09:31:47 +0000583 switch (I->getOpcode()) {
584 case Instruction::And:
585 // If either the LHS or the RHS are Zero, the result is zero.
586 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
587 Mask &= ~KnownZero;
588 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
589 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
590 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
591
592 // Output known-1 bits are only known if set in both the LHS & RHS.
593 KnownOne &= KnownOne2;
594 // Output known-0 are known to be clear if zero in either the LHS | RHS.
595 KnownZero |= KnownZero2;
596 return;
597 case Instruction::Or:
598 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
599 Mask &= ~KnownOne;
600 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
603
604 // Output known-0 bits are only known if clear in both the LHS & RHS.
605 KnownZero &= KnownZero2;
606 // Output known-1 are known to be set if set in either the LHS | RHS.
607 KnownOne |= KnownOne2;
608 return;
609 case Instruction::Xor: {
610 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
611 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
612 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
613 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
614
615 // Output known-0 bits are known if clear or set in both the LHS & RHS.
616 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
617 // Output known-1 are known to be set if set in only one of the LHS, RHS.
618 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
619 KnownZero = KnownZeroOut;
620 return;
621 }
622 case Instruction::Select:
623 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
625 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
626 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
627
628 // Only known if known in both the LHS and RHS.
629 KnownOne &= KnownOne2;
630 KnownZero &= KnownZero2;
631 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000632 case Instruction::FPTrunc:
633 case Instruction::FPExt:
634 case Instruction::FPToUI:
635 case Instruction::FPToSI:
636 case Instruction::SIToFP:
637 case Instruction::PtrToInt:
638 case Instruction::UIToFP:
639 case Instruction::IntToPtr:
640 return; // Can't work with floating point or pointers
641 case Instruction::Trunc:
642 // All these have integer operands
643 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
644 return;
645 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000646 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000647 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000648 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000649 return;
650 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000651 break;
652 }
653 case Instruction::ZExt: {
654 // Compute the bits in the result that are not present in the input.
655 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000656 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
657 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000658
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000659 Mask &= SrcTy->getIntegralTypeMask();
660 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
661 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
662 // The top bits are known to be zero.
663 KnownZero |= NewBits;
664 return;
665 }
666 case Instruction::SExt: {
667 // Compute the bits in the result that are not present in the input.
668 const Type *SrcTy = I->getOperand(0)->getType();
669 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
670 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
671
672 Mask &= SrcTy->getIntegralTypeMask();
673 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
674 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000675
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000676 // If the sign bit of the input is known set or clear, then we know the
677 // top bits of the result.
678 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
679 if (KnownZero & InSignBit) { // Input sign bit known zero
680 KnownZero |= NewBits;
681 KnownOne &= ~NewBits;
682 } else if (KnownOne & InSignBit) { // Input sign bit known set
683 KnownOne |= NewBits;
684 KnownZero &= ~NewBits;
685 } else { // Input sign bit unknown
686 KnownZero &= ~NewBits;
687 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000688 }
689 return;
690 }
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000693 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
694 uint64_t ShiftAmt = SA->getZExtValue();
695 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000698 KnownZero <<= ShiftAmt;
699 KnownOne <<= ShiftAmt;
700 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000701 return;
702 }
703 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000704 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000706 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000707 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000708 uint64_t ShiftAmt = SA->getZExtValue();
709 uint64_t HighBits = (1ULL << ShiftAmt)-1;
710 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000711
Reid Spencerfdff9382006-11-08 06:47:33 +0000712 // Unsigned 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;
718 KnownZero |= HighBits; // high bits known zero.
719 return;
720 }
721 break;
722 case Instruction::AShr:
723 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
724 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
725 // Compute the new bits that are at the top now.
726 uint64_t ShiftAmt = SA->getZExtValue();
727 uint64_t HighBits = (1ULL << ShiftAmt)-1;
728 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
729
730 // Signed shift right.
731 Mask <<= ShiftAmt;
732 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
733 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
734 KnownZero >>= ShiftAmt;
735 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000736
Reid Spencerfdff9382006-11-08 06:47:33 +0000737 // Handle the sign bits.
738 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
739 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000740
Reid Spencerfdff9382006-11-08 06:47:33 +0000741 if (KnownZero & SignBit) { // New bits are known zero.
742 KnownZero |= HighBits;
743 } else if (KnownOne & SignBit) { // New bits are known one.
744 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000745 }
746 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000747 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000748 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000749 }
Chris Lattner92a68652006-02-07 08:05:22 +0000750}
751
752/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
753/// this predicate to simplify operations downstream. Mask is known to be zero
754/// for bits that V cannot have.
755static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000756 uint64_t KnownZero, KnownOne;
757 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000760}
761
Chris Lattner0157e7f2006-02-11 09:31:47 +0000762/// ShrinkDemandedConstant - Check to see if the specified operand of the
763/// specified instruction is a constant integer. If so, check to see if there
764/// are any bits set in the constant that are not demanded. If so, shrink the
765/// constant and return true.
766static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
767 uint64_t Demanded) {
768 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
769 if (!OpC) return false;
770
771 // If there are no bits set that aren't demanded, nothing to do.
772 if ((~Demanded & OpC->getZExtValue()) == 0)
773 return false;
774
775 // This is producing any bits that are not needed, shrink the RHS.
776 uint64_t Val = Demanded & OpC->getZExtValue();
777 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
778 return true;
779}
780
Chris Lattneree0f2802006-02-12 02:07:56 +0000781// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
782// set of known zero and one bits, compute the maximum and minimum values that
783// could have the specified known zero and known one bits, returning them in
784// min/max.
785static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
786 uint64_t KnownZero,
787 uint64_t KnownOne,
788 int64_t &Min, int64_t &Max) {
789 uint64_t TypeBits = Ty->getIntegralTypeMask();
790 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
791
792 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
793
794 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
795 // bit if it is unknown.
796 Min = KnownOne;
797 Max = KnownOne|UnknownBits;
798
799 if (SignBit & UnknownBits) { // Sign bit is unknown
800 Min |= SignBit;
801 Max &= ~SignBit;
802 }
803
804 // Sign extend the min/max values.
805 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
806 Min = (Min << ShAmt) >> ShAmt;
807 Max = (Max << ShAmt) >> ShAmt;
808}
809
810// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
811// a set of known zero and one bits, compute the maximum and minimum values that
812// could have the specified known zero and known one bits, returning them in
813// min/max.
814static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
815 uint64_t KnownZero,
816 uint64_t KnownOne,
817 uint64_t &Min,
818 uint64_t &Max) {
819 uint64_t TypeBits = Ty->getIntegralTypeMask();
820 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821
822 // The minimum value is when the unknown bits are all zeros.
823 Min = KnownOne;
824 // The maximum value is when the unknown bits are all ones.
825 Max = KnownOne|UnknownBits;
826}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000827
828
829/// SimplifyDemandedBits - Look at V. At this point, we know that only the
830/// DemandedMask bits of the result of V are ever used downstream. If we can
831/// use this information to simplify V, do so and return true. Otherwise,
832/// analyze the expression and return a mask of KnownOne and KnownZero bits for
833/// the expression (used to simplify the caller). The KnownZero/One bits may
834/// only be accurate for those bits in the DemandedMask.
835bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
836 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000837 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000838 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
839 // We know all of the bits for a constant!
840 KnownOne = CI->getZExtValue() & DemandedMask;
841 KnownZero = ~KnownOne & DemandedMask;
842 return false;
843 }
844
845 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000846 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000847 if (Depth != 0) { // Not at the root.
848 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
849 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000850 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000851 }
Chris Lattner2590e512006-02-07 06:56:34 +0000852 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000853 // just set the DemandedMask to all bits.
854 DemandedMask = V->getType()->getIntegralTypeMask();
855 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000856 if (V != UndefValue::get(V->getType()))
857 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
858 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000859 } else if (Depth == 6) { // Limit search depth.
860 return false;
861 }
862
863 Instruction *I = dyn_cast<Instruction>(V);
864 if (!I) return false; // Only analyze instructions.
865
Chris Lattnerfb296922006-05-04 17:33:35 +0000866 DemandedMask &= V->getType()->getIntegralTypeMask();
867
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000868 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000869 switch (I->getOpcode()) {
870 default: break;
871 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000872 // If either the LHS or the RHS are Zero, the result is zero.
873 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
874 KnownZero, KnownOne, Depth+1))
875 return true;
876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
877
878 // If something is known zero on the RHS, the bits aren't demanded on the
879 // LHS.
880 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
881 KnownZero2, KnownOne2, Depth+1))
882 return true;
883 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
884
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000885 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 // These bits cannot contribute to the result of the 'and'.
887 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
888 return UpdateValueUsesWith(I, I->getOperand(0));
889 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
890 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000891
892 // If all of the demanded bits in the inputs are known zeros, return zero.
893 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
894 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
895
Chris Lattner0157e7f2006-02-11 09:31:47 +0000896 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000897 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 return UpdateValueUsesWith(I, I);
899
900 // Output known-1 bits are only known if set in both the LHS & RHS.
901 KnownOne &= KnownOne2;
902 // Output known-0 are known to be clear if zero in either the LHS | RHS.
903 KnownZero |= KnownZero2;
904 break;
905 case Instruction::Or:
906 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
907 KnownZero, KnownOne, Depth+1))
908 return true;
909 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
910 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
911 KnownZero2, KnownOne2, Depth+1))
912 return true;
913 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
914
915 // If all of the demanded bits are known zero on one side, return the other.
916 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000917 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000919 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000920 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000921
922 // If all of the potentially set bits on one side are known to be set on
923 // the other side, just use the 'other' side.
924 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
925 (DemandedMask & (~KnownZero)))
926 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000927 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
928 (DemandedMask & (~KnownZero2)))
929 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000930
931 // If the RHS is a constant, see if we can simplify it.
932 if (ShrinkDemandedConstant(I, 1, DemandedMask))
933 return UpdateValueUsesWith(I, I);
934
935 // Output known-0 bits are only known if clear in both the LHS & RHS.
936 KnownZero &= KnownZero2;
937 // Output known-1 are known to be set if set in either the LHS | RHS.
938 KnownOne |= KnownOne2;
939 break;
940 case Instruction::Xor: {
941 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
942 KnownZero, KnownOne, Depth+1))
943 return true;
944 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
945 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
946 KnownZero2, KnownOne2, Depth+1))
947 return true;
948 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
949
950 // If all of the demanded bits are known zero on one side, return the other.
951 // These bits cannot contribute to the result of the 'xor'.
952 if ((DemandedMask & KnownZero) == DemandedMask)
953 return UpdateValueUsesWith(I, I->getOperand(0));
954 if ((DemandedMask & KnownZero2) == DemandedMask)
955 return UpdateValueUsesWith(I, I->getOperand(1));
956
957 // Output known-0 bits are known if clear or set in both the LHS & RHS.
958 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
959 // Output known-1 are known to be set if set in only one of the LHS, RHS.
960 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
961
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000962 // If all of the demanded bits are known to be zero on one side or the
963 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000964 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000965 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
966 Instruction *Or =
967 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
968 I->getName());
969 InsertNewInstBefore(Or, *I);
970 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000971 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972
Chris Lattner5b2edb12006-02-12 08:02:11 +0000973 // If all of the demanded bits on one side are known, and all of the set
974 // bits on that side are also known to be set on the other side, turn this
975 // into an AND, as we know the bits will be cleared.
976 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
977 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
978 if ((KnownOne & KnownOne2) == KnownOne) {
979 Constant *AndC = GetConstantInType(I->getType(),
980 ~KnownOne & DemandedMask);
981 Instruction *And =
982 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
983 InsertNewInstBefore(And, *I);
984 return UpdateValueUsesWith(I, And);
985 }
986 }
987
Chris Lattner0157e7f2006-02-11 09:31:47 +0000988 // If the RHS is a constant, see if we can simplify it.
989 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
990 if (ShrinkDemandedConstant(I, 1, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992
993 KnownZero = KnownZeroOut;
994 KnownOne = KnownOneOut;
995 break;
996 }
997 case Instruction::Select:
998 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
999 KnownZero, KnownOne, Depth+1))
1000 return true;
1001 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1002 KnownZero2, KnownOne2, Depth+1))
1003 return true;
1004 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1005 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1006
1007 // If the operands are constants, see if we can simplify them.
1008 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1009 return UpdateValueUsesWith(I, I);
1010 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1011 return UpdateValueUsesWith(I, I);
1012
1013 // Only known if known in both the LHS and RHS.
1014 KnownOne &= KnownOne2;
1015 KnownZero &= KnownZero2;
1016 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001017 case Instruction::Trunc:
1018 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1019 KnownZero, KnownOne, Depth+1))
1020 return true;
1021 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1022 break;
1023 case Instruction::BitCast:
1024 if (!I->getOperand(0)->getType()->isIntegral())
1025 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001026
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001027 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1028 KnownZero, KnownOne, Depth+1))
1029 return true;
1030 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1031 break;
1032 case Instruction::ZExt: {
1033 // Compute the bits in the result that are not present in the input.
1034 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001035 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1036 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1037
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001038 DemandedMask &= SrcTy->getIntegralTypeMask();
1039 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1040 KnownZero, KnownOne, Depth+1))
1041 return true;
1042 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1043 // The top bits are known to be zero.
1044 KnownZero |= NewBits;
1045 break;
1046 }
1047 case Instruction::SExt: {
1048 // Compute the bits in the result that are not present in the input.
1049 const Type *SrcTy = I->getOperand(0)->getType();
1050 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1051 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1052
1053 // Get the sign bit for the source type
1054 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1055 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001056
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001057 // If any of the sign extended bits are demanded, we know that the sign
1058 // bit is demanded.
1059 if (NewBits & DemandedMask)
1060 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001061
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001062 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1063 KnownZero, KnownOne, Depth+1))
1064 return true;
1065 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001067 // If the sign bit of the input is known set or clear, then we know the
1068 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001069
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001070 // If the input sign bit is known zero, or if the NewBits are not demanded
1071 // convert this into a zero extension.
1072 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1073 // Convert to ZExt cast
1074 CastInst *NewCast = CastInst::create(
1075 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1076 return UpdateValueUsesWith(I, NewCast);
1077 } else if (KnownOne & InSignBit) { // Input sign bit known set
1078 KnownOne |= NewBits;
1079 KnownZero &= ~NewBits;
1080 } else { // Input sign bit unknown
1081 KnownZero &= ~NewBits;
1082 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001083 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001084 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001085 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001086 case Instruction::Add:
1087 // If there is a constant on the RHS, there are a variety of xformations
1088 // we can do.
1089 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1090 // If null, this should be simplified elsewhere. Some of the xforms here
1091 // won't work if the RHS is zero.
1092 if (RHS->isNullValue())
1093 break;
1094
1095 // Figure out what the input bits are. If the top bits of the and result
1096 // are not demanded, then the add doesn't demand them from its input
1097 // either.
1098
1099 // Shift the demanded mask up so that it's at the top of the uint64_t.
1100 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1101 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1102
1103 // If the top bit of the output is demanded, demand everything from the
1104 // input. Otherwise, we demand all the input bits except NLZ top bits.
1105 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1106
1107 // Find information about known zero/one bits in the input.
1108 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1109 KnownZero2, KnownOne2, Depth+1))
1110 return true;
1111
1112 // If the RHS of the add has bits set that can't affect the input, reduce
1113 // the constant.
1114 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1115 return UpdateValueUsesWith(I, I);
1116
1117 // Avoid excess work.
1118 if (KnownZero2 == 0 && KnownOne2 == 0)
1119 break;
1120
1121 // Turn it into OR if input bits are zero.
1122 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1123 Instruction *Or =
1124 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1125 I->getName());
1126 InsertNewInstBefore(Or, *I);
1127 return UpdateValueUsesWith(I, Or);
1128 }
1129
1130 // We can say something about the output known-zero and known-one bits,
1131 // depending on potential carries from the input constant and the
1132 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1133 // bits set and the RHS constant is 0x01001, then we know we have a known
1134 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1135
1136 // To compute this, we first compute the potential carry bits. These are
1137 // the bits which may be modified. I'm not aware of a better way to do
1138 // this scan.
1139 uint64_t RHSVal = RHS->getZExtValue();
1140
1141 bool CarryIn = false;
1142 uint64_t CarryBits = 0;
1143 uint64_t CurBit = 1;
1144 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1145 // Record the current carry in.
1146 if (CarryIn) CarryBits |= CurBit;
1147
1148 bool CarryOut;
1149
1150 // This bit has a carry out unless it is "zero + zero" or
1151 // "zero + anything" with no carry in.
1152 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1153 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1154 } else if (!CarryIn &&
1155 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1156 CarryOut = false; // 0 + anything has no carry out if no carry in.
1157 } else {
1158 // Otherwise, we have to assume we have a carry out.
1159 CarryOut = true;
1160 }
1161
1162 // This stage's carry out becomes the next stage's carry-in.
1163 CarryIn = CarryOut;
1164 }
1165
1166 // Now that we know which bits have carries, compute the known-1/0 sets.
1167
1168 // Bits are known one if they are known zero in one operand and one in the
1169 // other, and there is no input carry.
1170 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1171
1172 // Bits are known zero if they are known zero in both operands and there
1173 // is no input carry.
1174 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1175 }
1176 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001177 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179 uint64_t ShiftAmt = SA->getZExtValue();
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001181 KnownZero, KnownOne, Depth+1))
1182 return true;
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001184 KnownZero <<= ShiftAmt;
1185 KnownOne <<= ShiftAmt;
1186 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001187 }
Chris Lattner2590e512006-02-07 06:56:34 +00001188 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001189 case Instruction::LShr:
1190 // For a logical shift right
1191 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1192 unsigned ShiftAmt = SA->getZExtValue();
1193
1194 // Compute the new bits that are at the top now.
1195 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1196 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1197 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1198 // Unsigned shift right.
1199 if (SimplifyDemandedBits(I->getOperand(0),
1200 (DemandedMask << ShiftAmt) & TypeMask,
1201 KnownZero, KnownOne, Depth+1))
1202 return true;
1203 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1204 KnownZero &= TypeMask;
1205 KnownOne &= TypeMask;
1206 KnownZero >>= ShiftAmt;
1207 KnownOne >>= ShiftAmt;
1208 KnownZero |= HighBits; // high bits known zero.
1209 }
1210 break;
1211 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001212 // If this is an arithmetic shift right and only the low-bit is set, we can
1213 // always convert this into a logical shr, even if the shift amount is
1214 // variable. The low bit of the shift cannot be an input sign bit unless
1215 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001216 if (DemandedMask == 1) {
1217 // Perform the logical shift right.
1218 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1219 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001220 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001221 return UpdateValueUsesWith(I, NewVal);
1222 }
1223
Reid Spencere0fc4df2006-10-20 07:07:24 +00001224 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001226
1227 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001228 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1229 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001230 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001231 // Signed shift right.
1232 if (SimplifyDemandedBits(I->getOperand(0),
1233 (DemandedMask << ShiftAmt) & TypeMask,
1234 KnownZero, KnownOne, Depth+1))
1235 return true;
1236 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1237 KnownZero &= TypeMask;
1238 KnownOne &= TypeMask;
1239 KnownZero >>= ShiftAmt;
1240 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001241
Reid Spencerfdff9382006-11-08 06:47:33 +00001242 // Handle the sign bits.
1243 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1244 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001245
Reid Spencerfdff9382006-11-08 06:47:33 +00001246 // If the input sign bit is known to be zero, or if none of the top bits
1247 // are demanded, turn this into an unsigned shift right.
1248 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1249 // Perform the logical shift right.
1250 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1251 SA, I->getName());
1252 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1253 return UpdateValueUsesWith(I, NewVal);
1254 } else if (KnownOne & SignBit) { // New bits are known one.
1255 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001256 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001257 }
Chris Lattner2590e512006-02-07 06:56:34 +00001258 break;
1259 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001260
1261 // If the client is only demanding bits that we know, return the known
1262 // constant.
1263 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1264 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001265 return false;
1266}
1267
Chris Lattner2deeaea2006-10-05 06:55:50 +00001268
1269/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1270/// 64 or fewer elements. DemandedElts contains the set of elements that are
1271/// actually used by the caller. This method analyzes which elements of the
1272/// operand are undef and returns that information in UndefElts.
1273///
1274/// If the information about demanded elements can be used to simplify the
1275/// operation, the operation is simplified, then the resultant value is
1276/// returned. This returns null if no change was made.
1277Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1278 uint64_t &UndefElts,
1279 unsigned Depth) {
1280 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1281 assert(VWidth <= 64 && "Vector too wide to analyze!");
1282 uint64_t EltMask = ~0ULL >> (64-VWidth);
1283 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1284 "Invalid DemandedElts!");
1285
1286 if (isa<UndefValue>(V)) {
1287 // If the entire vector is undefined, just return this info.
1288 UndefElts = EltMask;
1289 return 0;
1290 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1291 UndefElts = EltMask;
1292 return UndefValue::get(V->getType());
1293 }
1294
1295 UndefElts = 0;
1296 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1297 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1298 Constant *Undef = UndefValue::get(EltTy);
1299
1300 std::vector<Constant*> Elts;
1301 for (unsigned i = 0; i != VWidth; ++i)
1302 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1303 Elts.push_back(Undef);
1304 UndefElts |= (1ULL << i);
1305 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1306 Elts.push_back(Undef);
1307 UndefElts |= (1ULL << i);
1308 } else { // Otherwise, defined.
1309 Elts.push_back(CP->getOperand(i));
1310 }
1311
1312 // If we changed the constant, return it.
1313 Constant *NewCP = ConstantPacked::get(Elts);
1314 return NewCP != CP ? NewCP : 0;
1315 } else if (isa<ConstantAggregateZero>(V)) {
1316 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1317 // set to undef.
1318 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1319 Constant *Zero = Constant::getNullValue(EltTy);
1320 Constant *Undef = UndefValue::get(EltTy);
1321 std::vector<Constant*> Elts;
1322 for (unsigned i = 0; i != VWidth; ++i)
1323 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1324 UndefElts = DemandedElts ^ EltMask;
1325 return ConstantPacked::get(Elts);
1326 }
1327
1328 if (!V->hasOneUse()) { // Other users may use these bits.
1329 if (Depth != 0) { // Not at the root.
1330 // TODO: Just compute the UndefElts information recursively.
1331 return false;
1332 }
1333 return false;
1334 } else if (Depth == 10) { // Limit search depth.
1335 return false;
1336 }
1337
1338 Instruction *I = dyn_cast<Instruction>(V);
1339 if (!I) return false; // Only analyze instructions.
1340
1341 bool MadeChange = false;
1342 uint64_t UndefElts2;
1343 Value *TmpV;
1344 switch (I->getOpcode()) {
1345 default: break;
1346
1347 case Instruction::InsertElement: {
1348 // If this is a variable index, we don't know which element it overwrites.
1349 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001350 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001351 if (Idx == 0) {
1352 // Note that we can't propagate undef elt info, because we don't know
1353 // which elt is getting updated.
1354 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1355 UndefElts2, Depth+1);
1356 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1357 break;
1358 }
1359
1360 // If this is inserting an element that isn't demanded, remove this
1361 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001362 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001363 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1364 return AddSoonDeadInstToWorklist(*I, 0);
1365
1366 // Otherwise, the element inserted overwrites whatever was there, so the
1367 // input demanded set is simpler than the output set.
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1369 DemandedElts & ~(1ULL << IdxNo),
1370 UndefElts, Depth+1);
1371 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372
1373 // The inserted element is defined.
1374 UndefElts |= 1ULL << IdxNo;
1375 break;
1376 }
1377
1378 case Instruction::And:
1379 case Instruction::Or:
1380 case Instruction::Xor:
1381 case Instruction::Add:
1382 case Instruction::Sub:
1383 case Instruction::Mul:
1384 // div/rem demand all inputs, because they don't want divide by zero.
1385 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1386 UndefElts, Depth+1);
1387 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1388 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1389 UndefElts2, Depth+1);
1390 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1391
1392 // Output elements are undefined if both are undefined. Consider things
1393 // like undef&0. The result is known zero, not undef.
1394 UndefElts &= UndefElts2;
1395 break;
1396
1397 case Instruction::Call: {
1398 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1399 if (!II) break;
1400 switch (II->getIntrinsicID()) {
1401 default: break;
1402
1403 // Binary vector operations that work column-wise. A dest element is a
1404 // function of the corresponding input elements from the two inputs.
1405 case Intrinsic::x86_sse_sub_ss:
1406 case Intrinsic::x86_sse_mul_ss:
1407 case Intrinsic::x86_sse_min_ss:
1408 case Intrinsic::x86_sse_max_ss:
1409 case Intrinsic::x86_sse2_sub_sd:
1410 case Intrinsic::x86_sse2_mul_sd:
1411 case Intrinsic::x86_sse2_min_sd:
1412 case Intrinsic::x86_sse2_max_sd:
1413 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1414 UndefElts, Depth+1);
1415 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1416 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1417 UndefElts2, Depth+1);
1418 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1419
1420 // If only the low elt is demanded and this is a scalarizable intrinsic,
1421 // scalarize it now.
1422 if (DemandedElts == 1) {
1423 switch (II->getIntrinsicID()) {
1424 default: break;
1425 case Intrinsic::x86_sse_sub_ss:
1426 case Intrinsic::x86_sse_mul_ss:
1427 case Intrinsic::x86_sse2_sub_sd:
1428 case Intrinsic::x86_sse2_mul_sd:
1429 // TODO: Lower MIN/MAX/ABS/etc
1430 Value *LHS = II->getOperand(1);
1431 Value *RHS = II->getOperand(2);
1432 // Extract the element as scalars.
1433 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1434 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1435
1436 switch (II->getIntrinsicID()) {
1437 default: assert(0 && "Case stmts out of sync!");
1438 case Intrinsic::x86_sse_sub_ss:
1439 case Intrinsic::x86_sse2_sub_sd:
1440 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1441 II->getName()), *II);
1442 break;
1443 case Intrinsic::x86_sse_mul_ss:
1444 case Intrinsic::x86_sse2_mul_sd:
1445 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1446 II->getName()), *II);
1447 break;
1448 }
1449
1450 Instruction *New =
1451 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1452 II->getName());
1453 InsertNewInstBefore(New, *II);
1454 AddSoonDeadInstToWorklist(*II, 0);
1455 return New;
1456 }
1457 }
1458
1459 // Output elements are undefined if both are undefined. Consider things
1460 // like undef&0. The result is known zero, not undef.
1461 UndefElts &= UndefElts2;
1462 break;
1463 }
1464 break;
1465 }
1466 }
1467 return MadeChange ? I : 0;
1468}
1469
Reid Spencer266e42b2006-12-23 06:05:41 +00001470/// @returns true if the specified compare instruction is
1471/// true when both operands are equal...
1472/// @brief Determine if the ICmpInst returns true if both operands are equal
1473static bool isTrueWhenEqual(ICmpInst &ICI) {
1474 ICmpInst::Predicate pred = ICI.getPredicate();
1475 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1476 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1477 pred == ICmpInst::ICMP_SLE;
1478}
1479
1480/// @returns true if the specified compare instruction is
1481/// true when both operands are equal...
1482/// @brief Determine if the FCmpInst returns true if both operands are equal
1483static bool isTrueWhenEqual(FCmpInst &FCI) {
1484 FCmpInst::Predicate pred = FCI.getPredicate();
1485 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1486 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1487 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001488}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001489
1490/// AssociativeOpt - Perform an optimization on an associative operator. This
1491/// function is designed to check a chain of associative operators for a
1492/// potential to apply a certain optimization. Since the optimization may be
1493/// applicable if the expression was reassociated, this checks the chain, then
1494/// reassociates the expression as necessary to expose the optimization
1495/// opportunity. This makes use of a special Functor, which must define
1496/// 'shouldApply' and 'apply' methods.
1497///
1498template<typename Functor>
1499Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1500 unsigned Opcode = Root.getOpcode();
1501 Value *LHS = Root.getOperand(0);
1502
1503 // Quick check, see if the immediate LHS matches...
1504 if (F.shouldApply(LHS))
1505 return F.apply(Root);
1506
1507 // Otherwise, if the LHS is not of the same opcode as the root, return.
1508 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001509 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001510 // Should we apply this transform to the RHS?
1511 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1512
1513 // If not to the RHS, check to see if we should apply to the LHS...
1514 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1515 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1516 ShouldApply = true;
1517 }
1518
1519 // If the functor wants to apply the optimization to the RHS of LHSI,
1520 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1521 if (ShouldApply) {
1522 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001523
Chris Lattnerb8b97502003-08-13 19:01:45 +00001524 // Now all of the instructions are in the current basic block, go ahead
1525 // and perform the reassociation.
1526 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1527
1528 // First move the selected RHS to the LHS of the root...
1529 Root.setOperand(0, LHSI->getOperand(1));
1530
1531 // Make what used to be the LHS of the root be the user of the root...
1532 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001533 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001534 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1535 return 0;
1536 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001537 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001538 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001539 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1540 BasicBlock::iterator ARI = &Root; ++ARI;
1541 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1542 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001543
1544 // Now propagate the ExtraOperand down the chain of instructions until we
1545 // get to LHSI.
1546 while (TmpLHSI != LHSI) {
1547 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001548 // Move the instruction to immediately before the chain we are
1549 // constructing to avoid breaking dominance properties.
1550 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1551 BB->getInstList().insert(ARI, NextLHSI);
1552 ARI = NextLHSI;
1553
Chris Lattnerb8b97502003-08-13 19:01:45 +00001554 Value *NextOp = NextLHSI->getOperand(1);
1555 NextLHSI->setOperand(1, ExtraOperand);
1556 TmpLHSI = NextLHSI;
1557 ExtraOperand = NextOp;
1558 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001559
Chris Lattnerb8b97502003-08-13 19:01:45 +00001560 // Now that the instructions are reassociated, have the functor perform
1561 // the transformation...
1562 return F.apply(Root);
1563 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001564
Chris Lattnerb8b97502003-08-13 19:01:45 +00001565 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1566 }
1567 return 0;
1568}
1569
1570
1571// AddRHS - Implements: X + X --> X << 1
1572struct AddRHS {
1573 Value *RHS;
1574 AddRHS(Value *rhs) : RHS(rhs) {}
1575 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1576 Instruction *apply(BinaryOperator &Add) const {
1577 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1578 ConstantInt::get(Type::UByteTy, 1));
1579 }
1580};
1581
1582// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1583// iff C1&C2 == 0
1584struct AddMaskingAnd {
1585 Constant *C2;
1586 AddMaskingAnd(Constant *c) : C2(c) {}
1587 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001588 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001589 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001590 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001591 }
1592 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001593 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001594 }
1595};
1596
Chris Lattner86102b82005-01-01 16:22:27 +00001597static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001598 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001599 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001600 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001601 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001602
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001603 return IC->InsertNewInstBefore(CastInst::create(
1604 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001605 }
1606
Chris Lattner183b3362004-04-09 19:05:30 +00001607 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001608 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1609 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001610
Chris Lattner183b3362004-04-09 19:05:30 +00001611 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1612 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001613 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1614 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001615 }
1616
1617 Value *Op0 = SO, *Op1 = ConstOperand;
1618 if (!ConstIsRHS)
1619 std::swap(Op0, Op1);
1620 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001621 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1622 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001623 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1624 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1625 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001626 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1627 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001628 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001629 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001630 abort();
1631 }
Chris Lattner86102b82005-01-01 16:22:27 +00001632 return IC->InsertNewInstBefore(New, I);
1633}
1634
1635// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1636// constant as the other operand, try to fold the binary operator into the
1637// select arguments. This also works for Cast instructions, which obviously do
1638// not have a second operand.
1639static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1640 InstCombiner *IC) {
1641 // Don't modify shared select instructions
1642 if (!SI->hasOneUse()) return 0;
1643 Value *TV = SI->getOperand(1);
1644 Value *FV = SI->getOperand(2);
1645
1646 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001647 // Bool selects with constant operands can be folded to logical ops.
1648 if (SI->getType() == Type::BoolTy) return 0;
1649
Chris Lattner86102b82005-01-01 16:22:27 +00001650 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1651 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1652
1653 return new SelectInst(SI->getCondition(), SelectTrueVal,
1654 SelectFalseVal);
1655 }
1656 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001657}
1658
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001659
1660/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1661/// node as operand #0, see if we can fold the instruction into the PHI (which
1662/// is only possible if all operands to the PHI are constants).
1663Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1664 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001665 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001666 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001667
Chris Lattner04689872006-09-09 22:02:56 +00001668 // Check to see if all of the operands of the PHI are constants. If there is
1669 // one non-constant value, remember the BB it is. If there is more than one
1670 // bail out.
1671 BasicBlock *NonConstBB = 0;
1672 for (unsigned i = 0; i != NumPHIValues; ++i)
1673 if (!isa<Constant>(PN->getIncomingValue(i))) {
1674 if (NonConstBB) return 0; // More than one non-const value.
1675 NonConstBB = PN->getIncomingBlock(i);
1676
1677 // If the incoming non-constant value is in I's block, we have an infinite
1678 // loop.
1679 if (NonConstBB == I.getParent())
1680 return 0;
1681 }
1682
1683 // If there is exactly one non-constant value, we can insert a copy of the
1684 // operation in that block. However, if this is a critical edge, we would be
1685 // inserting the computation one some other paths (e.g. inside a loop). Only
1686 // do this if the pred block is unconditionally branching into the phi block.
1687 if (NonConstBB) {
1688 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1689 if (!BI || !BI->isUnconditional()) return 0;
1690 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001691
1692 // Okay, we can do the transformation: create the new PHI node.
1693 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1694 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001695 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001696 InsertNewInstBefore(NewPN, *PN);
1697
1698 // Next, add all of the operands to the PHI.
1699 if (I.getNumOperands() == 2) {
1700 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001701 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001702 Value *InV;
1703 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001704 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1705 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1706 else
1707 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001708 } else {
1709 assert(PN->getIncomingBlock(i) == NonConstBB);
1710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1711 InV = BinaryOperator::create(BO->getOpcode(),
1712 PN->getIncomingValue(i), C, "phitmp",
1713 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001714 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1715 InV = CmpInst::create(CI->getOpcode(),
1716 CI->getPredicate(),
1717 PN->getIncomingValue(i), C, "phitmp",
1718 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001719 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1720 InV = new ShiftInst(SI->getOpcode(),
1721 PN->getIncomingValue(i), C, "phitmp",
1722 NonConstBB->getTerminator());
1723 else
1724 assert(0 && "Unknown binop!");
1725
1726 WorkList.push_back(cast<Instruction>(InV));
1727 }
1728 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001729 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001730 } else {
1731 CastInst *CI = cast<CastInst>(&I);
1732 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001733 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001734 Value *InV;
1735 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001736 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001737 } else {
1738 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001739 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1740 I.getType(), "phitmp",
1741 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001742 WorkList.push_back(cast<Instruction>(InV));
1743 }
1744 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001745 }
1746 }
1747 return ReplaceInstUsesWith(I, NewPN);
1748}
1749
Chris Lattner113f4f42002-06-25 16:13:24 +00001750Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001751 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001752 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001753
Chris Lattnercf4a9962004-04-10 22:01:55 +00001754 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001755 // X + undef -> undef
1756 if (isa<UndefValue>(RHS))
1757 return ReplaceInstUsesWith(I, RHS);
1758
Chris Lattnercf4a9962004-04-10 22:01:55 +00001759 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001760 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001761 if (RHSC->isNullValue())
1762 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001763 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1764 if (CFP->isExactlyValue(-0.0))
1765 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001766 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001767
Chris Lattnercf4a9962004-04-10 22:01:55 +00001768 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001769 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001770 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001771 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001772 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001773
1774 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1775 // (X & 254)+1 -> (X&254)|1
1776 uint64_t KnownZero, KnownOne;
1777 if (!isa<PackedType>(I.getType()) &&
1778 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1779 KnownZero, KnownOne))
1780 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001781 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001782
1783 if (isa<PHINode>(LHS))
1784 if (Instruction *NV = FoldOpIntoPhi(I))
1785 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001786
Chris Lattner330628a2006-01-06 17:59:59 +00001787 ConstantInt *XorRHS = 0;
1788 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001789 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1790 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1791 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1792 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1793
1794 uint64_t C0080Val = 1ULL << 31;
1795 int64_t CFF80Val = -C0080Val;
1796 unsigned Size = 32;
1797 do {
1798 if (TySizeBits > Size) {
1799 bool Found = false;
1800 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1801 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1802 if (RHSSExt == CFF80Val) {
1803 if (XorRHS->getZExtValue() == C0080Val)
1804 Found = true;
1805 } else if (RHSZExt == C0080Val) {
1806 if (XorRHS->getSExtValue() == CFF80Val)
1807 Found = true;
1808 }
1809 if (Found) {
1810 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001811 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001812 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001813 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001814 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001815 Size = 0; // Not a sign ext, but can't be any others either.
1816 goto FoundSExt;
1817 }
1818 }
1819 Size >>= 1;
1820 C0080Val >>= Size;
1821 CFF80Val >>= Size;
1822 } while (Size >= 8);
1823
1824FoundSExt:
1825 const Type *MiddleType = 0;
1826 switch (Size) {
1827 default: break;
1828 case 32: MiddleType = Type::IntTy; break;
1829 case 16: MiddleType = Type::ShortTy; break;
1830 case 8: MiddleType = Type::SByteTy; break;
1831 }
1832 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001833 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001834 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001835 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001836 }
1837 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001838 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001839
Chris Lattnerb8b97502003-08-13 19:01:45 +00001840 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001841 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001842 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001843
1844 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1845 if (RHSI->getOpcode() == Instruction::Sub)
1846 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1847 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1848 }
1849 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1850 if (LHSI->getOpcode() == Instruction::Sub)
1851 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1852 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1853 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001854 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001855
Chris Lattner147e9752002-05-08 22:46:53 +00001856 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001857 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001858 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001859
1860 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001861 if (!isa<Constant>(RHS))
1862 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001863 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001864
Misha Brukmanb1c93172005-04-21 23:48:37 +00001865
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001866 ConstantInt *C2;
1867 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1868 if (X == RHS) // X*C + X --> X * (C+1)
1869 return BinaryOperator::createMul(RHS, AddOne(C2));
1870
1871 // X*C1 + X*C2 --> X * (C1+C2)
1872 ConstantInt *C1;
1873 if (X == dyn_castFoldableMul(RHS, C1))
1874 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001875 }
1876
1877 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001878 if (dyn_castFoldableMul(RHS, C2) == LHS)
1879 return BinaryOperator::createMul(LHS, AddOne(C2));
1880
Chris Lattner57c8d992003-02-18 19:57:07 +00001881
Chris Lattnerb8b97502003-08-13 19:01:45 +00001882 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001883 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001884 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001885
Chris Lattnerb9cde762003-10-02 15:11:26 +00001886 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001887 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001888 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1889 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1890 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001891 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001892
Chris Lattnerbff91d92004-10-08 05:07:56 +00001893 // (X & FF00) + xx00 -> (X+xx00) & FF00
1894 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1895 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1896 if (Anded == CRHS) {
1897 // See if all bits from the first bit set in the Add RHS up are included
1898 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001899 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001900
1901 // Form a mask of all bits from the lowest bit added through the top.
1902 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001903 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001904
1905 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001906 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001907
Chris Lattnerbff91d92004-10-08 05:07:56 +00001908 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1909 // Okay, the xform is safe. Insert the new add pronto.
1910 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1911 LHS->getName()), I);
1912 return BinaryOperator::createAnd(NewAdd, C2);
1913 }
1914 }
1915 }
1916
Chris Lattnerd4252a72004-07-30 07:50:03 +00001917 // Try to fold constant add into select arguments.
1918 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001919 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001920 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001921 }
1922
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001923 // add (cast *A to intptrtype) B ->
1924 // cast (GEP (cast *A to sbyte*) B) ->
1925 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001926 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001927 CastInst *CI = dyn_cast<CastInst>(LHS);
1928 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001929 if (!CI) {
1930 CI = dyn_cast<CastInst>(RHS);
1931 Other = LHS;
1932 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001933 if (CI && CI->getType()->isSized() &&
1934 (CI->getType()->getPrimitiveSize() ==
1935 TD->getIntPtrType()->getPrimitiveSize())
1936 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001937 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001938 PointerType::get(Type::SByteTy), I);
1939 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001940 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001941 }
1942 }
1943
Chris Lattner113f4f42002-06-25 16:13:24 +00001944 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001945}
1946
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001947// isSignBit - Return true if the value represented by the constant only has the
1948// highest order bit set.
1949static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001950 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001951 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001952}
1953
Chris Lattner022167f2004-03-13 00:11:49 +00001954/// RemoveNoopCast - Strip off nonconverting casts from the value.
1955///
1956static Value *RemoveNoopCast(Value *V) {
1957 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1958 const Type *CTy = CI->getType();
1959 const Type *OpTy = CI->getOperand(0)->getType();
1960 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001961 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001962 return RemoveNoopCast(CI->getOperand(0));
1963 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1964 return RemoveNoopCast(CI->getOperand(0));
1965 }
1966 return V;
1967}
1968
Chris Lattner113f4f42002-06-25 16:13:24 +00001969Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001971
Chris Lattnere6794492002-08-12 21:17:25 +00001972 if (Op0 == Op1) // sub X, X -> 0
1973 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001974
Chris Lattnere6794492002-08-12 21:17:25 +00001975 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001976 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001977 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001978
Chris Lattner81a7a232004-10-16 18:11:37 +00001979 if (isa<UndefValue>(Op0))
1980 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1981 if (isa<UndefValue>(Op1))
1982 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1983
Chris Lattner8f2f5982003-11-05 01:06:05 +00001984 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1985 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001986 if (C->isAllOnesValue())
1987 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001988
Chris Lattner8f2f5982003-11-05 01:06:05 +00001989 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001990 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001991 if (match(Op1, m_Not(m_Value(X))))
1992 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001993 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001994 // -((uint)X >> 31) -> ((int)X >> 31)
1995 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001996 if (C->isNullValue()) {
1997 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1998 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001999 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002000 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002001 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002002 if (CU->getZExtValue() ==
2003 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002004 // Ok, the transformation is safe. Insert AShr.
2005 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2006 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002007 }
2008 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002009 }
2010 else if (SI->getOpcode() == Instruction::AShr) {
2011 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2012 // Check to see if we are shifting out everything but the sign bit.
2013 if (CU->getZExtValue() ==
2014 SI->getType()->getPrimitiveSizeInBits()-1) {
2015 // Ok, the transformation is safe. Insert LShr.
2016 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2017 CU, SI->getName());
2018 }
2019 }
2020 }
Chris Lattner022167f2004-03-13 00:11:49 +00002021 }
Chris Lattner183b3362004-04-09 19:05:30 +00002022
2023 // Try to fold constant sub into select arguments.
2024 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002025 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002026 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002027
2028 if (isa<PHINode>(Op0))
2029 if (Instruction *NV = FoldOpIntoPhi(I))
2030 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002031 }
2032
Chris Lattnera9be4492005-04-07 16:15:25 +00002033 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2034 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002035 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002036 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002037 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002038 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002039 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002040 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2041 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2042 // C1-(X+C2) --> (C1-C2)-X
2043 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2044 Op1I->getOperand(0));
2045 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002046 }
2047
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002048 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002049 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2050 // is not used by anyone else...
2051 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002052 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002053 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002054 // Swap the two operands of the subexpr...
2055 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2056 Op1I->setOperand(0, IIOp1);
2057 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002058
Chris Lattner3082c5a2003-02-18 19:28:33 +00002059 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002060 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002061 }
2062
2063 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2064 //
2065 if (Op1I->getOpcode() == Instruction::And &&
2066 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2067 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2068
Chris Lattner396dbfe2004-06-09 05:08:07 +00002069 Value *NewNot =
2070 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002071 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002072 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002073
Reid Spencer3c514952006-10-16 23:08:08 +00002074 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002075 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002076 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002077 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002078 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002079 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002080 ConstantExpr::getNeg(DivRHS));
2081
Chris Lattner57c8d992003-02-18 19:57:07 +00002082 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002083 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002084 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002085 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002086 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002087 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002088 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002089 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002090 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002091
Chris Lattner7a002fe2006-12-02 00:13:08 +00002092 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002093 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2094 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002095 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2096 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2097 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2098 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002099 } else if (Op0I->getOpcode() == Instruction::Sub) {
2100 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2101 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002102 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002103
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002104 ConstantInt *C1;
2105 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2106 if (X == Op1) { // X*C - X --> X * (C-1)
2107 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2108 return BinaryOperator::createMul(Op1, CP1);
2109 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002110
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002111 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2112 if (X == dyn_castFoldableMul(Op1, C2))
2113 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2114 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002115 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002116}
2117
Reid Spencer266e42b2006-12-23 06:05:41 +00002118/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002119/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002120static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2121 switch (pred) {
2122 case ICmpInst::ICMP_SLT:
2123 // True if LHS s< RHS and RHS == 0
2124 return RHS->isNullValue();
2125 case ICmpInst::ICMP_SLE:
2126 // True if LHS s<= RHS and RHS == -1
2127 return RHS->isAllOnesValue();
2128 case ICmpInst::ICMP_UGE:
2129 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2130 return RHS->getZExtValue() == (1ULL <<
2131 (RHS->getType()->getPrimitiveSizeInBits()-1));
2132 case ICmpInst::ICMP_UGT:
2133 // True if LHS u> RHS and RHS == high-bit-mask - 1
2134 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002135 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002136 default:
2137 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002138 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002139}
2140
Chris Lattner113f4f42002-06-25 16:13:24 +00002141Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002142 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002143 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002144
Chris Lattner81a7a232004-10-16 18:11:37 +00002145 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2147
Chris Lattnere6794492002-08-12 21:17:25 +00002148 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002149 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2150 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002151
2152 // ((X << C1)*C2) == (X * (C2 << C1))
2153 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2154 if (SI->getOpcode() == Instruction::Shl)
2155 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002156 return BinaryOperator::createMul(SI->getOperand(0),
2157 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002158
Chris Lattnercce81be2003-09-11 22:24:54 +00002159 if (CI->isNullValue())
2160 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2161 if (CI->equalsInt(1)) // X * 1 == X
2162 return ReplaceInstUsesWith(I, Op0);
2163 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002164 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002165
Reid Spencere0fc4df2006-10-20 07:07:24 +00002166 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002167 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2168 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002169 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002170 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002171 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002172 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002173 if (Op1F->isNullValue())
2174 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002175
Chris Lattner3082c5a2003-02-18 19:28:33 +00002176 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2177 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2178 if (Op1F->getValue() == 1.0)
2179 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2180 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002181
2182 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2183 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2184 isa<ConstantInt>(Op0I->getOperand(1))) {
2185 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2186 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2187 Op1, "tmp");
2188 InsertNewInstBefore(Add, I);
2189 Value *C1C2 = ConstantExpr::getMul(Op1,
2190 cast<Constant>(Op0I->getOperand(1)));
2191 return BinaryOperator::createAdd(Add, C1C2);
2192
2193 }
Chris Lattner183b3362004-04-09 19:05:30 +00002194
2195 // Try to fold constant mul into select arguments.
2196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002198 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002199
2200 if (isa<PHINode>(Op0))
2201 if (Instruction *NV = FoldOpIntoPhi(I))
2202 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002203 }
2204
Chris Lattner934a64cf2003-03-10 23:23:04 +00002205 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2206 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002207 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002208
Chris Lattner2635b522004-02-23 05:39:21 +00002209 // If one of the operands of the multiply is a cast from a boolean value, then
2210 // we know the bool is either zero or one, so this is a 'masking' multiply.
2211 // See if we can simplify things based on how the boolean was originally
2212 // formed.
2213 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002214 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2215 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002216 BoolCast = CI;
2217 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002218 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2219 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002220 BoolCast = CI;
2221 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002222 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002223 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2224 const Type *SCOpTy = SCIOp0->getType();
2225
Reid Spencer266e42b2006-12-23 06:05:41 +00002226 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002227 // multiply into a shift/and combination.
2228 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002229 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002230 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002231 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002232 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002233 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002234 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002235 BoolCast->getOperand(0)->getName()+
2236 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002237
2238 // If the multiply type is not the same as the source type, sign extend
2239 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002240 if (I.getType() != V->getType()) {
2241 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2242 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2243 Instruction::CastOps opcode =
2244 (SrcBits == DstBits ? Instruction::BitCast :
2245 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2246 V = InsertCastBefore(opcode, V, I.getType(), I);
2247 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002248
Chris Lattner2635b522004-02-23 05:39:21 +00002249 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002250 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002251 }
2252 }
2253 }
2254
Chris Lattner113f4f42002-06-25 16:13:24 +00002255 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002256}
2257
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002258/// This function implements the transforms on div instructions that work
2259/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2260/// used by the visitors to those instructions.
2261/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002262Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002263 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002264
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002265 // undef / X -> 0
2266 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002267 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002268
2269 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002270 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002272
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002273 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002274 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2275 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276 // same basic block, then we replace the select with Y, and the condition
2277 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002278 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002280 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2281 if (ST->isNullValue()) {
2282 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2283 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002284 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002285 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2286 I.setOperand(1, SI->getOperand(2));
2287 else
2288 UpdateValueUsesWith(SI, SI->getOperand(2));
2289 return &I;
2290 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002291
Chris Lattnerd79dc792006-09-09 20:26:32 +00002292 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2293 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2294 if (ST->isNullValue()) {
2295 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2296 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002297 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002298 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2299 I.setOperand(1, SI->getOperand(1));
2300 else
2301 UpdateValueUsesWith(SI, SI->getOperand(1));
2302 return &I;
2303 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002304 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002305
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002306 return 0;
2307}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002308
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309/// This function implements the transforms common to both integer division
2310/// instructions (udiv and sdiv). It is called by the visitors to those integer
2311/// division instructions.
2312/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002313Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315
2316 if (Instruction *Common = commonDivTransforms(I))
2317 return Common;
2318
2319 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2320 // div X, 1 == X
2321 if (RHS->equalsInt(1))
2322 return ReplaceInstUsesWith(I, Op0);
2323
2324 // (X / C1) / C2 -> X / (C1*C2)
2325 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2326 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2327 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2328 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2329 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002330 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002331
2332 if (!RHS->isNullValue()) { // avoid X udiv 0
2333 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2334 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2335 return R;
2336 if (isa<PHINode>(Op0))
2337 if (Instruction *NV = FoldOpIntoPhi(I))
2338 return NV;
2339 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002340 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002341
Chris Lattner3082c5a2003-02-18 19:28:33 +00002342 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002343 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002344 if (LHS->equalsInt(0))
2345 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2346
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002347 return 0;
2348}
2349
2350Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2351 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2352
2353 // Handle the integer div common cases
2354 if (Instruction *Common = commonIDivTransforms(I))
2355 return Common;
2356
2357 // X udiv C^2 -> X >> C
2358 // Check to see if this is an unsigned division with an exact power of 2,
2359 // if so, convert to a right shift.
2360 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2361 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2362 if (isPowerOf2_64(Val)) {
2363 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002364 return new ShiftInst(Instruction::LShr, Op0,
2365 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366 }
2367 }
2368
2369 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2370 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2371 if (RHSI->getOpcode() == Instruction::Shl &&
2372 isa<ConstantInt>(RHSI->getOperand(0))) {
2373 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2374 if (isPowerOf2_64(C1)) {
2375 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002376 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002378 Constant *C2V = ConstantInt::get(NTy, C2);
2379 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002380 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002381 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002382 }
2383 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002384 }
2385
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2387 // where C1&C2 are powers of two.
2388 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2389 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2390 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2391 if (!STO->isNullValue() && !STO->isNullValue()) {
2392 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2393 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2394 // Compute the shift amounts
2395 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002396 // Construct the "on true" case of the select
2397 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2398 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002399 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002400 TSI = InsertNewInstBefore(TSI, I);
2401
2402 // Construct the "on false" case of the select
2403 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2404 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002405 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002406 FSI = InsertNewInstBefore(FSI, I);
2407
2408 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002409 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002410 }
2411 }
2412 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002413 return 0;
2414}
2415
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2418
2419 // Handle the integer div common cases
2420 if (Instruction *Common = commonIDivTransforms(I))
2421 return Common;
2422
2423 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2424 // sdiv X, -1 == -X
2425 if (RHS->isAllOnesValue())
2426 return BinaryOperator::createNeg(Op0);
2427
2428 // -X/C -> X/-C
2429 if (Value *LHSNeg = dyn_castNegVal(Op0))
2430 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2431 }
2432
2433 // If the sign bits of both operands are zero (i.e. we can prove they are
2434 // unsigned inputs), turn this into a udiv.
2435 if (I.getType()->isInteger()) {
2436 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2437 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2438 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2439 }
2440 }
2441
2442 return 0;
2443}
2444
2445Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2446 return commonDivTransforms(I);
2447}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002448
Chris Lattner85dda9a2006-03-02 06:50:58 +00002449/// GetFactor - If we can prove that the specified value is at least a multiple
2450/// of some factor, return that factor.
2451static Constant *GetFactor(Value *V) {
2452 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2453 return CI;
2454
2455 // Unless we can be tricky, we know this is a multiple of 1.
2456 Constant *Result = ConstantInt::get(V->getType(), 1);
2457
2458 Instruction *I = dyn_cast<Instruction>(V);
2459 if (!I) return Result;
2460
2461 if (I->getOpcode() == Instruction::Mul) {
2462 // Handle multiplies by a constant, etc.
2463 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2464 GetFactor(I->getOperand(1)));
2465 } else if (I->getOpcode() == Instruction::Shl) {
2466 // (X<<C) -> X * (1 << C)
2467 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2468 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2469 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2470 }
2471 } else if (I->getOpcode() == Instruction::And) {
2472 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2473 // X & 0xFFF0 is known to be a multiple of 16.
2474 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2475 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2476 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002477 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002478 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002479 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002480 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002481 if (!CI->isIntegerCast())
2482 return Result;
2483 Value *Op = CI->getOperand(0);
2484 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002485 }
2486 return Result;
2487}
2488
Reid Spencer7eb55b32006-11-02 01:53:59 +00002489/// This function implements the transforms on rem instructions that work
2490/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2491/// is used by the visitors to those instructions.
2492/// @brief Transforms common to all three rem instructions
2493Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002495
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002496 // 0 % X == 0, we don't need to preserve faults!
2497 if (Constant *LHS = dyn_cast<Constant>(Op0))
2498 if (LHS->isNullValue())
2499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500
2501 if (isa<UndefValue>(Op0)) // undef % X -> 0
2502 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2503 if (isa<UndefValue>(Op1))
2504 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002505
2506 // Handle cases involving: rem X, (select Cond, Y, Z)
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2508 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2509 // the same basic block, then we replace the select with Y, and the
2510 // condition of the select with false (if the cond value is in the same
2511 // BB). If the select has uses other than the div, this allows them to be
2512 // simplified also.
2513 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2514 if (ST->isNullValue()) {
2515 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2516 if (CondI && CondI->getParent() == I.getParent())
2517 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2518 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2519 I.setOperand(1, SI->getOperand(2));
2520 else
2521 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002522 return &I;
2523 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002524 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2525 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2526 if (ST->isNullValue()) {
2527 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2528 if (CondI && CondI->getParent() == I.getParent())
2529 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2530 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2531 I.setOperand(1, SI->getOperand(1));
2532 else
2533 UpdateValueUsesWith(SI, SI->getOperand(1));
2534 return &I;
2535 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002536 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002537
Reid Spencer7eb55b32006-11-02 01:53:59 +00002538 return 0;
2539}
2540
2541/// This function implements the transforms common to both integer remainder
2542/// instructions (urem and srem). It is called by the visitors to those integer
2543/// remainder instructions.
2544/// @brief Common integer remainder transforms
2545Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2547
2548 if (Instruction *common = commonRemTransforms(I))
2549 return common;
2550
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002551 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002552 // X % 0 == undef, we don't need to preserve faults!
2553 if (RHS->equalsInt(0))
2554 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2555
Chris Lattner3082c5a2003-02-18 19:28:33 +00002556 if (RHS->equalsInt(1)) // X % 1 == 0
2557 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2558
Chris Lattnerb70f1412006-02-28 05:49:21 +00002559 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2560 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2561 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2562 return R;
2563 } else if (isa<PHINode>(Op0I)) {
2564 if (Instruction *NV = FoldOpIntoPhi(I))
2565 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002566 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002567 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2568 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002570 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002571 }
2572
Reid Spencer7eb55b32006-11-02 01:53:59 +00002573 return 0;
2574}
2575
2576Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578
2579 if (Instruction *common = commonIRemTransforms(I))
2580 return common;
2581
2582 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2583 // X urem C^2 -> X and C
2584 // Check to see if this is an unsigned remainder with an exact power of 2,
2585 // if so, convert to a bitwise and.
2586 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2587 if (isPowerOf2_64(C->getZExtValue()))
2588 return BinaryOperator::createAnd(Op0, SubOne(C));
2589 }
2590
Chris Lattner2e90b732006-02-05 07:54:04 +00002591 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002592 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2593 if (RHSI->getOpcode() == Instruction::Shl &&
2594 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002595 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002596 if (isPowerOf2_64(C1)) {
2597 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2598 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2599 "tmp"), I);
2600 return BinaryOperator::createAnd(Op0, Add);
2601 }
2602 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002603 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002604
Reid Spencer7eb55b32006-11-02 01:53:59 +00002605 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2606 // where C1&C2 are powers of two.
2607 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2608 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2609 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2610 // STO == 0 and SFO == 0 handled above.
2611 if (isPowerOf2_64(STO->getZExtValue()) &&
2612 isPowerOf2_64(SFO->getZExtValue())) {
2613 Value *TrueAnd = InsertNewInstBefore(
2614 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2615 Value *FalseAnd = InsertNewInstBefore(
2616 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2617 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2618 }
2619 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002620 }
2621
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002622 return 0;
2623}
2624
Reid Spencer7eb55b32006-11-02 01:53:59 +00002625Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2626 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2627
2628 if (Instruction *common = commonIRemTransforms(I))
2629 return common;
2630
2631 if (Value *RHSNeg = dyn_castNegVal(Op1))
2632 if (!isa<ConstantInt>(RHSNeg) ||
2633 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2634 // X % -Y -> X % Y
2635 AddUsesToWorkList(I);
2636 I.setOperand(1, RHSNeg);
2637 return &I;
2638 }
2639
2640 // If the top bits of both operands are zero (i.e. we can prove they are
2641 // unsigned inputs), turn this into a urem.
2642 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2643 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2644 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2645 return BinaryOperator::createURem(Op0, Op1, I.getName());
2646 }
2647
2648 return 0;
2649}
2650
2651Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002652 return commonRemTransforms(I);
2653}
2654
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002655// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002656static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2657 if (isSigned) {
2658 // Calculate 0111111111..11111
2659 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2660 int64_t Val = INT64_MAX; // All ones
2661 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2662 return C->getSExtValue() == Val-1;
2663 }
2664 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002665}
2666
2667// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002668static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2669 if (isSigned) {
2670 // Calculate 1111111111000000000000
2671 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2672 int64_t Val = -1; // All ones
2673 Val <<= TypeBits-1; // Shift over to the right spot
2674 return C->getSExtValue() == Val+1;
2675 }
2676 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002677}
2678
Chris Lattner35167c32004-06-09 07:59:58 +00002679// isOneBitSet - Return true if there is exactly one bit set in the specified
2680// constant.
2681static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002682 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002683 return V && (V & (V-1)) == 0;
2684}
2685
Chris Lattner8fc5af42004-09-23 21:46:38 +00002686#if 0 // Currently unused
2687// isLowOnes - Return true if the constant is of the form 0+1+.
2688static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002689 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002690
2691 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002692 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002693
2694 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2695 return U && V && (U & V) == 0;
2696}
2697#endif
2698
2699// isHighOnes - Return true if the constant is of the form 1+0+.
2700// This is the same as lowones(~X).
2701static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002702 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002703 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002704
2705 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002706 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002707
2708 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2709 return U && V && (U & V) == 0;
2710}
2711
Reid Spencer266e42b2006-12-23 06:05:41 +00002712/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002713/// are carefully arranged to allow folding of expressions such as:
2714///
2715/// (A < B) | (A > B) --> (A != B)
2716///
Reid Spencer266e42b2006-12-23 06:05:41 +00002717/// Note that this is only valid if the first and second predicates have the
2718/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002719///
Reid Spencer266e42b2006-12-23 06:05:41 +00002720/// Three bits are used to represent the condition, as follows:
2721/// 0 A > B
2722/// 1 A == B
2723/// 2 A < B
2724///
2725/// <=> Value Definition
2726/// 000 0 Always false
2727/// 001 1 A > B
2728/// 010 2 A == B
2729/// 011 3 A >= B
2730/// 100 4 A < B
2731/// 101 5 A != B
2732/// 110 6 A <= B
2733/// 111 7 Always true
2734///
2735static unsigned getICmpCode(const ICmpInst *ICI) {
2736 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002737 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002738 case ICmpInst::ICMP_UGT: return 1; // 001
2739 case ICmpInst::ICMP_SGT: return 1; // 001
2740 case ICmpInst::ICMP_EQ: return 2; // 010
2741 case ICmpInst::ICMP_UGE: return 3; // 011
2742 case ICmpInst::ICMP_SGE: return 3; // 011
2743 case ICmpInst::ICMP_ULT: return 4; // 100
2744 case ICmpInst::ICMP_SLT: return 4; // 100
2745 case ICmpInst::ICMP_NE: return 5; // 101
2746 case ICmpInst::ICMP_ULE: return 6; // 110
2747 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002748 // True -> 7
2749 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002750 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002751 return 0;
2752 }
2753}
2754
Reid Spencer266e42b2006-12-23 06:05:41 +00002755/// getICmpValue - This is the complement of getICmpCode, which turns an
2756/// opcode and two operands into either a constant true or false, or a brand
2757/// new /// ICmp instruction. The sign is passed in to determine which kind
2758/// of predicate to use in new icmp instructions.
2759static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2760 switch (code) {
2761 default: assert(0 && "Illegal ICmp code!");
2762 case 0: return ConstantBool::getFalse();
2763 case 1:
2764 if (sign)
2765 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2766 else
2767 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2768 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2769 case 3:
2770 if (sign)
2771 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2772 else
2773 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2774 case 4:
2775 if (sign)
2776 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2777 else
2778 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2779 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2780 case 6:
2781 if (sign)
2782 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2783 else
2784 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2785 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002786 }
2787}
2788
Reid Spencer266e42b2006-12-23 06:05:41 +00002789static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2790 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2791 (ICmpInst::isSignedPredicate(p1) &&
2792 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2793 (ICmpInst::isSignedPredicate(p2) &&
2794 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2795}
2796
2797namespace {
2798// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2799struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002800 InstCombiner &IC;
2801 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002802 ICmpInst::Predicate pred;
2803 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2804 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2805 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002806 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002807 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2808 if (PredicatesFoldable(pred, ICI->getPredicate()))
2809 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2810 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002811 return false;
2812 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002813 Instruction *apply(Instruction &Log) const {
2814 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2815 if (ICI->getOperand(0) != LHS) {
2816 assert(ICI->getOperand(1) == LHS);
2817 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002818 }
2819
Reid Spencer266e42b2006-12-23 06:05:41 +00002820 unsigned LHSCode = getICmpCode(ICI);
2821 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002822 unsigned Code;
2823 switch (Log.getOpcode()) {
2824 case Instruction::And: Code = LHSCode & RHSCode; break;
2825 case Instruction::Or: Code = LHSCode | RHSCode; break;
2826 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002827 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002828 }
2829
Reid Spencer266e42b2006-12-23 06:05:41 +00002830 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002831 if (Instruction *I = dyn_cast<Instruction>(RV))
2832 return I;
2833 // Otherwise, it's a constant boolean value...
2834 return IC.ReplaceInstUsesWith(Log, RV);
2835 }
2836};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002837} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002838
Chris Lattnerba1cb382003-09-19 17:17:26 +00002839// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2840// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2841// guaranteed to be either a shift instruction or a binary operator.
2842Instruction *InstCombiner::OptAndOp(Instruction *Op,
2843 ConstantIntegral *OpRHS,
2844 ConstantIntegral *AndRHS,
2845 BinaryOperator &TheAnd) {
2846 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002847 Constant *Together = 0;
2848 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002849 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002850
Chris Lattnerba1cb382003-09-19 17:17:26 +00002851 switch (Op->getOpcode()) {
2852 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002853 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002854 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2855 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002856 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002857 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002858 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002859 }
2860 break;
2861 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002862 if (Together == AndRHS) // (X | C) & C --> C
2863 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002864
Chris Lattner86102b82005-01-01 16:22:27 +00002865 if (Op->hasOneUse() && Together != OpRHS) {
2866 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2867 std::string Op0Name = Op->getName(); Op->setName("");
2868 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2869 InsertNewInstBefore(Or, TheAnd);
2870 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002871 }
2872 break;
2873 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002874 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002875 // Adding a one to a single bit bit-field should be turned into an XOR
2876 // of the bit. First thing to check is to see if this AND is with a
2877 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002878 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002879
2880 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002881 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002882
2883 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002884 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002885 // Ok, at this point, we know that we are masking the result of the
2886 // ADD down to exactly one bit. If the constant we are adding has
2887 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002888 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002889
Chris Lattnerba1cb382003-09-19 17:17:26 +00002890 // Check to see if any bits below the one bit set in AndRHSV are set.
2891 if ((AddRHS & (AndRHSV-1)) == 0) {
2892 // If not, the only thing that can effect the output of the AND is
2893 // the bit specified by AndRHSV. If that bit is set, the effect of
2894 // the XOR is to toggle the bit. If it is clear, then the ADD has
2895 // no effect.
2896 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2897 TheAnd.setOperand(0, X);
2898 return &TheAnd;
2899 } else {
2900 std::string Name = Op->getName(); Op->setName("");
2901 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002902 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002903 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002904 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002905 }
2906 }
2907 }
2908 }
2909 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002910
2911 case Instruction::Shl: {
2912 // We know that the AND will not produce any of the bits shifted in, so if
2913 // the anded constant includes them, clear them now!
2914 //
2915 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002916 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2917 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002918
Chris Lattner7e794272004-09-24 15:21:34 +00002919 if (CI == ShlMask) { // Masking out bits that the shift already masks
2920 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2921 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002922 TheAnd.setOperand(1, CI);
2923 return &TheAnd;
2924 }
2925 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002926 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002927 case Instruction::LShr:
2928 {
Chris Lattner2da29172003-09-19 19:05:02 +00002929 // We know that the AND will not produce any of the bits shifted in, so if
2930 // the anded constant includes them, clear them now! This only applies to
2931 // unsigned shifts, because a signed shr may bring in set bits!
2932 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002933 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2934 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2935 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002936
Reid Spencerfdff9382006-11-08 06:47:33 +00002937 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2938 return ReplaceInstUsesWith(TheAnd, Op);
2939 } else if (CI != AndRHS) {
2940 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2941 return &TheAnd;
2942 }
2943 break;
2944 }
2945 case Instruction::AShr:
2946 // Signed shr.
2947 // See if this is shifting in some sign extension, then masking it out
2948 // with an and.
2949 if (Op->hasOneUse()) {
2950 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2951 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002952 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2953 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002954 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002955 // Make the argument unsigned.
2956 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002957 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2958 OpRHS, Op->getName()), TheAnd);
2959 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002960 }
Chris Lattner2da29172003-09-19 19:05:02 +00002961 }
2962 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002963 }
2964 return 0;
2965}
2966
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002967
Chris Lattner6862fbd2004-09-29 17:40:11 +00002968/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2969/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002970/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2971/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002972/// insert new instructions.
2973Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002974 bool isSigned, bool Inside,
2975 Instruction &IB) {
2976 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2977 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002978 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002979
Chris Lattner6862fbd2004-09-29 17:40:11 +00002980 if (Inside) {
2981 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002982 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002983
Reid Spencer266e42b2006-12-23 06:05:41 +00002984 // V >= Min && V < Hi --> V < Hi
2985 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2986 ICmpInst::Predicate pred = (isSigned ?
2987 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2988 return new ICmpInst(pred, V, Hi);
2989 }
2990
2991 // Emit V-Lo <u Hi-Lo
2992 Constant *NegLo = ConstantExpr::getNeg(Lo);
2993 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002994 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002995 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2996 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002997 }
2998
2999 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003000 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003001
Reid Spencer266e42b2006-12-23 06:05:41 +00003002 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003003 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencer266e42b2006-12-23 06:05:41 +00003004 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3005 ICmpInst::Predicate pred = (isSigned ?
3006 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3007 return new ICmpInst(pred, V, Hi);
3008 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003009
Reid Spencer266e42b2006-12-23 06:05:41 +00003010 // Emit V-Lo > Hi-1-Lo
3011 Constant *NegLo = ConstantExpr::getNeg(Lo);
3012 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003013 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003014 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3015 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003016}
3017
Chris Lattnerb4b25302005-09-18 07:22:02 +00003018// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3019// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3020// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3021// not, since all 1s are not contiguous.
3022static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003023 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003024 if (!isShiftedMask_64(V)) return false;
3025
3026 // look for the first zero bit after the run of ones
3027 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3028 // look for the first non-zero bit
3029 ME = 64-CountLeadingZeros_64(V);
3030 return true;
3031}
3032
3033
3034
3035/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3036/// where isSub determines whether the operator is a sub. If we can fold one of
3037/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003038///
3039/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3040/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3041/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3042///
3043/// return (A +/- B).
3044///
3045Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3046 ConstantIntegral *Mask, bool isSub,
3047 Instruction &I) {
3048 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3049 if (!LHSI || LHSI->getNumOperands() != 2 ||
3050 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3051
3052 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3053
3054 switch (LHSI->getOpcode()) {
3055 default: return 0;
3056 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003057 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3058 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003059 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003060 break;
3061
3062 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3063 // part, we don't need any explicit masks to take them out of A. If that
3064 // is all N is, ignore it.
3065 unsigned MB, ME;
3066 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003067 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3068 Mask >>= 64-MB+1;
3069 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003070 break;
3071 }
3072 }
Chris Lattneraf517572005-09-18 04:24:45 +00003073 return 0;
3074 case Instruction::Or:
3075 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003076 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003077 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003078 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003079 break;
3080 return 0;
3081 }
3082
3083 Instruction *New;
3084 if (isSub)
3085 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3086 else
3087 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3088 return InsertNewInstBefore(New, I);
3089}
3090
Chris Lattner113f4f42002-06-25 16:13:24 +00003091Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003092 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003093 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003094
Chris Lattner81a7a232004-10-16 18:11:37 +00003095 if (isa<UndefValue>(Op1)) // X & undef -> 0
3096 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3097
Chris Lattner86102b82005-01-01 16:22:27 +00003098 // and X, X = X
3099 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003100 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003101
Chris Lattner5b2edb12006-02-12 08:02:11 +00003102 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003103 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003104 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003105 if (!isa<PackedType>(I.getType()) &&
3106 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003107 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003108 return &I;
3109
Chris Lattner86102b82005-01-01 16:22:27 +00003110 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003111 uint64_t AndRHSMask = AndRHS->getZExtValue();
3112 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003113 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003114
Chris Lattnerba1cb382003-09-19 17:17:26 +00003115 // Optimize a variety of ((val OP C1) & C2) combinations...
3116 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3117 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003118 Value *Op0LHS = Op0I->getOperand(0);
3119 Value *Op0RHS = Op0I->getOperand(1);
3120 switch (Op0I->getOpcode()) {
3121 case Instruction::Xor:
3122 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003123 // If the mask is only needed on one incoming arm, push it up.
3124 if (Op0I->hasOneUse()) {
3125 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3126 // Not masking anything out for the LHS, move to RHS.
3127 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3128 Op0RHS->getName()+".masked");
3129 InsertNewInstBefore(NewRHS, I);
3130 return BinaryOperator::create(
3131 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003132 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003133 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003134 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3135 // Not masking anything out for the RHS, move to LHS.
3136 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3137 Op0LHS->getName()+".masked");
3138 InsertNewInstBefore(NewLHS, I);
3139 return BinaryOperator::create(
3140 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3141 }
3142 }
3143
Chris Lattner86102b82005-01-01 16:22:27 +00003144 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003145 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003146 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3147 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3149 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3150 return BinaryOperator::createAnd(V, AndRHS);
3151 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3152 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003153 break;
3154
3155 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003156 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3157 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3159 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3160 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003161 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003162 }
3163
Chris Lattner16464b32003-07-23 19:25:52 +00003164 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003165 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003166 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003167 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003168 // If this is an integer truncation or change from signed-to-unsigned, and
3169 // if the source is an and/or with immediate, transform it. This
3170 // frequently occurs for bitfield accesses.
3171 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003172 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003173 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003174 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003175 if (CastOp->getOpcode() == Instruction::And) {
3176 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003177 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3178 // This will fold the two constants together, which may allow
3179 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003180 Instruction *NewCast = CastInst::createTruncOrBitCast(
3181 CastOp->getOperand(0), I.getType(),
3182 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003183 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003184 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003185 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003186 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003187 return BinaryOperator::createAnd(NewCast, C3);
3188 } else if (CastOp->getOpcode() == Instruction::Or) {
3189 // Change: and (cast (or X, C1) to T), C2
3190 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003191 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003192 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3193 return ReplaceInstUsesWith(I, AndRHS);
3194 }
3195 }
Chris Lattner33217db2003-07-23 19:36:21 +00003196 }
Chris Lattner183b3362004-04-09 19:05:30 +00003197
3198 // Try to fold constant and into select arguments.
3199 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003200 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003201 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003202 if (isa<PHINode>(Op0))
3203 if (Instruction *NV = FoldOpIntoPhi(I))
3204 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003205 }
3206
Chris Lattnerbb74e222003-03-10 23:06:50 +00003207 Value *Op0NotVal = dyn_castNotVal(Op0);
3208 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003209
Chris Lattner023a4832004-06-18 06:07:51 +00003210 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3211 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3212
Misha Brukman9c003d82004-07-30 12:50:08 +00003213 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003214 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003215 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3216 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003217 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003218 return BinaryOperator::createNot(Or);
3219 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003220
3221 {
3222 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003223 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3224 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3225 return ReplaceInstUsesWith(I, Op1);
3226 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3227 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3228 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003229
3230 if (Op0->hasOneUse() &&
3231 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3232 if (A == Op1) { // (A^B)&A -> A&(A^B)
3233 I.swapOperands(); // Simplify below
3234 std::swap(Op0, Op1);
3235 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3236 cast<BinaryOperator>(Op0)->swapOperands();
3237 I.swapOperands(); // Simplify below
3238 std::swap(Op0, Op1);
3239 }
3240 }
3241 if (Op1->hasOneUse() &&
3242 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3243 if (B == Op0) { // B&(A^B) -> B&(B^A)
3244 cast<BinaryOperator>(Op1)->swapOperands();
3245 std::swap(A, B);
3246 }
3247 if (A == Op0) { // A&(A^B) -> A & ~B
3248 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3249 InsertNewInstBefore(NotB, I);
3250 return BinaryOperator::createAnd(A, NotB);
3251 }
3252 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003253 }
3254
Reid Spencer266e42b2006-12-23 06:05:41 +00003255 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3256 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3257 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003258 return R;
3259
Chris Lattner623826c2004-09-28 21:48:02 +00003260 Value *LHSVal, *RHSVal;
3261 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003262 ICmpInst::Predicate LHSCC, RHSCC;
3263 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3264 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3265 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3266 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3267 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3268 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3269 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3270 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003271 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003272 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3273 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3274 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3275 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner623826c2004-09-28 21:48:02 +00003276 if (cast<ConstantBool>(Cmp)->getValue()) {
3277 std::swap(LHS, RHS);
3278 std::swap(LHSCst, RHSCst);
3279 std::swap(LHSCC, RHSCC);
3280 }
3281
Reid Spencer266e42b2006-12-23 06:05:41 +00003282 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003283 // comparing a value against two constants and and'ing the result
3284 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003285 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3286 // (from the FoldICmpLogical check above), that the two constants
3287 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003288 assert(LHSCst != RHSCst && "Compares not folded above?");
3289
3290 switch (LHSCC) {
3291 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003292 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003293 switch (RHSCC) {
3294 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003295 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3296 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3297 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003298 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003299 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3300 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3301 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003302 return ReplaceInstUsesWith(I, LHS);
3303 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003304 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003305 switch (RHSCC) {
3306 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003307 case ICmpInst::ICMP_ULT:
3308 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3309 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3310 break; // (X != 13 & X u< 15) -> no change
3311 case ICmpInst::ICMP_SLT:
3312 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3313 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3314 break; // (X != 13 & X s< 15) -> no change
3315 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3316 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3317 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003318 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003319 case ICmpInst::ICMP_NE:
3320 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003321 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3322 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3323 LHSVal->getName()+".off");
3324 InsertNewInstBefore(Add, I);
3325 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003326 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3327 UnsType, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003328 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003329 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Reid Spencer266e42b2006-12-23 06:05:41 +00003330 return new ICmpInst(ICmpInst::ICMP_UGT, OffsetVal, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003331 }
3332 break; // (X != 13 & X != 15) -> no change
3333 }
3334 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003335 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003336 switch (RHSCC) {
3337 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003338 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3339 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003340 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003341 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3342 break;
3343 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3344 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003345 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003346 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3347 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003348 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003349 break;
3350 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003351 switch (RHSCC) {
3352 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003353 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3354 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3355 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3356 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3357 break;
3358 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3359 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003360 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003361 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3362 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003363 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003364 break;
3365 case ICmpInst::ICMP_UGT:
3366 switch (RHSCC) {
3367 default: assert(0 && "Unknown integer condition code!");
3368 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3369 return ReplaceInstUsesWith(I, LHS);
3370 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3371 return ReplaceInstUsesWith(I, RHS);
3372 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3373 break;
3374 case ICmpInst::ICMP_NE:
3375 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3376 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3377 break; // (X u> 13 & X != 15) -> no change
3378 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3379 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3380 true, I);
3381 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3382 break;
3383 }
3384 break;
3385 case ICmpInst::ICMP_SGT:
3386 switch (RHSCC) {
3387 default: assert(0 && "Unknown integer condition code!");
3388 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3389 return ReplaceInstUsesWith(I, LHS);
3390 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3391 return ReplaceInstUsesWith(I, RHS);
3392 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3393 break;
3394 case ICmpInst::ICMP_NE:
3395 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3396 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3397 break; // (X s> 13 & X != 15) -> no change
3398 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3399 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3400 true, I);
3401 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3402 break;
3403 }
3404 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003405 }
3406 }
3407 }
3408
Chris Lattner3af10532006-05-05 06:39:07 +00003409 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003410 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3411 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3412 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3413 const Type *SrcTy = Op0C->getOperand(0)->getType();
3414 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3415 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003416 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3417 I.getType(), TD) &&
3418 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3419 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003420 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3421 Op1C->getOperand(0),
3422 I.getName());
3423 InsertNewInstBefore(NewOp, I);
3424 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3425 }
Chris Lattner3af10532006-05-05 06:39:07 +00003426 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003427
3428 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3429 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3430 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3431 if (SI0->getOpcode() == SI1->getOpcode() &&
3432 SI0->getOperand(1) == SI1->getOperand(1) &&
3433 (SI0->hasOneUse() || SI1->hasOneUse())) {
3434 Instruction *NewOp =
3435 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3436 SI1->getOperand(0),
3437 SI0->getName()), I);
3438 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3439 }
Chris Lattner3af10532006-05-05 06:39:07 +00003440 }
3441
Chris Lattner113f4f42002-06-25 16:13:24 +00003442 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003443}
3444
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003445/// CollectBSwapParts - Look to see if the specified value defines a single byte
3446/// in the result. If it does, and if the specified byte hasn't been filled in
3447/// yet, fill it in and return false.
3448static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3449 Instruction *I = dyn_cast<Instruction>(V);
3450 if (I == 0) return true;
3451
3452 // If this is an or instruction, it is an inner node of the bswap.
3453 if (I->getOpcode() == Instruction::Or)
3454 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3455 CollectBSwapParts(I->getOperand(1), ByteValues);
3456
3457 // If this is a shift by a constant int, and it is "24", then its operand
3458 // defines a byte. We only handle unsigned types here.
3459 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3460 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003461 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003462 8*(ByteValues.size()-1))
3463 return true;
3464
3465 unsigned DestNo;
3466 if (I->getOpcode() == Instruction::Shl) {
3467 // X << 24 defines the top byte with the lowest of the input bytes.
3468 DestNo = ByteValues.size()-1;
3469 } else {
3470 // X >>u 24 defines the low byte with the highest of the input bytes.
3471 DestNo = 0;
3472 }
3473
3474 // If the destination byte value is already defined, the values are or'd
3475 // together, which isn't a bswap (unless it's an or of the same bits).
3476 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3477 return true;
3478 ByteValues[DestNo] = I->getOperand(0);
3479 return false;
3480 }
3481
3482 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3483 // don't have this.
3484 Value *Shift = 0, *ShiftLHS = 0;
3485 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3486 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3487 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3488 return true;
3489 Instruction *SI = cast<Instruction>(Shift);
3490
3491 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003492 if (ShiftAmt->getZExtValue() & 7 ||
3493 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003494 return true;
3495
3496 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3497 unsigned DestByte;
3498 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003499 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003500 break;
3501 // Unknown mask for bswap.
3502 if (DestByte == ByteValues.size()) return true;
3503
Reid Spencere0fc4df2006-10-20 07:07:24 +00003504 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003505 unsigned SrcByte;
3506 if (SI->getOpcode() == Instruction::Shl)
3507 SrcByte = DestByte - ShiftBytes;
3508 else
3509 SrcByte = DestByte + ShiftBytes;
3510
3511 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3512 if (SrcByte != ByteValues.size()-DestByte-1)
3513 return true;
3514
3515 // If the destination byte value is already defined, the values are or'd
3516 // together, which isn't a bswap (unless it's an or of the same bits).
3517 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3518 return true;
3519 ByteValues[DestByte] = SI->getOperand(0);
3520 return false;
3521}
3522
3523/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3524/// If so, insert the new bswap intrinsic and return it.
3525Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3526 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3527 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3528 return 0;
3529
3530 /// ByteValues - For each byte of the result, we keep track of which value
3531 /// defines each byte.
3532 std::vector<Value*> ByteValues;
3533 ByteValues.resize(I.getType()->getPrimitiveSize());
3534
3535 // Try to find all the pieces corresponding to the bswap.
3536 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3537 CollectBSwapParts(I.getOperand(1), ByteValues))
3538 return 0;
3539
3540 // Check to see if all of the bytes come from the same value.
3541 Value *V = ByteValues[0];
3542 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3543
3544 // Check to make sure that all of the bytes come from the same value.
3545 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3546 if (ByteValues[i] != V)
3547 return 0;
3548
3549 // If they do then *success* we can turn this into a bswap. Figure out what
3550 // bswap to make it into.
3551 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003552 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003553 if (I.getType() == Type::UShortTy)
3554 FnName = "llvm.bswap.i16";
3555 else if (I.getType() == Type::UIntTy)
3556 FnName = "llvm.bswap.i32";
3557 else if (I.getType() == Type::ULongTy)
3558 FnName = "llvm.bswap.i64";
3559 else
3560 assert(0 && "Unknown integer type!");
3561 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3562
3563 return new CallInst(F, V);
3564}
3565
3566
Chris Lattner113f4f42002-06-25 16:13:24 +00003567Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003568 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003570
Chris Lattner81a7a232004-10-16 18:11:37 +00003571 if (isa<UndefValue>(Op1))
3572 return ReplaceInstUsesWith(I, // X | undef -> -1
3573 ConstantIntegral::getAllOnesValue(I.getType()));
3574
Chris Lattner5b2edb12006-02-12 08:02:11 +00003575 // or X, X = X
3576 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003577 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003578
Chris Lattner5b2edb12006-02-12 08:02:11 +00003579 // See if we can simplify any instructions used by the instruction whose sole
3580 // purpose is to compute bits we don't care about.
3581 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003582 if (!isa<PackedType>(I.getType()) &&
3583 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003584 KnownZero, KnownOne))
3585 return &I;
3586
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003587 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003588 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003589 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003590 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3591 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003592 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3593 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003594 InsertNewInstBefore(Or, I);
3595 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3596 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003597
Chris Lattnerd4252a72004-07-30 07:50:03 +00003598 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3599 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3600 std::string Op0Name = Op0->getName(); Op0->setName("");
3601 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3602 InsertNewInstBefore(Or, I);
3603 return BinaryOperator::createXor(Or,
3604 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003605 }
Chris Lattner183b3362004-04-09 19:05:30 +00003606
3607 // Try to fold constant and into select arguments.
3608 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003609 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003610 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003611 if (isa<PHINode>(Op0))
3612 if (Instruction *NV = FoldOpIntoPhi(I))
3613 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003614 }
3615
Chris Lattner330628a2006-01-06 17:59:59 +00003616 Value *A = 0, *B = 0;
3617 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003618
3619 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3620 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3621 return ReplaceInstUsesWith(I, Op1);
3622 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3623 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3624 return ReplaceInstUsesWith(I, Op0);
3625
Chris Lattnerb7845d62006-07-10 20:25:24 +00003626 // (A | B) | C and A | (B | C) -> bswap if possible.
3627 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003628 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003629 match(Op1, m_Or(m_Value(), m_Value())) ||
3630 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3631 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003632 if (Instruction *BSwap = MatchBSwap(I))
3633 return BSwap;
3634 }
3635
Chris Lattnerb62f5082005-05-09 04:58:36 +00003636 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3637 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003638 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003639 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3640 Op0->setName("");
3641 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3642 }
3643
3644 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3645 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003646 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003647 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3648 Op0->setName("");
3649 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3650 }
3651
Chris Lattner15212982005-09-18 03:42:07 +00003652 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003653 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003654 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3655
3656 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3657 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3658
3659
Chris Lattner01f56c62005-09-18 06:02:59 +00003660 // If we have: ((V + N) & C1) | (V & C2)
3661 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3662 // replace with V+N.
3663 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003664 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003665 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003666 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3667 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003668 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003669 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003670 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003671 return ReplaceInstUsesWith(I, A);
3672 }
3673 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003674 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003675 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3676 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003677 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003678 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003679 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003680 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003681 }
3682 }
3683 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003684
3685 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3686 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3687 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3688 if (SI0->getOpcode() == SI1->getOpcode() &&
3689 SI0->getOperand(1) == SI1->getOperand(1) &&
3690 (SI0->hasOneUse() || SI1->hasOneUse())) {
3691 Instruction *NewOp =
3692 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3693 SI1->getOperand(0),
3694 SI0->getName()), I);
3695 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3696 }
3697 }
Chris Lattner812aab72003-08-12 19:11:07 +00003698
Chris Lattnerd4252a72004-07-30 07:50:03 +00003699 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3700 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003701 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003702 ConstantIntegral::getAllOnesValue(I.getType()));
3703 } else {
3704 A = 0;
3705 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003706 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003707 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3708 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003709 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003710 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003711
Misha Brukman9c003d82004-07-30 12:50:08 +00003712 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003713 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3714 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3715 I.getName()+".demorgan"), I);
3716 return BinaryOperator::createNot(And);
3717 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003718 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003719
Reid Spencer266e42b2006-12-23 06:05:41 +00003720 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3721 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3722 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003723 return R;
3724
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003725 Value *LHSVal, *RHSVal;
3726 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003727 ICmpInst::Predicate LHSCC, RHSCC;
3728 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3729 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3730 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3731 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3732 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3733 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3734 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3735 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003736 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003737 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3738 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3739 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3740 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003741 if (cast<ConstantBool>(Cmp)->getValue()) {
3742 std::swap(LHS, RHS);
3743 std::swap(LHSCst, RHSCst);
3744 std::swap(LHSCC, RHSCC);
3745 }
3746
Reid Spencer266e42b2006-12-23 06:05:41 +00003747 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003748 // comparing a value against two constants and or'ing the result
3749 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003750 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3751 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003752 // equal.
3753 assert(LHSCst != RHSCst && "Compares not folded above?");
3754
3755 switch (LHSCC) {
3756 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003757 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003758 switch (RHSCC) {
3759 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003760 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3762 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3763 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3764 LHSVal->getName()+".off");
3765 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003766 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003767 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003768 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003769 break; // (X == 13 | X == 15) -> no change
3770 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3771 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003772 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003773 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3774 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3775 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003776 return ReplaceInstUsesWith(I, RHS);
3777 }
3778 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003779 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003780 switch (RHSCC) {
3781 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003782 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3783 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3784 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003785 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003786 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3787 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3788 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003789 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003790 }
3791 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003792 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003793 switch (RHSCC) {
3794 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003795 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003796 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003797 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3798 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3799 false, I);
3800 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3801 break;
3802 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3803 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003804 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3806 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003807 }
3808 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003809 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003810 switch (RHSCC) {
3811 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003812 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3813 break;
3814 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3815 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3816 false, I);
3817 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3818 break;
3819 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3820 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3821 return ReplaceInstUsesWith(I, RHS);
3822 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3823 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003824 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003825 break;
3826 case ICmpInst::ICMP_UGT:
3827 switch (RHSCC) {
3828 default: assert(0 && "Unknown integer condition code!");
3829 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3830 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3831 return ReplaceInstUsesWith(I, LHS);
3832 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3833 break;
3834 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3835 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3836 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3837 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3838 break;
3839 }
3840 break;
3841 case ICmpInst::ICMP_SGT:
3842 switch (RHSCC) {
3843 default: assert(0 && "Unknown integer condition code!");
3844 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3845 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3846 return ReplaceInstUsesWith(I, LHS);
3847 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3848 break;
3849 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3850 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3851 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3852 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3853 break;
3854 }
3855 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003856 }
3857 }
3858 }
Chris Lattner3af10532006-05-05 06:39:07 +00003859
3860 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003861 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003862 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003863 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3864 const Type *SrcTy = Op0C->getOperand(0)->getType();
3865 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3866 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003867 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3868 I.getType(), TD) &&
3869 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3870 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003871 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3872 Op1C->getOperand(0),
3873 I.getName());
3874 InsertNewInstBefore(NewOp, I);
3875 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3876 }
Chris Lattner3af10532006-05-05 06:39:07 +00003877 }
Chris Lattner3af10532006-05-05 06:39:07 +00003878
Chris Lattner15212982005-09-18 03:42:07 +00003879
Chris Lattner113f4f42002-06-25 16:13:24 +00003880 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003881}
3882
Chris Lattnerc2076352004-02-16 01:20:27 +00003883// XorSelf - Implements: X ^ X --> 0
3884struct XorSelf {
3885 Value *RHS;
3886 XorSelf(Value *rhs) : RHS(rhs) {}
3887 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3888 Instruction *apply(BinaryOperator &Xor) const {
3889 return &Xor;
3890 }
3891};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003892
3893
Chris Lattner113f4f42002-06-25 16:13:24 +00003894Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003895 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003897
Chris Lattner81a7a232004-10-16 18:11:37 +00003898 if (isa<UndefValue>(Op1))
3899 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3900
Chris Lattnerc2076352004-02-16 01:20:27 +00003901 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3902 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3903 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003904 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003905 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003906
3907 // See if we can simplify any instructions used by the instruction whose sole
3908 // purpose is to compute bits we don't care about.
3909 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003910 if (!isa<PackedType>(I.getType()) &&
3911 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003912 KnownZero, KnownOne))
3913 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003914
Chris Lattner97638592003-07-23 21:37:07 +00003915 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003916 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3917 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3918 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3919 return new ICmpInst(ICI->getInversePredicate(),
3920 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003921
Reid Spencer266e42b2006-12-23 06:05:41 +00003922 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003923 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003924 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3925 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003926 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3927 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003928 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003929 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003930 }
Chris Lattner023a4832004-06-18 06:07:51 +00003931
3932 // ~(~X & Y) --> (X | ~Y)
3933 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3934 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3935 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3936 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003937 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003938 Op0I->getOperand(1)->getName()+".not");
3939 InsertNewInstBefore(NotY, I);
3940 return BinaryOperator::createOr(Op0NotVal, NotY);
3941 }
3942 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003943
Chris Lattner97638592003-07-23 21:37:07 +00003944 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003945 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003946 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003947 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003948 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3949 return BinaryOperator::createSub(
3950 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003951 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003952 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003953 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003954 } else if (Op0I->getOpcode() == Instruction::Or) {
3955 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3956 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3957 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3958 // Anything in both C1 and C2 is known to be zero, remove it from
3959 // NewRHS.
3960 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3961 NewRHS = ConstantExpr::getAnd(NewRHS,
3962 ConstantExpr::getNot(CommonBits));
3963 WorkList.push_back(Op0I);
3964 I.setOperand(0, Op0I->getOperand(0));
3965 I.setOperand(1, NewRHS);
3966 return &I;
3967 }
Chris Lattner97638592003-07-23 21:37:07 +00003968 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003969 }
Chris Lattner183b3362004-04-09 19:05:30 +00003970
3971 // Try to fold constant and into select arguments.
3972 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003973 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003974 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003975 if (isa<PHINode>(Op0))
3976 if (Instruction *NV = FoldOpIntoPhi(I))
3977 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003978 }
3979
Chris Lattnerbb74e222003-03-10 23:06:50 +00003980 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003981 if (X == Op1)
3982 return ReplaceInstUsesWith(I,
3983 ConstantIntegral::getAllOnesValue(I.getType()));
3984
Chris Lattnerbb74e222003-03-10 23:06:50 +00003985 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003986 if (X == Op0)
3987 return ReplaceInstUsesWith(I,
3988 ConstantIntegral::getAllOnesValue(I.getType()));
3989
Chris Lattnerdcd07922006-04-01 08:03:55 +00003990 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003991 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003992 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003993 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003994 I.swapOperands();
3995 std::swap(Op0, Op1);
3996 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003997 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003998 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003999 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004000 } else if (Op1I->getOpcode() == Instruction::Xor) {
4001 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4002 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4003 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4004 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004005 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4006 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4007 Op1I->swapOperands();
4008 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4009 I.swapOperands(); // Simplified below.
4010 std::swap(Op0, Op1);
4011 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004012 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004013
Chris Lattnerdcd07922006-04-01 08:03:55 +00004014 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004015 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004016 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004017 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004018 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004019 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4020 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004021 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004022 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004023 } else if (Op0I->getOpcode() == Instruction::Xor) {
4024 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4025 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4026 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4027 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004028 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4029 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4030 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004031 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4032 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004033 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4034 InsertNewInstBefore(N, I);
4035 return BinaryOperator::createAnd(N, Op1);
4036 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004037 }
4038
Reid Spencer266e42b2006-12-23 06:05:41 +00004039 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4040 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4041 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004042 return R;
4043
Chris Lattner3af10532006-05-05 06:39:07 +00004044 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004045 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004046 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004047 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4048 const Type *SrcTy = Op0C->getOperand(0)->getType();
4049 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4050 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004051 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4052 I.getType(), TD) &&
4053 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4054 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004055 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4056 Op1C->getOperand(0),
4057 I.getName());
4058 InsertNewInstBefore(NewOp, I);
4059 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4060 }
Chris Lattner3af10532006-05-05 06:39:07 +00004061 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004062
4063 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4064 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4065 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4066 if (SI0->getOpcode() == SI1->getOpcode() &&
4067 SI0->getOperand(1) == SI1->getOperand(1) &&
4068 (SI0->hasOneUse() || SI1->hasOneUse())) {
4069 Instruction *NewOp =
4070 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4071 SI1->getOperand(0),
4072 SI0->getName()), I);
4073 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4074 }
4075 }
Chris Lattner3af10532006-05-05 06:39:07 +00004076
Chris Lattner113f4f42002-06-25 16:13:24 +00004077 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004078}
4079
Chris Lattner6862fbd2004-09-29 17:40:11 +00004080static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004081 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004082}
4083
4084/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4085/// overflowed for this type.
4086static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4087 ConstantInt *In2) {
4088 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4089
4090 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00004091 return cast<ConstantInt>(Result)->getZExtValue() <
4092 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004093 if (isPositive(In1) != isPositive(In2))
4094 return false;
4095 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00004096 return cast<ConstantInt>(Result)->getSExtValue() <
4097 cast<ConstantInt>(In1)->getSExtValue();
4098 return cast<ConstantInt>(Result)->getSExtValue() >
4099 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004100}
4101
Chris Lattner0798af32005-01-13 20:14:25 +00004102/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4103/// code necessary to compute the offset from the base pointer (without adding
4104/// in the base pointer). Return the result as a signed integer of intptr size.
4105static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4106 TargetData &TD = IC.getTargetData();
4107 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004108 const Type *IntPtrTy = TD.getIntPtrType();
4109 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004110
4111 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004112 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004113
Chris Lattner0798af32005-01-13 20:14:25 +00004114 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4115 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004116 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004117 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004118 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4119 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004120 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004121 Scale = ConstantExpr::getMul(OpC, Scale);
4122 if (Constant *RC = dyn_cast<Constant>(Result))
4123 Result = ConstantExpr::getAdd(RC, Scale);
4124 else {
4125 // Emit an add instruction.
4126 Result = IC.InsertNewInstBefore(
4127 BinaryOperator::createAdd(Result, Scale,
4128 GEP->getName()+".offs"), I);
4129 }
4130 }
4131 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004132 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004133 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004134 Op->getName()+".c"), I);
4135 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004136 // We'll let instcombine(mul) convert this to a shl if possible.
4137 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4138 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004139
4140 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004141 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004142 GEP->getName()+".offs"), I);
4143 }
4144 }
4145 return Result;
4146}
4147
Reid Spencer266e42b2006-12-23 06:05:41 +00004148/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004149/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004150Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4151 ICmpInst::Predicate Cond,
4152 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004153 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004154
4155 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4156 if (isa<PointerType>(CI->getOperand(0)->getType()))
4157 RHS = CI->getOperand(0);
4158
Chris Lattner0798af32005-01-13 20:14:25 +00004159 Value *PtrBase = GEPLHS->getOperand(0);
4160 if (PtrBase == RHS) {
4161 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004162 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4163 // each index is zero or not.
4164 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004165 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004166 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4167 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004168 bool EmitIt = true;
4169 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4170 if (isa<UndefValue>(C)) // undef index -> undef.
4171 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4172 if (C->isNullValue())
4173 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004174 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4175 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004176 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004177 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004178 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004179 }
4180
4181 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004182 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004183 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004184 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4185 if (InVal == 0)
4186 InVal = Comp;
4187 else {
4188 InVal = InsertNewInstBefore(InVal, I);
4189 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004190 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004191 InVal = BinaryOperator::createOr(InVal, Comp);
4192 else // True if all are equal
4193 InVal = BinaryOperator::createAnd(InVal, Comp);
4194 }
4195 }
4196 }
4197
4198 if (InVal)
4199 return InVal;
4200 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004201 // No comparison is needed here, all indexes = 0
4202 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004203 }
Chris Lattner0798af32005-01-13 20:14:25 +00004204
Reid Spencer266e42b2006-12-23 06:05:41 +00004205 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004206 // the result to fold to a constant!
4207 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4208 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4209 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004210 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4211 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004212 }
4213 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004214 // If the base pointers are different, but the indices are the same, just
4215 // compare the base pointer.
4216 if (PtrBase != GEPRHS->getOperand(0)) {
4217 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004218 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004219 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004220 if (IndicesTheSame)
4221 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4222 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4223 IndicesTheSame = false;
4224 break;
4225 }
4226
4227 // If all indices are the same, just compare the base pointers.
4228 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004229 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4230 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004231
4232 // Otherwise, the base pointers are different and the indices are
4233 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004234 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004235 }
Chris Lattner0798af32005-01-13 20:14:25 +00004236
Chris Lattner81e84172005-01-13 22:25:21 +00004237 // If one of the GEPs has all zero indices, recurse.
4238 bool AllZeros = true;
4239 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4240 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4241 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4242 AllZeros = false;
4243 break;
4244 }
4245 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004246 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4247 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004248
4249 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004250 AllZeros = true;
4251 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4252 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4253 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4254 AllZeros = false;
4255 break;
4256 }
4257 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004258 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004259
Chris Lattner4fa89822005-01-14 00:20:05 +00004260 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4261 // If the GEPs only differ by one index, compare it.
4262 unsigned NumDifferences = 0; // Keep track of # differences.
4263 unsigned DiffOperand = 0; // The operand that differs.
4264 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4265 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004266 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4267 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004268 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004269 NumDifferences = 2;
4270 break;
4271 } else {
4272 if (NumDifferences++) break;
4273 DiffOperand = i;
4274 }
4275 }
4276
4277 if (NumDifferences == 0) // SAME GEP?
4278 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004279 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004280 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004281 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4282 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004283 if (LHSV->getType() != RHSV->getType())
4284 // Doesn't matter which one we bitconvert here.
4285 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, RHSV->getType(),
4286 I);
4287 // Make sure we do a signed comparison here.
4288 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004289 }
4290 }
4291
Reid Spencer266e42b2006-12-23 06:05:41 +00004292 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004293 // the result to fold to a constant!
4294 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4295 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4296 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4297 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4298 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004299 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004300 }
4301 }
4302 return 0;
4303}
4304
Reid Spencer266e42b2006-12-23 06:05:41 +00004305Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4306 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004308
Reid Spencer266e42b2006-12-23 06:05:41 +00004309 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004310 if (Op0 == Op1)
4311 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004312
Reid Spencer266e42b2006-12-23 06:05:41 +00004313 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00004314 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4315
Reid Spencer266e42b2006-12-23 06:05:41 +00004316 // Handle fcmp with constant RHS
4317 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4318 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4319 switch (LHSI->getOpcode()) {
4320 case Instruction::PHI:
4321 if (Instruction *NV = FoldOpIntoPhi(I))
4322 return NV;
4323 break;
4324 case Instruction::Select:
4325 // If either operand of the select is a constant, we can fold the
4326 // comparison into the select arms, which will cause one to be
4327 // constant folded and the select turned into a bitwise or.
4328 Value *Op1 = 0, *Op2 = 0;
4329 if (LHSI->hasOneUse()) {
4330 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4331 // Fold the known value into the constant operand.
4332 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4333 // Insert a new FCmp of the other select operand.
4334 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4335 LHSI->getOperand(2), RHSC,
4336 I.getName()), I);
4337 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4338 // Fold the known value into the constant operand.
4339 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4340 // Insert a new FCmp of the other select operand.
4341 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4342 LHSI->getOperand(1), RHSC,
4343 I.getName()), I);
4344 }
4345 }
4346
4347 if (Op1)
4348 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4349 break;
4350 }
4351 }
4352
4353 return Changed ? &I : 0;
4354}
4355
4356Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4357 bool Changed = SimplifyCompare(I);
4358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4359 const Type *Ty = Op0->getType();
4360
4361 // icmp X, X
4362 if (Op0 == Op1)
4363 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4364
4365 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4366 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4367
4368 // icmp of GlobalValues can never equal each other as long as they aren't
4369 // external weak linkage type.
4370 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4371 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4372 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4373 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4374
4375 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004376 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004377 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4378 isa<ConstantPointerNull>(Op0)) &&
4379 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004380 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004381 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4382
Reid Spencer266e42b2006-12-23 06:05:41 +00004383 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004384 if (Ty == Type::BoolTy) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004385 switch (I.getPredicate()) {
4386 default: assert(0 && "Invalid icmp instruction!");
4387 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004388 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004389 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004390 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004391 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004392 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004393 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004394
Reid Spencer266e42b2006-12-23 06:05:41 +00004395 case ICmpInst::ICMP_UGT:
4396 case ICmpInst::ICMP_SGT:
4397 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004398 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004399 case ICmpInst::ICMP_ULT:
4400 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004401 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4402 InsertNewInstBefore(Not, I);
4403 return BinaryOperator::createAnd(Not, Op1);
4404 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004405 case ICmpInst::ICMP_UGE:
4406 case ICmpInst::ICMP_SGE:
4407 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004408 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004409 case ICmpInst::ICMP_ULE:
4410 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004411 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4412 InsertNewInstBefore(Not, I);
4413 return BinaryOperator::createOr(Not, Op1);
4414 }
4415 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004416 }
4417
Chris Lattner2dd01742004-06-09 04:24:29 +00004418 // See if we are doing a comparison between a constant and an instruction that
4419 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004421 switch (I.getPredicate()) {
4422 default: break;
4423 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4424 if (CI->isMinValue(false))
Chris Lattner6ab03f62006-09-28 23:35:22 +00004425 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004426 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4427 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4428 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4429 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4430 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004431
Reid Spencer266e42b2006-12-23 06:05:41 +00004432 case ICmpInst::ICMP_SLT:
4433 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004434 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004435 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4436 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4437 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4438 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4439 break;
4440
4441 case ICmpInst::ICMP_UGT:
4442 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4443 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4444 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4445 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4446 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4447 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4448 break;
4449
4450 case ICmpInst::ICMP_SGT:
4451 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4452 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4453 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4454 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4455 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4456 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4457 break;
4458
4459 case ICmpInst::ICMP_ULE:
4460 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004461 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004462 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4463 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4464 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4465 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4466 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004467
Reid Spencer266e42b2006-12-23 06:05:41 +00004468 case ICmpInst::ICMP_SLE:
4469 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4470 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4471 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4472 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4473 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4474 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4475 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004476
Reid Spencer266e42b2006-12-23 06:05:41 +00004477 case ICmpInst::ICMP_UGE:
4478 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4479 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4480 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4481 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4482 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4483 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4484 break;
4485
4486 case ICmpInst::ICMP_SGE:
4487 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4488 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4489 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4490 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4491 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4492 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4493 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004494 }
4495
Reid Spencer266e42b2006-12-23 06:05:41 +00004496 // If we still have a icmp le or icmp ge instruction, turn it into the
4497 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004498 // already been handled above, this requires little checking.
4499 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004500 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4501 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4502 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4503 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4504 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4505 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4506 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4507 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004508
4509 // See if we can fold the comparison based on bits known to be zero or one
4510 // in the input.
4511 uint64_t KnownZero, KnownOne;
4512 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4513 KnownZero, KnownOne, 0))
4514 return &I;
4515
4516 // Given the known and unknown bits, compute a range that the LHS could be
4517 // in.
4518 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004519 // Compute the Min, Max and RHS values based on the known bits. For the
4520 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004521 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4522 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004523 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4524 SRHSVal = CI->getSExtValue();
4525 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4526 SMax);
4527 } else {
4528 URHSVal = CI->getZExtValue();
4529 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4530 UMax);
4531 }
4532 switch (I.getPredicate()) { // LE/GE have been folded already.
4533 default: assert(0 && "Unknown icmp opcode!");
4534 case ICmpInst::ICMP_EQ:
4535 if (UMax < URHSVal || UMin > URHSVal)
4536 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4537 break;
4538 case ICmpInst::ICMP_NE:
4539 if (UMax < URHSVal || UMin > URHSVal)
4540 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4541 break;
4542 case ICmpInst::ICMP_ULT:
4543 if (UMax < URHSVal)
4544 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4545 if (UMin > URHSVal)
4546 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4547 break;
4548 case ICmpInst::ICMP_UGT:
4549 if (UMin > URHSVal)
4550 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4551 if (UMax < URHSVal)
4552 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4553 break;
4554 case ICmpInst::ICMP_SLT:
4555 if (SMax < SRHSVal)
4556 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4557 if (SMin > SRHSVal)
4558 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4559 break;
4560 case ICmpInst::ICMP_SGT:
4561 if (SMin > SRHSVal)
4562 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4563 if (SMax < SRHSVal)
4564 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4565 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004566 }
4567 }
4568
Reid Spencer266e42b2006-12-23 06:05:41 +00004569 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004570 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004571 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004572 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004573 switch (LHSI->getOpcode()) {
4574 case Instruction::And:
4575 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4576 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004577 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4578
Reid Spencer266e42b2006-12-23 06:05:41 +00004579 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004580 // and/compare to be the input width without changing the value
4581 // produced, eliminating a cast.
4582 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4583 // We can do this transformation if either the AND constant does not
4584 // have its sign bit set or if it is an equality comparison.
4585 // Extending a relational comparison when we're checking the sign
4586 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004587 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004588 (I.isEquality() ||
4589 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4590 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4591 ConstantInt *NewCST;
4592 ConstantInt *NewCI;
4593 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004594 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004595 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004596 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004597 CI->getZExtValue());
4598 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004599 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004600 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004601 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004602 CI->getZExtValue());
4603 }
4604 Instruction *NewAnd =
4605 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4606 LHSI->getName());
4607 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004608 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004609 }
4610 }
4611
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004612 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4613 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4614 // happens a LOT in code produced by the C front-end, for bitfield
4615 // access.
4616 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004617
4618 // Check to see if there is a noop-cast between the shift and the and.
4619 if (!Shift) {
4620 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004621 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004622 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4623 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004624
Reid Spencere0fc4df2006-10-20 07:07:24 +00004625 ConstantInt *ShAmt;
4626 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004627 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4628 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004629
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004630 // We can fold this as long as we can't shift unknown bits
4631 // into the mask. This can only happen with signed shift
4632 // rights, as they sign-extend.
4633 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004634 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004635 if (!CanFold) {
4636 // To test for the bad case of the signed shr, see if any
4637 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004638 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004639 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4640
Reid Spencere0fc4df2006-10-20 07:07:24 +00004641 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004642 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004643 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4644 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004645 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4646 CanFold = true;
4647 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004648
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004649 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004650 Constant *NewCst;
4651 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004652 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004653 else
4654 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004655
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004656 // Check to see if we are shifting out any of the bits being
4657 // compared.
4658 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4659 // If we shifted bits out, the fold is not going to work out.
4660 // As a special case, check to see if this means that the
4661 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004662 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004663 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004664 if (I.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004665 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004666 } else {
4667 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004668 Constant *NewAndCST;
4669 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004670 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004671 else
4672 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4673 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004674 if (AndTy == Ty)
4675 LHSI->setOperand(0, Shift->getOperand(0));
4676 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004677 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4678 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004679 *Shift);
4680 LHSI->setOperand(0, NewCast);
4681 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004682 WorkList.push_back(Shift); // Shift is dead.
4683 AddUsesToWorkList(I);
4684 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004685 }
4686 }
Chris Lattner35167c32004-06-09 07:59:58 +00004687 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004688
4689 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4690 // preferable because it allows the C<<Y expression to be hoisted out
4691 // of a loop if Y is invariant and X is not.
4692 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004693 I.isEquality() && !Shift->isArithmeticShift() &&
4694 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004695 // Compute C << Y.
4696 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004697 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004698 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4699 "tmp");
4700 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004701 // Insert a logical shift.
4702 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004703 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004704 }
4705 InsertNewInstBefore(cast<Instruction>(NS), I);
4706
4707 // If C's sign doesn't agree with the and, insert a cast now.
4708 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004709 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4710 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004711
4712 Value *ShiftOp = Shift->getOperand(0);
4713 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004714 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4715 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004716
4717 // Compute X & (C << Y).
4718 Instruction *NewAnd =
4719 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4720 InsertNewInstBefore(NewAnd, I);
4721
4722 I.setOperand(0, NewAnd);
4723 return &I;
4724 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004725 }
4726 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004727
Reid Spencer266e42b2006-12-23 06:05:41 +00004728 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004729 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004730 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004731 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4732
4733 // Check that the shift amount is in range. If not, don't perform
4734 // undefined shifts. When the shift is visited it will be
4735 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004736 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004737 break;
4738
Chris Lattner272d5ca2004-09-28 18:22:15 +00004739 // If we are comparing against bits always shifted out, the
4740 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004741 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004742 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004743 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004744 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4745 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004746 return ReplaceInstUsesWith(I, Cst);
4747 }
4748
4749 if (LHSI->hasOneUse()) {
4750 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004751 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004752 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4753
4754 Constant *Mask;
4755 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004756 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004757 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004758 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004759 } else {
4760 Mask = ConstantInt::getAllOnesValue(CI->getType());
4761 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004762
Chris Lattner272d5ca2004-09-28 18:22:15 +00004763 Instruction *AndI =
4764 BinaryOperator::createAnd(LHSI->getOperand(0),
4765 Mask, LHSI->getName()+".mask");
4766 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004767 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004768 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004769 }
4770 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004771 }
4772 break;
4773
Reid Spencer266e42b2006-12-23 06:05:41 +00004774 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004775 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004776 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004777 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004778 // Check that the shift amount is in range. If not, don't perform
4779 // undefined shifts. When the shift is visited it will be
4780 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004781 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004782 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004783 break;
4784
Chris Lattner1023b872004-09-27 16:18:50 +00004785 // If we are comparing against bits always shifted out, the
4786 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004787 Constant *Comp;
4788 if (CI->getType()->isUnsigned())
4789 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4790 ShAmt);
4791 else
4792 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4793 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004794
Chris Lattner1023b872004-09-27 16:18:50 +00004795 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004796 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4797 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004798 return ReplaceInstUsesWith(I, Cst);
4799 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004800
Chris Lattner1023b872004-09-27 16:18:50 +00004801 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004802 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004803
Chris Lattner1023b872004-09-27 16:18:50 +00004804 // Otherwise strength reduce the shift into an and.
4805 uint64_t Val = ~0ULL; // All ones.
4806 Val <<= ShAmtVal; // Shift over to the right spot.
4807
4808 Constant *Mask;
4809 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004810 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004811 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004812 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004813 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004814 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004815
Chris Lattner1023b872004-09-27 16:18:50 +00004816 Instruction *AndI =
4817 BinaryOperator::createAnd(LHSI->getOperand(0),
4818 Mask, LHSI->getName()+".mask");
4819 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004820 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004821 ConstantExpr::getShl(CI, ShAmt));
4822 }
Chris Lattner1023b872004-09-27 16:18:50 +00004823 }
4824 }
4825 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004826
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004827 case Instruction::SDiv:
4828 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004829 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004830 // Fold this div into the comparison, producing a range check.
4831 // Determine, based on the divide type, what the range is being
4832 // checked. If there is an overflow on the low or high side, remember
4833 // it, otherwise compute the range [low, hi) bounding the new value.
4834 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004835 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004836 // FIXME: If the operand types don't match the type of the divide
4837 // then don't attempt this transform. The code below doesn't have the
4838 // logic to deal with a signed divide and an unsigned compare (and
4839 // vice versa). This is because (x /s C1) <s C2 produces different
4840 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4841 // (x /u C1) <u C2. Simply casting the operands and result won't
4842 // work. :( The if statement below tests that condition and bails
4843 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004844 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4845 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004846 break;
4847
4848 // Initialize the variables that will indicate the nature of the
4849 // range check.
4850 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004851 ConstantInt *LoBound = 0, *HiBound = 0;
4852
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004853 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4854 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4855 // C2 (CI). By solving for X we can turn this into a range check
4856 // instead of computing a divide.
4857 ConstantInt *Prod =
4858 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004859
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004860 // Determine if the product overflows by seeing if the product is
4861 // not equal to the divide. Make sure we do the same kind of divide
4862 // as in the LHS instruction that we're folding.
4863 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004864 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004865 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4866
Reid Spencer266e42b2006-12-23 06:05:41 +00004867 // Get the ICmp opcode
4868 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004869
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004870 if (DivRHS->isNullValue()) {
4871 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004872 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004873 LoBound = Prod;
4874 LoOverflow = ProdOV;
4875 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004876 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004877 if (CI->isNullValue()) { // (X / pos) op 0
4878 // Can't overflow.
4879 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4880 HiBound = DivRHS;
4881 } else if (isPositive(CI)) { // (X / pos) op pos
4882 LoBound = Prod;
4883 LoOverflow = ProdOV;
4884 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4885 } else { // (X / pos) op neg
4886 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4887 LoOverflow = AddWithOverflow(LoBound, Prod,
4888 cast<ConstantInt>(DivRHSH));
4889 HiBound = Prod;
4890 HiOverflow = ProdOV;
4891 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004892 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004893 if (CI->isNullValue()) { // (X / neg) op 0
4894 LoBound = AddOne(DivRHS);
4895 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004896 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004897 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004898 } else if (isPositive(CI)) { // (X / neg) op pos
4899 HiOverflow = LoOverflow = ProdOV;
4900 if (!LoOverflow)
4901 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4902 HiBound = AddOne(Prod);
4903 } else { // (X / neg) op neg
4904 LoBound = Prod;
4905 LoOverflow = HiOverflow = ProdOV;
4906 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4907 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004908
Chris Lattnera92af962004-10-11 19:40:04 +00004909 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004910 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004911 }
4912
4913 if (LoBound) {
4914 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004915 switch (predicate) {
4916 default: assert(0 && "Unhandled icmp opcode!");
4917 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004918 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004919 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004920 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4922 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004923 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004924 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4925 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004926 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004927 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4928 true, I);
4929 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004930 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004931 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004932 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004933 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4934 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004935 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004936 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4937 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004938 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004939 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4940 false, I);
4941 case ICmpInst::ICMP_ULT:
4942 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004943 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004944 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 return new ICmpInst(predicate, X, LoBound);
4946 case ICmpInst::ICMP_UGT:
4947 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004948 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004949 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004950 if (predicate == ICmpInst::ICMP_UGT)
4951 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4952 else
4953 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004954 }
4955 }
4956 }
4957 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004958 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004959
Reid Spencer266e42b2006-12-23 06:05:41 +00004960 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004961 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004962 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004963
Reid Spencere0fc4df2006-10-20 07:07:24 +00004964 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4965 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004966 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4967 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004968 case Instruction::SRem:
4969 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4970 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4971 BO->hasOneUse()) {
4972 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4973 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004974 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4975 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004976 return new ICmpInst(I.getPredicate(), NewRem,
4977 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004978 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004979 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004980 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004981 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004982 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4983 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004984 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004985 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4986 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004987 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004988 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4989 // efficiently invertible, or if the add has just this one use.
4990 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004991
Chris Lattnerc992add2003-08-13 05:33:12 +00004992 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004993 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004994 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004995 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004996 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004997 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4998 BO->setName("");
4999 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005000 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005001 }
5002 }
5003 break;
5004 case Instruction::Xor:
5005 // For the xor case, we can xor two constants together, eliminating
5006 // the explicit xor.
5007 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005008 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5009 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005010
5011 // FALLTHROUGH
5012 case Instruction::Sub:
5013 // Replace (([sub|xor] A, B) != 0) with (A != B)
5014 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005015 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5016 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005017 break;
5018
5019 case Instruction::Or:
5020 // If bits are being or'd in that are not present in the constant we
5021 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005022 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005023 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005024 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005026 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005027 break;
5028
5029 case Instruction::And:
5030 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005031 // If bits are being compared against that are and'd out, then the
5032 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005033 if (!ConstantExpr::getAnd(CI,
5034 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005035 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005036
Chris Lattner35167c32004-06-09 07:59:58 +00005037 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005038 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5040 ICmpInst::ICMP_NE, Op0,
5041 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005042
Reid Spencer266e42b2006-12-23 06:05:41 +00005043 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005044 if (isSignBit(BOC)) {
5045 Value *X = BO->getOperand(0);
5046 // If 'X' is not signed, insert a cast now...
5047 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00005048 const Type *DestTy = BOC->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00005049 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00005050 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005051 Constant *Zero = Constant::getNullValue(X->getType());
5052 ICmpInst::Predicate pred = isICMP_NE ?
5053 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5054 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005055 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005056
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005057 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005058 if (CI->isNullValue() && isHighOnes(BOC)) {
5059 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005060 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005061 ICmpInst::Predicate pred = isICMP_NE ?
5062 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5063 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005064 }
5065
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005066 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005067 default: break;
5068 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005069 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5070 // Handle set{eq|ne} <intrinsic>, intcst.
5071 switch (II->getIntrinsicID()) {
5072 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005073 case Intrinsic::bswap_i16:
5074 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005075 WorkList.push_back(II); // Dead?
5076 I.setOperand(0, II->getOperand(1));
5077 I.setOperand(1, ConstantInt::get(Type::UShortTy,
5078 ByteSwap_16(CI->getZExtValue())));
5079 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005080 case Intrinsic::bswap_i32:
5081 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005082 WorkList.push_back(II); // Dead?
5083 I.setOperand(0, II->getOperand(1));
5084 I.setOperand(1, ConstantInt::get(Type::UIntTy,
5085 ByteSwap_32(CI->getZExtValue())));
5086 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005087 case Intrinsic::bswap_i64:
5088 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005089 WorkList.push_back(II); // Dead?
5090 I.setOperand(0, II->getOperand(1));
5091 I.setOperand(1, ConstantInt::get(Type::ULongTy,
5092 ByteSwap_64(CI->getZExtValue())));
5093 return &I;
5094 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005095 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005096 } else { // Not a ICMP_EQ/ICMP_NE
5097 // If the LHS is a cast from an integral value of the same size, then
5098 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005099 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5100 Value *CastOp = Cast->getOperand(0);
5101 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005102 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005103 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005104 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005105 // If this is an unsigned comparison, try to make the comparison use
5106 // smaller constant values.
5107 switch (I.getPredicate()) {
5108 default: break;
5109 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5110 ConstantInt *CUI = cast<ConstantInt>(CI);
5111 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5112 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5113 ConstantInt::get(SrcTy, -1));
5114 break;
5115 }
5116 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5117 ConstantInt *CUI = cast<ConstantInt>(CI);
5118 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5119 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5120 Constant::getNullValue(SrcTy));
5121 break;
5122 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005123 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005124
Chris Lattner2b55ea32004-02-23 07:16:20 +00005125 }
5126 }
Chris Lattnere967b342003-06-04 05:10:11 +00005127 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005128 }
5129
Reid Spencer266e42b2006-12-23 06:05:41 +00005130 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005131 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5132 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5133 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005134 case Instruction::GetElementPtr:
5135 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005136 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005137 bool isAllZeros = true;
5138 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5139 if (!isa<Constant>(LHSI->getOperand(i)) ||
5140 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5141 isAllZeros = false;
5142 break;
5143 }
5144 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005145 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005146 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5147 }
5148 break;
5149
Chris Lattner77c32c32005-04-23 15:31:55 +00005150 case Instruction::PHI:
5151 if (Instruction *NV = FoldOpIntoPhi(I))
5152 return NV;
5153 break;
5154 case Instruction::Select:
5155 // If either operand of the select is a constant, we can fold the
5156 // comparison into the select arms, which will cause one to be
5157 // constant folded and the select turned into a bitwise or.
5158 Value *Op1 = 0, *Op2 = 0;
5159 if (LHSI->hasOneUse()) {
5160 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5161 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005162 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5163 // Insert a new ICmp of the other select operand.
5164 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5165 LHSI->getOperand(2), RHSC,
5166 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005167 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5168 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005169 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5170 // Insert a new ICmp of the other select operand.
5171 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5172 LHSI->getOperand(1), RHSC,
5173 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005174 }
5175 }
Jeff Cohen82639852005-04-23 21:38:35 +00005176
Chris Lattner77c32c32005-04-23 15:31:55 +00005177 if (Op1)
5178 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5179 break;
5180 }
5181 }
5182
Reid Spencer266e42b2006-12-23 06:05:41 +00005183 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005184 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005185 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005186 return NI;
5187 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005188 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5189 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005190 return NI;
5191
Reid Spencer266e42b2006-12-23 06:05:41 +00005192 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner16930792003-11-03 04:25:02 +00005193 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00005194 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5195 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005196 if (CI->isLosslessCast() && I.isEquality() &&
5197 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005198 // We keep moving the cast from the left operand over to the right
5199 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00005200 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005201
Chris Lattner16930792003-11-03 04:25:02 +00005202 // If operand #1 is a cast instruction, see if we can eliminate it as
5203 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005204 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
5205 Value *CI2Op0 = CI2->getOperand(0);
5206 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5207 Op1 = CI2Op0;
5208 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005209
Chris Lattner16930792003-11-03 04:25:02 +00005210 // If Op1 is a constant, we can fold the cast into the constant.
5211 if (Op1->getType() != Op0->getType())
5212 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005213 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005214 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005215 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005216 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005217 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005218 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005219 }
5220
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005222 // This comes up when you have code like
5223 // int X = A < B;
5224 // if (X) ...
5225 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005226 // with a constant or another cast from the same type.
5227 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005228 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005229 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005230 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005231
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005232 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005233 Value *A, *B;
5234 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5235 (A == Op1 || B == Op1)) {
5236 // (A^B) == A -> B == 0
5237 Value *OtherVal = A == Op1 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005238 return new ICmpInst(I.getPredicate(), OtherVal,
5239 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005240 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5241 (A == Op0 || B == Op0)) {
5242 // A == (A^B) -> B == 0
5243 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005244 return new ICmpInst(I.getPredicate(), OtherVal,
5245 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005246 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5247 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005248 return new ICmpInst(I.getPredicate(), B,
5249 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005250 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5251 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005252 return new ICmpInst(I.getPredicate(), B,
5253 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005254 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005255
5256 Value *C, *D;
5257 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5258 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5259 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5260 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5261 Value *X = 0, *Y = 0, *Z = 0;
5262
5263 if (A == C) {
5264 X = B; Y = D; Z = A;
5265 } else if (A == D) {
5266 X = B; Y = C; Z = A;
5267 } else if (B == C) {
5268 X = A; Y = D; Z = B;
5269 } else if (B == D) {
5270 X = A; Y = C; Z = B;
5271 }
5272
5273 if (X) { // Build (X^Y) & Z
5274 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5275 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5276 I.setOperand(0, Op1);
5277 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5278 return &I;
5279 }
5280 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005281 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005282 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005283}
5284
Reid Spencer266e42b2006-12-23 06:05:41 +00005285// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005286// We only handle extending casts so far.
5287//
Reid Spencer266e42b2006-12-23 06:05:41 +00005288Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5289 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005290 Value *LHSCIOp = LHSCI->getOperand(0);
5291 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005292 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005293 Value *RHSCIOp;
5294
Reid Spencer266e42b2006-12-23 06:05:41 +00005295 // We only handle extension cast instructions, so far. Enforce this.
5296 if (LHSCI->getOpcode() != Instruction::ZExt &&
5297 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005298 return 0;
5299
Reid Spencer266e42b2006-12-23 06:05:41 +00005300 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5301 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005302
Reid Spencer266e42b2006-12-23 06:05:41 +00005303 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005304 // Not an extension from the same type?
5305 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005306 if (RHSCIOp->getType() != LHSCIOp->getType())
5307 return 0;
5308 else
5309 // Okay, just insert a compare of the reduced operands now!
5310 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005311 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005312
Reid Spencer266e42b2006-12-23 06:05:41 +00005313 // If we aren't dealing with a constant on the RHS, exit early
5314 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5315 if (!CI)
5316 return 0;
5317
5318 // Compute the constant that would happen if we truncated to SrcTy then
5319 // reextended to DestTy.
5320 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5321 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5322
5323 // If the re-extended constant didn't change...
5324 if (Res2 == CI) {
5325 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5326 // For example, we might have:
5327 // %A = sext short %X to uint
5328 // %B = icmp ugt uint %A, 1330
5329 // It is incorrect to transform this into
5330 // %B = icmp ugt short %X, 1330
5331 // because %A may have negative value.
5332 //
5333 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5334 // OR operation is EQ/NE.
5335 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5336 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5337 else
5338 return 0;
5339 }
5340
5341 // The re-extended constant changed so the constant cannot be represented
5342 // in the shorter type. Consequently, we cannot emit a simple comparison.
5343
5344 // First, handle some easy cases. We know the result cannot be equal at this
5345 // point so handle the ICI.isEquality() cases
5346 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5347 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5348 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5349 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5350
5351 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5352 // should have been folded away previously and not enter in here.
5353 Value *Result;
5354 if (isSignedCmp) {
5355 // We're performing a signed comparison.
5356 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5357 Result = ConstantBool::getFalse(); // X < (small) --> false
5358 else
5359 Result = ConstantBool::getTrue(); // X < (large) --> true
5360 } else {
5361 // We're performing an unsigned comparison.
5362 if (isSignedExt) {
5363 // We're performing an unsigned comp with a sign extended value.
5364 // This is true if the input is >= 0. [aka >s -1]
5365 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5366 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5367 NegOne, ICI.getName()), ICI);
5368 } else {
5369 // Unsigned extend & unsigned compare -> always true.
5370 Result = ConstantBool::getTrue();
5371 }
5372 }
5373
5374 // Finally, return the value computed.
5375 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5376 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5377 return ReplaceInstUsesWith(ICI, Result);
5378 } else {
5379 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5380 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5381 "ICmp should be folded!");
5382 if (Constant *CI = dyn_cast<Constant>(Result))
5383 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5384 else
5385 return BinaryOperator::createNot(Result);
5386 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005387}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005388
Chris Lattnere8d6c602003-03-10 19:16:08 +00005389Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005390 assert(I.getOperand(1)->getType() == Type::UByteTy);
5391 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005392
5393 // shl X, 0 == X and shr X, 0 == X
5394 // shl 0, X == 0 and shr 0, X == 0
5395 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005396 Op0 == Constant::getNullValue(Op0->getType()))
5397 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005398
Reid Spencer266e42b2006-12-23 06:05:41 +00005399 if (isa<UndefValue>(Op0)) {
5400 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005401 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005402 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005403 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5404 }
5405 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005406 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5407 return ReplaceInstUsesWith(I, Op0);
5408 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005409 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005410 }
5411
Chris Lattnerd4dee402006-11-10 23:38:52 +00005412 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5413 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005414 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005415 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005416 return ReplaceInstUsesWith(I, CSI);
5417
Chris Lattner183b3362004-04-09 19:05:30 +00005418 // Try to fold constant and into select arguments.
5419 if (isa<Constant>(Op0))
5420 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005421 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005422 return R;
5423
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005424 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005425 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005426 if (MaskedValueIsZero(Op0,
5427 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005428 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005429 }
5430 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005431
Reid Spencere0fc4df2006-10-20 07:07:24 +00005432 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5433 if (CUI->getType()->isUnsigned())
5434 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5435 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005436 return 0;
5437}
5438
Reid Spencere0fc4df2006-10-20 07:07:24 +00005439Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005440 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005441 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5442 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005443 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005444
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005445 // See if we can simplify any instructions used by the instruction whose sole
5446 // purpose is to compute bits we don't care about.
5447 uint64_t KnownZero, KnownOne;
5448 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5449 KnownZero, KnownOne))
5450 return &I;
5451
Chris Lattner14553932006-01-06 07:12:35 +00005452 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5453 // of a signed value.
5454 //
5455 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005456 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005457 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005458 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5459 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005460 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005461 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005462 }
Chris Lattner14553932006-01-06 07:12:35 +00005463 }
5464
5465 // ((X*C1) << C2) == (X * (C1 << C2))
5466 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5467 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5468 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5469 return BinaryOperator::createMul(BO->getOperand(0),
5470 ConstantExpr::getShl(BOOp, Op1));
5471
5472 // Try to fold constant and into select arguments.
5473 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5474 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5475 return R;
5476 if (isa<PHINode>(Op0))
5477 if (Instruction *NV = FoldOpIntoPhi(I))
5478 return NV;
5479
5480 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005481 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5482 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5483 Value *V1, *V2;
5484 ConstantInt *CC;
5485 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005486 default: break;
5487 case Instruction::Add:
5488 case Instruction::And:
5489 case Instruction::Or:
5490 case Instruction::Xor:
5491 // These operators commute.
5492 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005493 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5494 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005495 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
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)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005500 Instruction *X =
5501 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5502 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005503 InsertNewInstBefore(X, I); // (X + (Y << C))
5504 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005505 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005506 return BinaryOperator::createAnd(X, C2);
5507 }
Chris Lattner14553932006-01-06 07:12:35 +00005508
Chris Lattner797dee72005-09-18 06:30:59 +00005509 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5510 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5511 match(Op0BO->getOperand(1),
5512 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005513 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005514 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005515 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005516 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005517 Op0BO->getName());
5518 InsertNewInstBefore(YS, I); // (Y << C)
5519 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005520 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005521 V1->getName()+".mask");
5522 InsertNewInstBefore(XM, I); // X & (CC << C)
5523
5524 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5525 }
Chris Lattner14553932006-01-06 07:12:35 +00005526
Chris Lattner797dee72005-09-18 06:30:59 +00005527 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005528 case Instruction::Sub:
5529 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005530 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5531 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005532 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005533 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005534 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005535 Op0BO->getName());
5536 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005537 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005538 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005539 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005540 InsertNewInstBefore(X, I); // (X + (Y << C))
5541 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005542 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005543 return BinaryOperator::createAnd(X, C2);
5544 }
Chris Lattner14553932006-01-06 07:12:35 +00005545
Chris Lattner1df0e982006-05-31 21:14:00 +00005546 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005547 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5548 match(Op0BO->getOperand(0),
5549 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005550 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005551 cast<BinaryOperator>(Op0BO->getOperand(0))
5552 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005553 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005554 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005555 Op0BO->getName());
5556 InsertNewInstBefore(YS, I); // (Y << C)
5557 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005558 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005559 V1->getName()+".mask");
5560 InsertNewInstBefore(XM, I); // X & (CC << C)
5561
Chris Lattner1df0e982006-05-31 21:14:00 +00005562 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005563 }
Chris Lattner14553932006-01-06 07:12:35 +00005564
Chris Lattner27cb9db2005-09-18 05:12:10 +00005565 break;
Chris Lattner14553932006-01-06 07:12:35 +00005566 }
5567
5568
5569 // If the operand is an bitwise operator with a constant RHS, and the
5570 // shift is the only use, we can pull it out of the shift.
5571 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5572 bool isValid = true; // Valid only for And, Or, Xor
5573 bool highBitSet = false; // Transform if high bit of constant set?
5574
5575 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005576 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005577 case Instruction::Add:
5578 isValid = isLeftShift;
5579 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005580 case Instruction::Or:
5581 case Instruction::Xor:
5582 highBitSet = false;
5583 break;
5584 case Instruction::And:
5585 highBitSet = true;
5586 break;
Chris Lattner14553932006-01-06 07:12:35 +00005587 }
5588
5589 // If this is a signed shift right, and the high bit is modified
5590 // by the logical operation, do not perform the transformation.
5591 // The highBitSet boolean indicates the value of the high bit of
5592 // the constant which would cause it to be modified for this
5593 // operation.
5594 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005595 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005596 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005597 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5598 }
5599
5600 if (isValid) {
5601 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5602
5603 Instruction *NewShift =
5604 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5605 Op0BO->getName());
5606 Op0BO->setName("");
5607 InsertNewInstBefore(NewShift, I);
5608
5609 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5610 NewRHS);
5611 }
5612 }
5613 }
5614 }
5615
Chris Lattnereb372a02006-01-06 07:52:12 +00005616 // Find out if this is a shift of a shift by a constant.
5617 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005618 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005619 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005620 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5621 // If this is a noop-integer cast of a shift instruction, use the shift.
5622 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005623 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5624 }
5625 }
5626
Reid Spencere0fc4df2006-10-20 07:07:24 +00005627 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005628 // Find the operands and properties of the input shift. Note that the
5629 // signedness of the input shift may differ from the current shift if there
5630 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005631 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5632 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005633 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005634
Reid Spencere0fc4df2006-10-20 07:07:24 +00005635 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005636
Reid Spencere0fc4df2006-10-20 07:07:24 +00005637 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5638 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005639
5640 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5641 if (isLeftShift == isShiftOfLeftShift) {
5642 // Do not fold these shifts if the first one is signed and the second one
5643 // is unsigned and this is a right shift. Further, don't do any folding
5644 // on them.
5645 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5646 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005647
Chris Lattnereb372a02006-01-06 07:52:12 +00005648 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5649 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5650 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005651
Chris Lattnereb372a02006-01-06 07:52:12 +00005652 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005653 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencer74a528b2006-12-13 18:21:21 +00005654 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005655 if (I.getType() == ShiftResult->getType())
5656 return ShiftResult;
5657 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005658 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005659 }
5660
5661 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5662 // signed types, we can only support the (A >> c1) << c2 configuration,
5663 // because it can not turn an arbitrary bit of A into a sign bit.
5664 if (isUnsignedShift || isLeftShift) {
5665 // Calculate bitmask for what gets shifted off the edge.
5666 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5667 if (isLeftShift)
5668 C = ConstantExpr::getShl(C, ShiftAmt1C);
5669 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005670 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005671
5672 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005673 if (Op->getType() != C->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00005674 Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005675
5676 Instruction *Mask =
5677 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5678 InsertNewInstBefore(Mask, I);
5679
5680 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005681 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005682 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005683 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005684 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005685 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005686 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5687 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005688 return new ShiftInst(Instruction::LShr, Mask,
5689 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005690 } else {
5691 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005692 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005693 }
5694 } else {
5695 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005696 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005697 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005698 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005699 InsertNewInstBefore(Shift, I);
5700
5701 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5702 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005703 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005704 }
5705 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005706 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005707 // this case, C1 == C2 and C1 is 8, 16, or 32.
5708 if (ShiftAmt1 == ShiftAmt2) {
5709 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005710 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005711 case 8 : SExtType = Type::SByteTy; break;
5712 case 16: SExtType = Type::ShortTy; break;
5713 case 32: SExtType = Type::IntTy; break;
5714 }
5715
5716 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005717 Instruction *NewTrunc =
5718 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005719 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005720 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005721 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005722 }
Chris Lattner86102b82005-01-01 16:22:27 +00005723 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005724 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005725 return 0;
5726}
5727
Chris Lattner48a44f72002-05-02 17:06:02 +00005728
Chris Lattner8f663e82005-10-29 04:36:15 +00005729/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5730/// expression. If so, decompose it, returning some value X, such that Val is
5731/// X*Scale+Offset.
5732///
5733static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5734 unsigned &Offset) {
5735 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005736 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5737 if (CI->getType()->isUnsigned()) {
5738 Offset = CI->getZExtValue();
5739 Scale = 1;
5740 return ConstantInt::get(Type::UIntTy, 0);
5741 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005742 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5743 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005744 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5745 if (CUI->getType()->isUnsigned()) {
5746 if (I->getOpcode() == Instruction::Shl) {
5747 // This is a value scaled by '1 << the shift amt'.
5748 Scale = 1U << CUI->getZExtValue();
5749 Offset = 0;
5750 return I->getOperand(0);
5751 } else if (I->getOpcode() == Instruction::Mul) {
5752 // This value is scaled by 'CUI'.
5753 Scale = CUI->getZExtValue();
5754 Offset = 0;
5755 return I->getOperand(0);
5756 } else if (I->getOpcode() == Instruction::Add) {
5757 // We have X+C. Check to see if we really have (X*C2)+C1,
5758 // where C1 is divisible by C2.
5759 unsigned SubScale;
5760 Value *SubVal =
5761 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5762 Offset += CUI->getZExtValue();
5763 if (SubScale > 1 && (Offset % SubScale == 0)) {
5764 Scale = SubScale;
5765 return SubVal;
5766 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005767 }
5768 }
5769 }
5770 }
5771 }
5772
5773 // Otherwise, we can't look past this.
5774 Scale = 1;
5775 Offset = 0;
5776 return Val;
5777}
5778
5779
Chris Lattner216be912005-10-24 06:03:58 +00005780/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5781/// try to eliminate the cast by moving the type information into the alloc.
5782Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5783 AllocationInst &AI) {
5784 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005785 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005786
Chris Lattnerac87beb2005-10-24 06:22:12 +00005787 // Remove any uses of AI that are dead.
5788 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5789 std::vector<Instruction*> DeadUsers;
5790 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5791 Instruction *User = cast<Instruction>(*UI++);
5792 if (isInstructionTriviallyDead(User)) {
5793 while (UI != E && *UI == User)
5794 ++UI; // If this instruction uses AI more than once, don't break UI.
5795
5796 // Add operands to the worklist.
5797 AddUsesToWorkList(*User);
5798 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005799 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005800
5801 User->eraseFromParent();
5802 removeFromWorkList(User);
5803 }
5804 }
5805
Chris Lattner216be912005-10-24 06:03:58 +00005806 // Get the type really allocated and the type casted to.
5807 const Type *AllocElTy = AI.getAllocatedType();
5808 const Type *CastElTy = PTy->getElementType();
5809 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005810
Chris Lattner7d190672006-10-01 19:40:58 +00005811 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5812 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005813 if (CastElTyAlign < AllocElTyAlign) return 0;
5814
Chris Lattner46705b22005-10-24 06:35:18 +00005815 // If the allocation has multiple uses, only promote it if we are strictly
5816 // increasing the alignment of the resultant allocation. If we keep it the
5817 // same, we open the door to infinite loops of various kinds.
5818 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5819
Chris Lattner216be912005-10-24 06:03:58 +00005820 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5821 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005822 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005823
Chris Lattner8270c332005-10-29 03:19:53 +00005824 // See if we can satisfy the modulus by pulling a scale out of the array
5825 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005826 unsigned ArraySizeScale, ArrayOffset;
5827 Value *NumElements = // See if the array size is a decomposable linear expr.
5828 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5829
Chris Lattner8270c332005-10-29 03:19:53 +00005830 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5831 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005832 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5833 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005834
Chris Lattner8270c332005-10-29 03:19:53 +00005835 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5836 Value *Amt = 0;
5837 if (Scale == 1) {
5838 Amt = NumElements;
5839 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005840 // If the allocation size is constant, form a constant mul expression
5841 Amt = ConstantInt::get(Type::UIntTy, Scale);
5842 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5843 Amt = ConstantExpr::getMul(
5844 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5845 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005846 else if (Scale != 1) {
5847 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5848 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005849 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005850 }
5851
Chris Lattner8f663e82005-10-29 04:36:15 +00005852 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005853 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005854 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5855 Amt = InsertNewInstBefore(Tmp, AI);
5856 }
5857
Chris Lattner216be912005-10-24 06:03:58 +00005858 std::string Name = AI.getName(); AI.setName("");
5859 AllocationInst *New;
5860 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005861 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005862 else
Nate Begeman848622f2005-11-05 09:21:28 +00005863 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005864 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005865
5866 // If the allocation has multiple uses, insert a cast and change all things
5867 // that used it to use the new cast. This will also hack on CI, but it will
5868 // die soon.
5869 if (!AI.hasOneUse()) {
5870 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005871 // New is the allocation instruction, pointer typed. AI is the original
5872 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5873 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005874 InsertNewInstBefore(NewCast, AI);
5875 AI.replaceAllUsesWith(NewCast);
5876 }
Chris Lattner216be912005-10-24 06:03:58 +00005877 return ReplaceInstUsesWith(CI, New);
5878}
5879
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005880/// CanEvaluateInDifferentType - Return true if we can take the specified value
5881/// and return it without inserting any new casts. This is used by code that
5882/// tries to decide whether promoting or shrinking integer operations to wider
5883/// or smaller types will allow us to eliminate a truncate or extend.
5884static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5885 int &NumCastsRemoved) {
5886 if (isa<Constant>(V)) return true;
5887
5888 Instruction *I = dyn_cast<Instruction>(V);
5889 if (!I || !I->hasOneUse()) return false;
5890
5891 switch (I->getOpcode()) {
5892 case Instruction::And:
5893 case Instruction::Or:
5894 case Instruction::Xor:
5895 // These operators can all arbitrarily be extended or truncated.
5896 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5897 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005898 case Instruction::AShr:
5899 case Instruction::LShr:
5900 case Instruction::Shl:
5901 // If this is just a bitcast changing the sign of the operation, we can
5902 // convert if the operand can be converted.
5903 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5904 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5905 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005906 case Instruction::Trunc:
5907 case Instruction::ZExt:
5908 case Instruction::SExt:
5909 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005910 // If this is a cast from the destination type, we can trivially eliminate
5911 // it, and this will remove a cast overall.
5912 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005913 // If the first operand is itself a cast, and is eliminable, do not count
5914 // this as an eliminable cast. We would prefer to eliminate those two
5915 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005916 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005917 return true;
5918
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005919 ++NumCastsRemoved;
5920 return true;
5921 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005922 break;
5923 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005924 // TODO: Can handle more cases here.
5925 break;
5926 }
5927
5928 return false;
5929}
5930
5931/// EvaluateInDifferentType - Given an expression that
5932/// CanEvaluateInDifferentType returns true for, actually insert the code to
5933/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005934Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5935 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005936 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005937 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005938
5939 // Otherwise, it must be an instruction.
5940 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005941 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005942 switch (I->getOpcode()) {
5943 case Instruction::And:
5944 case Instruction::Or:
5945 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005946 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5947 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005948 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5949 LHS, RHS, I->getName());
5950 break;
5951 }
Chris Lattner960acb02006-11-29 07:18:39 +00005952 case Instruction::AShr:
5953 case Instruction::LShr:
5954 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005955 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005956 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5957 I->getOperand(1), I->getName());
5958 break;
5959 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005960 case Instruction::Trunc:
5961 case Instruction::ZExt:
5962 case Instruction::SExt:
5963 case Instruction::BitCast:
5964 // If the source type of the cast is the type we're trying for then we can
5965 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005966 if (I->getOperand(0)->getType() == Ty)
5967 return I->getOperand(0);
5968
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005969 // Some other kind of cast, which shouldn't happen, so just ..
5970 // FALL THROUGH
5971 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005972 // TODO: Can handle more cases here.
5973 assert(0 && "Unreachable!");
5974 break;
5975 }
5976
5977 return InsertNewInstBefore(Res, *I);
5978}
5979
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005980/// @brief Implement the transforms common to all CastInst visitors.
5981Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005982 Value *Src = CI.getOperand(0);
5983
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005984 // Casting undef to anything results in undef so might as just replace it and
5985 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005986 if (isa<UndefValue>(Src)) // cast undef -> undef
5987 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5988
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005989 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5990 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005991 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005992 if (Instruction::CastOps opc =
5993 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5994 // The first cast (CSrc) is eliminable so we need to fix up or replace
5995 // the second cast (CI). CSrc will then have a good chance of being dead.
5996 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005997 }
5998 }
Chris Lattner03841652004-05-25 04:29:21 +00005999
Chris Lattnerd0d51602003-06-21 23:12:02 +00006000 // If casting the result of a getelementptr instruction with no offset, turn
6001 // this into a cast of the original pointer!
6002 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006003 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006004 bool AllZeroOperands = true;
6005 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6006 if (!isa<Constant>(GEP->getOperand(i)) ||
6007 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6008 AllZeroOperands = false;
6009 break;
6010 }
6011 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006012 // Changing the cast operand is usually not a good idea but it is safe
6013 // here because the pointer operand is being replaced with another
6014 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006015 CI.setOperand(0, GEP->getOperand(0));
6016 return &CI;
6017 }
6018 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006019
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006020 // If we are casting a malloc or alloca to a pointer to a type of the same
6021 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006022 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006023 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6024 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006025
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006026 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006027 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6028 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6029 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006030
6031 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006032 if (isa<PHINode>(Src))
6033 if (Instruction *NV = FoldOpIntoPhi(CI))
6034 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006035
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006036 return 0;
6037}
6038
6039/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6040/// integers. This function implements the common transforms for all those
6041/// cases.
6042/// @brief Implement the transforms common to CastInst with integer operands
6043Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6044 if (Instruction *Result = commonCastTransforms(CI))
6045 return Result;
6046
6047 Value *Src = CI.getOperand(0);
6048 const Type *SrcTy = Src->getType();
6049 const Type *DestTy = CI.getType();
6050 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6051 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6052
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006053 // See if we can simplify any instructions used by the LHS whose sole
6054 // purpose is to compute bits we don't care about.
6055 uint64_t KnownZero = 0, KnownOne = 0;
6056 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6057 KnownZero, KnownOne))
6058 return &CI;
6059
6060 // If the source isn't an instruction or has more than one use then we
6061 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006062 Instruction *SrcI = dyn_cast<Instruction>(Src);
6063 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006064 return 0;
6065
6066 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006067 int NumCastsRemoved = 0;
6068 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6069 // If this cast is a truncate, evaluting in a different type always
6070 // eliminates the cast, so it is always a win. If this is a noop-cast
6071 // this just removes a noop cast which isn't pointful, but simplifies
6072 // the code. If this is a zero-extension, we need to do an AND to
6073 // maintain the clear top-part of the computation, so we require that
6074 // the input have eliminated at least one cast. If this is a sign
6075 // extension, we insert two new casts (to do the extension) so we
6076 // require that two casts have been eliminated.
6077 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6078 if (!DoXForm) {
6079 switch (CI.getOpcode()) {
6080 case Instruction::Trunc:
6081 DoXForm = true;
6082 break;
6083 case Instruction::ZExt:
6084 DoXForm = NumCastsRemoved >= 1;
6085 break;
6086 case Instruction::SExt:
6087 DoXForm = NumCastsRemoved >= 2;
6088 break;
6089 case Instruction::BitCast:
6090 DoXForm = false;
6091 break;
6092 default:
6093 // All the others use floating point so we shouldn't actually
6094 // get here because of the check above.
6095 assert(!"Unknown cast type .. unreachable");
6096 break;
6097 }
6098 }
6099
6100 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006101 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6102 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006103 assert(Res->getType() == DestTy);
6104 switch (CI.getOpcode()) {
6105 default: assert(0 && "Unknown cast type!");
6106 case Instruction::Trunc:
6107 case Instruction::BitCast:
6108 // Just replace this cast with the result.
6109 return ReplaceInstUsesWith(CI, Res);
6110 case Instruction::ZExt: {
6111 // We need to emit an AND to clear the high bits.
6112 assert(SrcBitSize < DestBitSize && "Not a zext?");
6113 Constant *C =
6114 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
6115 if (DestBitSize < 64)
6116 C = ConstantExpr::getTrunc(C, DestTy);
6117 else {
6118 assert(DestBitSize == 64);
6119 C = ConstantExpr::getBitCast(C, DestTy);
6120 }
6121 return BinaryOperator::createAnd(Res, C);
6122 }
6123 case Instruction::SExt:
6124 // We need to emit a cast to truncate, then a cast to sext.
6125 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006126 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6127 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006128 }
6129 }
6130 }
6131
6132 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6133 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6134
6135 switch (SrcI->getOpcode()) {
6136 case Instruction::Add:
6137 case Instruction::Mul:
6138 case Instruction::And:
6139 case Instruction::Or:
6140 case Instruction::Xor:
6141 // If we are discarding information, or just changing the sign,
6142 // rewrite.
6143 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
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.
6147 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006148 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6149 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006150 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006151 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6152 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6153 return BinaryOperator::create(
6154 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006155 }
6156 }
6157
6158 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6159 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6160 SrcI->getOpcode() == Instruction::Xor &&
6161 Op1 == ConstantBool::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006162 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006163 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006164 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6165 }
6166 break;
6167 case Instruction::SDiv:
6168 case Instruction::UDiv:
6169 case Instruction::SRem:
6170 case Instruction::URem:
6171 // If we are just changing the sign, rewrite.
6172 if (DestBitSize == SrcBitSize) {
6173 // Don't insert two casts if they cannot be eliminated. We allow
6174 // two casts to be inserted if the sizes are the same. This could
6175 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006176 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6177 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006178 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6179 Op0, DestTy, SrcI);
6180 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6181 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006182 return BinaryOperator::create(
6183 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6184 }
6185 }
6186 break;
6187
6188 case Instruction::Shl:
6189 // Allow changing the sign of the source operand. Do not allow
6190 // changing the size of the shift, UNLESS the shift amount is a
6191 // constant. We must not change variable sized shifts to a smaller
6192 // size, because it is undefined to shift more bits out than exist
6193 // in the value.
6194 if (DestBitSize == SrcBitSize ||
6195 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006196 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6197 Instruction::BitCast : Instruction::Trunc);
6198 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006199 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6200 }
6201 break;
6202 case Instruction::AShr:
6203 // If this is a signed shr, and if all bits shifted in are about to be
6204 // truncated off, turn it into an unsigned shr to allow greater
6205 // simplifications.
6206 if (DestBitSize < SrcBitSize &&
6207 isa<ConstantInt>(Op1)) {
6208 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6209 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6210 // Insert the new logical shift right.
6211 return new ShiftInst(Instruction::LShr, Op0, Op1);
6212 }
6213 }
6214 break;
6215
Reid Spencer266e42b2006-12-23 06:05:41 +00006216 case Instruction::ICmp:
6217 // If we are just checking for a icmp eq of a single bit and casting it
6218 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006219 // cast to integer to avoid the comparison.
6220 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6221 uint64_t Op1CV = Op1C->getZExtValue();
6222 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6223 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6224 // cast (X == 1) to int --> X iff X has only the low bit set.
6225 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6226 // cast (X != 0) to int --> X iff X has only the low bit set.
6227 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6228 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6229 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6230 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6231 // If Op1C some other power of two, convert:
6232 uint64_t KnownZero, KnownOne;
6233 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6234 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006235
6236 // This only works for EQ and NE
6237 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6238 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6239 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006240
6241 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006242 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006243 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6244 // (X&4) == 2 --> false
6245 // (X&4) != 2 --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006246 Constant *Res = ConstantBool::get(isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006247 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006248 return ReplaceInstUsesWith(CI, Res);
6249 }
6250
6251 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6252 Value *In = Op0;
6253 if (ShiftAmt) {
6254 // Perform a logical shr by shiftamt.
6255 // Insert the shift to put the result in the low bit.
6256 In = InsertNewInstBefore(
6257 new ShiftInst(Instruction::LShr, In,
6258 ConstantInt::get(Type::UByteTy, ShiftAmt),
6259 In->getName()+".lobit"), CI);
6260 }
6261
Reid Spencer266e42b2006-12-23 06:05:41 +00006262 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006263 Constant *One = ConstantInt::get(In->getType(), 1);
6264 In = BinaryOperator::createXor(In, One, "tmp");
6265 InsertNewInstBefore(cast<Instruction>(In), CI);
6266 }
6267
6268 if (CI.getType() == In->getType())
6269 return ReplaceInstUsesWith(CI, In);
6270 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006271 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006272 }
6273 }
6274 }
6275 break;
6276 }
6277 return 0;
6278}
6279
6280Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006281 if (Instruction *Result = commonIntCastTransforms(CI))
6282 return Result;
6283
6284 Value *Src = CI.getOperand(0);
6285 const Type *Ty = CI.getType();
6286 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6287
6288 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6289 switch (SrcI->getOpcode()) {
6290 default: break;
6291 case Instruction::LShr:
6292 // We can shrink lshr to something smaller if we know the bits shifted in
6293 // are already zeros.
6294 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6295 unsigned ShAmt = ShAmtV->getZExtValue();
6296
6297 // Get a mask for the bits shifting in.
6298 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006299 Value* SrcIOp0 = SrcI->getOperand(0);
6300 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006301 if (ShAmt >= DestBitWidth) // All zeros.
6302 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6303
6304 // Okay, we can shrink this. Truncate the input, then return a new
6305 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006306 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006307 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6308 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006309 } else { // This is a variable shr.
6310
6311 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6312 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6313 // loop-invariant and CSE'd.
6314 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6315 Value *One = ConstantInt::get(SrcI->getType(), 1);
6316
6317 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6318 SrcI->getOperand(1),
6319 "tmp"), CI);
6320 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6321 SrcI->getOperand(0),
6322 "tmp"), CI);
6323 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006324 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006325 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006326 }
6327 break;
6328 }
6329 }
6330
6331 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006332}
6333
6334Instruction *InstCombiner::visitZExt(CastInst &CI) {
6335 // If one of the common conversion will work ..
6336 if (Instruction *Result = commonIntCastTransforms(CI))
6337 return Result;
6338
6339 Value *Src = CI.getOperand(0);
6340
6341 // If this is a cast of a cast
6342 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006343 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6344 // types and if the sizes are just right we can convert this into a logical
6345 // 'and' which will be much cheaper than the pair of casts.
6346 if (isa<TruncInst>(CSrc)) {
6347 // Get the sizes of the types involved
6348 Value *A = CSrc->getOperand(0);
6349 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6350 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6351 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6352 // If we're actually extending zero bits and the trunc is a no-op
6353 if (MidSize < DstSize && SrcSize == DstSize) {
6354 // Replace both of the casts with an And of the type mask.
6355 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6356 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6357 Instruction *And =
6358 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6359 // Unfortunately, if the type changed, we need to cast it back.
6360 if (And->getType() != CI.getType()) {
6361 And->setName(CSrc->getName()+".mask");
6362 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006363 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006364 }
6365 return And;
6366 }
6367 }
6368 }
6369
6370 return 0;
6371}
6372
6373Instruction *InstCombiner::visitSExt(CastInst &CI) {
6374 return commonIntCastTransforms(CI);
6375}
6376
6377Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6378 return commonCastTransforms(CI);
6379}
6380
6381Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6382 return commonCastTransforms(CI);
6383}
6384
6385Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006386 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006387}
6388
6389Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006390 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006391}
6392
6393Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6394 return commonCastTransforms(CI);
6395}
6396
6397Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6398 return commonCastTransforms(CI);
6399}
6400
6401Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006402 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006403}
6404
6405Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6406 return commonCastTransforms(CI);
6407}
6408
6409Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6410
6411 // If the operands are integer typed then apply the integer transforms,
6412 // otherwise just apply the common ones.
6413 Value *Src = CI.getOperand(0);
6414 const Type *SrcTy = Src->getType();
6415 const Type *DestTy = CI.getType();
6416
6417 if (SrcTy->isInteger() && DestTy->isInteger()) {
6418 if (Instruction *Result = commonIntCastTransforms(CI))
6419 return Result;
6420 } else {
6421 if (Instruction *Result = commonCastTransforms(CI))
6422 return Result;
6423 }
6424
6425
6426 // Get rid of casts from one type to the same type. These are useless and can
6427 // be replaced by the operand.
6428 if (DestTy == Src->getType())
6429 return ReplaceInstUsesWith(CI, Src);
6430
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006431 // If the source and destination are pointers, and this cast is equivalent to
6432 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6433 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006434 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6435 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6436 const Type *DstElTy = DstPTy->getElementType();
6437 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006438
6439 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6440 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006441 while (SrcElTy != DstElTy &&
6442 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6443 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6444 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006445 ++NumZeros;
6446 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006447
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006448 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006449 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006450 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6451 return new GetElementPtrInst(Src, Idxs);
6452 }
6453 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006454 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006455
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006456 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6457 if (SVI->hasOneUse()) {
6458 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6459 // a bitconvert to a vector with the same # elts.
6460 if (isa<PackedType>(DestTy) &&
6461 cast<PackedType>(DestTy)->getNumElements() ==
6462 SVI->getType()->getNumElements()) {
6463 CastInst *Tmp;
6464 // If either of the operands is a cast from CI.getType(), then
6465 // evaluating the shuffle in the casted destination's type will allow
6466 // us to eliminate at least one cast.
6467 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6468 Tmp->getOperand(0)->getType() == DestTy) ||
6469 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6470 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006471 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6472 SVI->getOperand(0), DestTy, &CI);
6473 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6474 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006475 // Return a new shuffle vector. Use the same element ID's, as we
6476 // know the vector types match #elts.
6477 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006478 }
6479 }
6480 }
6481 }
Chris Lattner260ab202002-04-18 17:39:14 +00006482 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006483}
6484
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006485/// GetSelectFoldableOperands - We want to turn code that looks like this:
6486/// %C = or %A, %B
6487/// %D = select %cond, %C, %A
6488/// into:
6489/// %C = select %cond, %B, 0
6490/// %D = or %A, %C
6491///
6492/// Assuming that the specified instruction is an operand to the select, return
6493/// a bitmask indicating which operands of this instruction are foldable if they
6494/// equal the other incoming value of the select.
6495///
6496static unsigned GetSelectFoldableOperands(Instruction *I) {
6497 switch (I->getOpcode()) {
6498 case Instruction::Add:
6499 case Instruction::Mul:
6500 case Instruction::And:
6501 case Instruction::Or:
6502 case Instruction::Xor:
6503 return 3; // Can fold through either operand.
6504 case Instruction::Sub: // Can only fold on the amount subtracted.
6505 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006506 case Instruction::LShr:
6507 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006508 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006509 default:
6510 return 0; // Cannot fold
6511 }
6512}
6513
6514/// GetSelectFoldableConstant - For the same transformation as the previous
6515/// function, return the identity constant that goes into the select.
6516static Constant *GetSelectFoldableConstant(Instruction *I) {
6517 switch (I->getOpcode()) {
6518 default: assert(0 && "This cannot happen!"); abort();
6519 case Instruction::Add:
6520 case Instruction::Sub:
6521 case Instruction::Or:
6522 case Instruction::Xor:
6523 return Constant::getNullValue(I->getType());
6524 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006525 case Instruction::LShr:
6526 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006527 return Constant::getNullValue(Type::UByteTy);
6528 case Instruction::And:
6529 return ConstantInt::getAllOnesValue(I->getType());
6530 case Instruction::Mul:
6531 return ConstantInt::get(I->getType(), 1);
6532 }
6533}
6534
Chris Lattner411336f2005-01-19 21:50:18 +00006535/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6536/// have the same opcode and only one use each. Try to simplify this.
6537Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6538 Instruction *FI) {
6539 if (TI->getNumOperands() == 1) {
6540 // If this is a non-volatile load or a cast from the same type,
6541 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006542 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006543 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6544 return 0;
6545 } else {
6546 return 0; // unknown unary op.
6547 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006548
Chris Lattner411336f2005-01-19 21:50:18 +00006549 // Fold this by inserting a select from the input values.
6550 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6551 FI->getOperand(0), SI.getName()+".v");
6552 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006553 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6554 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006555 }
6556
Reid Spencer266e42b2006-12-23 06:05:41 +00006557 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006558 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006559 return 0;
6560
6561 // Figure out if the operations have any operands in common.
6562 Value *MatchOp, *OtherOpT, *OtherOpF;
6563 bool MatchIsOpZero;
6564 if (TI->getOperand(0) == FI->getOperand(0)) {
6565 MatchOp = TI->getOperand(0);
6566 OtherOpT = TI->getOperand(1);
6567 OtherOpF = FI->getOperand(1);
6568 MatchIsOpZero = true;
6569 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6570 MatchOp = TI->getOperand(1);
6571 OtherOpT = TI->getOperand(0);
6572 OtherOpF = FI->getOperand(0);
6573 MatchIsOpZero = false;
6574 } else if (!TI->isCommutative()) {
6575 return 0;
6576 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6577 MatchOp = TI->getOperand(0);
6578 OtherOpT = TI->getOperand(1);
6579 OtherOpF = FI->getOperand(0);
6580 MatchIsOpZero = true;
6581 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6582 MatchOp = TI->getOperand(1);
6583 OtherOpT = TI->getOperand(0);
6584 OtherOpF = FI->getOperand(1);
6585 MatchIsOpZero = true;
6586 } else {
6587 return 0;
6588 }
6589
6590 // If we reach here, they do have operations in common.
6591 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6592 OtherOpF, SI.getName()+".v");
6593 InsertNewInstBefore(NewSI, SI);
6594
6595 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6596 if (MatchIsOpZero)
6597 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6598 else
6599 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006600 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006601
6602 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6603 if (MatchIsOpZero)
6604 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6605 else
6606 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006607}
6608
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006609Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006610 Value *CondVal = SI.getCondition();
6611 Value *TrueVal = SI.getTrueValue();
6612 Value *FalseVal = SI.getFalseValue();
6613
6614 // select true, X, Y -> X
6615 // select false, X, Y -> Y
6616 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006617 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006618
6619 // select C, X, X -> X
6620 if (TrueVal == FalseVal)
6621 return ReplaceInstUsesWith(SI, TrueVal);
6622
Chris Lattner81a7a232004-10-16 18:11:37 +00006623 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6624 return ReplaceInstUsesWith(SI, FalseVal);
6625 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6626 return ReplaceInstUsesWith(SI, TrueVal);
6627 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6628 if (isa<Constant>(TrueVal))
6629 return ReplaceInstUsesWith(SI, TrueVal);
6630 else
6631 return ReplaceInstUsesWith(SI, FalseVal);
6632 }
6633
Chris Lattner1c631e82004-04-08 04:43:23 +00006634 if (SI.getType() == Type::BoolTy)
6635 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006636 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006637 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006638 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006639 } else {
6640 // Change: A = select B, false, C --> A = and !B, C
6641 Value *NotCond =
6642 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6643 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006644 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006645 }
6646 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006647 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006648 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006649 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006650 } else {
6651 // Change: A = select B, C, true --> A = or !B, C
6652 Value *NotCond =
6653 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6654 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006655 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006656 }
6657 }
6658
Chris Lattner183b3362004-04-09 19:05:30 +00006659 // Selecting between two integer constants?
6660 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6661 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6662 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006663 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006664 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006665 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006666 // select C, 0, 1 -> cast !C to int
6667 Value *NotCond =
6668 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006669 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006670 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006671 }
Chris Lattner35167c32004-06-09 07:59:58 +00006672
Reid Spencer266e42b2006-12-23 06:05:41 +00006673 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006674
Reid Spencer266e42b2006-12-23 06:05:41 +00006675 // (x <s 0) ? -1 : 0 -> ashr x, 31
6676 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006677 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6678 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6679 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006680 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006681 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006682 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006683 else {
6684 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006685 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006686 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006687 }
6688
6689 if (CanXForm) {
6690 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006691 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006692 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006693 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006694 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006695 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006696 ShAmt, "ones");
6697 InsertNewInstBefore(SRA, SI);
6698
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006699 // Finally, convert to the type of the select RHS. We figure out
6700 // if this requires a SExt, Trunc or BitCast based on the sizes.
6701 Instruction::CastOps opc = Instruction::BitCast;
6702 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6703 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6704 if (SRASize < SISize)
6705 opc = Instruction::SExt;
6706 else if (SRASize > SISize)
6707 opc = Instruction::Trunc;
6708 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006709 }
6710 }
6711
6712
6713 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006714 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006715 // non-constant value, eliminate this whole mess. This corresponds to
6716 // cases like this: ((X & 27) ? 27 : 0)
6717 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006718 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006719 cast<Constant>(IC->getOperand(1))->isNullValue())
6720 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6721 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006722 isa<ConstantInt>(ICA->getOperand(1)) &&
6723 (ICA->getOperand(1) == TrueValC ||
6724 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006725 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6726 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006727 // know whether we have a icmp_ne or icmp_eq and whether the
6728 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006729 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006730 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006731 Value *V = ICA;
6732 if (ShouldNotVal)
6733 V = InsertNewInstBefore(BinaryOperator::create(
6734 Instruction::Xor, V, ICA->getOperand(1)), SI);
6735 return ReplaceInstUsesWith(SI, V);
6736 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006737 }
Chris Lattner533bc492004-03-30 19:37:13 +00006738 }
Chris Lattner623fba12004-04-10 22:21:27 +00006739
6740 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006741 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6742 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006743 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006744 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006745 return ReplaceInstUsesWith(SI, FalseVal);
6746 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006747 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006748 return ReplaceInstUsesWith(SI, TrueVal);
6749 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6750
Reid Spencer266e42b2006-12-23 06:05:41 +00006751 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006752 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006753 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006754 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006755 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006756 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6757 return ReplaceInstUsesWith(SI, TrueVal);
6758 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6759 }
6760 }
6761
6762 // See if we are selecting two values based on a comparison of the two values.
6763 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6764 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6765 // Transform (X == Y) ? X : Y -> Y
6766 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6767 return ReplaceInstUsesWith(SI, FalseVal);
6768 // Transform (X != Y) ? X : Y -> X
6769 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6770 return ReplaceInstUsesWith(SI, TrueVal);
6771 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6772
6773 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6774 // Transform (X == Y) ? Y : X -> X
6775 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6776 return ReplaceInstUsesWith(SI, FalseVal);
6777 // Transform (X != Y) ? Y : X -> Y
6778 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006779 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006780 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6781 }
6782 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006783
Chris Lattnera04c9042005-01-13 22:52:24 +00006784 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6785 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6786 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006787 Instruction *AddOp = 0, *SubOp = 0;
6788
Chris Lattner411336f2005-01-19 21:50:18 +00006789 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6790 if (TI->getOpcode() == FI->getOpcode())
6791 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6792 return IV;
6793
6794 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6795 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006796 if (TI->getOpcode() == Instruction::Sub &&
6797 FI->getOpcode() == Instruction::Add) {
6798 AddOp = FI; SubOp = TI;
6799 } else if (FI->getOpcode() == Instruction::Sub &&
6800 TI->getOpcode() == Instruction::Add) {
6801 AddOp = TI; SubOp = FI;
6802 }
6803
6804 if (AddOp) {
6805 Value *OtherAddOp = 0;
6806 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6807 OtherAddOp = AddOp->getOperand(1);
6808 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6809 OtherAddOp = AddOp->getOperand(0);
6810 }
6811
6812 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006813 // So at this point we know we have (Y -> OtherAddOp):
6814 // select C, (add X, Y), (sub X, Z)
6815 Value *NegVal; // Compute -Z
6816 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6817 NegVal = ConstantExpr::getNeg(C);
6818 } else {
6819 NegVal = InsertNewInstBefore(
6820 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006821 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006822
6823 Value *NewTrueOp = OtherAddOp;
6824 Value *NewFalseOp = NegVal;
6825 if (AddOp != TI)
6826 std::swap(NewTrueOp, NewFalseOp);
6827 Instruction *NewSel =
6828 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6829
6830 NewSel = InsertNewInstBefore(NewSel, SI);
6831 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006832 }
6833 }
6834 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006835
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006836 // See if we can fold the select into one of our operands.
6837 if (SI.getType()->isInteger()) {
6838 // See the comment above GetSelectFoldableOperands for a description of the
6839 // transformation we are doing here.
6840 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6841 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6842 !isa<Constant>(FalseVal))
6843 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6844 unsigned OpToFold = 0;
6845 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6846 OpToFold = 1;
6847 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6848 OpToFold = 2;
6849 }
6850
6851 if (OpToFold) {
6852 Constant *C = GetSelectFoldableConstant(TVI);
6853 std::string Name = TVI->getName(); TVI->setName("");
6854 Instruction *NewSel =
6855 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6856 Name);
6857 InsertNewInstBefore(NewSel, SI);
6858 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6859 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6860 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6861 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6862 else {
6863 assert(0 && "Unknown instruction!!");
6864 }
6865 }
6866 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006867
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006868 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6869 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6870 !isa<Constant>(TrueVal))
6871 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6872 unsigned OpToFold = 0;
6873 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6874 OpToFold = 1;
6875 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6876 OpToFold = 2;
6877 }
6878
6879 if (OpToFold) {
6880 Constant *C = GetSelectFoldableConstant(FVI);
6881 std::string Name = FVI->getName(); FVI->setName("");
6882 Instruction *NewSel =
6883 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6884 Name);
6885 InsertNewInstBefore(NewSel, SI);
6886 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6887 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6888 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6889 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6890 else {
6891 assert(0 && "Unknown instruction!!");
6892 }
6893 }
6894 }
6895 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006896
6897 if (BinaryOperator::isNot(CondVal)) {
6898 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6899 SI.setOperand(1, FalseVal);
6900 SI.setOperand(2, TrueVal);
6901 return &SI;
6902 }
6903
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006904 return 0;
6905}
6906
Chris Lattner82f2ef22006-03-06 20:18:44 +00006907/// GetKnownAlignment - If the specified pointer has an alignment that we can
6908/// determine, return it, otherwise return 0.
6909static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6910 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6911 unsigned Align = GV->getAlignment();
6912 if (Align == 0 && TD)
6913 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6914 return Align;
6915 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6916 unsigned Align = AI->getAlignment();
6917 if (Align == 0 && TD) {
6918 if (isa<AllocaInst>(AI))
6919 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6920 else if (isa<MallocInst>(AI)) {
6921 // Malloc returns maximally aligned memory.
6922 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6923 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6924 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6925 }
6926 }
6927 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006928 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006929 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006930 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006931 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006932 if (isa<PointerType>(CI->getOperand(0)->getType()))
6933 return GetKnownAlignment(CI->getOperand(0), TD);
6934 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006935 } else if (isa<GetElementPtrInst>(V) ||
6936 (isa<ConstantExpr>(V) &&
6937 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6938 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006939 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6940 if (BaseAlignment == 0) return 0;
6941
6942 // If all indexes are zero, it is just the alignment of the base pointer.
6943 bool AllZeroOperands = true;
6944 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6945 if (!isa<Constant>(GEPI->getOperand(i)) ||
6946 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6947 AllZeroOperands = false;
6948 break;
6949 }
6950 if (AllZeroOperands)
6951 return BaseAlignment;
6952
6953 // Otherwise, if the base alignment is >= the alignment we expect for the
6954 // base pointer type, then we know that the resultant pointer is aligned at
6955 // least as much as its type requires.
6956 if (!TD) return 0;
6957
6958 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6959 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006960 <= BaseAlignment) {
6961 const Type *GEPTy = GEPI->getType();
6962 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6963 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006964 return 0;
6965 }
6966 return 0;
6967}
6968
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006969
Chris Lattnerc66b2232006-01-13 20:11:04 +00006970/// visitCallInst - CallInst simplification. This mostly only handles folding
6971/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6972/// the heavy lifting.
6973///
Chris Lattner970c33a2003-06-19 17:00:31 +00006974Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006975 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6976 if (!II) return visitCallSite(&CI);
6977
Chris Lattner51ea1272004-02-28 05:22:00 +00006978 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6979 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006980 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006981 bool Changed = false;
6982
6983 // memmove/cpy/set of zero bytes is a noop.
6984 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6985 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6986
Chris Lattner00648e12004-10-12 04:52:52 +00006987 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006988 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006989 // Replace the instruction with just byte operations. We would
6990 // transform other cases to loads/stores, but we don't know if
6991 // alignment is sufficient.
6992 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006993 }
6994
Chris Lattner00648e12004-10-12 04:52:52 +00006995 // If we have a memmove and the source operation is a constant global,
6996 // then the source and dest pointers can't alias, so we can change this
6997 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006998 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006999 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7000 if (GVSrc->isConstant()) {
7001 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007002 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007003 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00007004 Type::UIntTy)
7005 Name = "llvm.memcpy.i32";
7006 else
7007 Name = "llvm.memcpy.i64";
7008 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007009 CI.getCalledFunction()->getFunctionType());
7010 CI.setOperand(0, MemCpy);
7011 Changed = true;
7012 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007013 }
Chris Lattner00648e12004-10-12 04:52:52 +00007014
Chris Lattner82f2ef22006-03-06 20:18:44 +00007015 // If we can determine a pointer alignment that is bigger than currently
7016 // set, update the alignment.
7017 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7018 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7019 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7020 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007021 if (MI->getAlignment()->getZExtValue() < Align) {
7022 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007023 Changed = true;
7024 }
7025 } else if (isa<MemSetInst>(MI)) {
7026 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007027 if (MI->getAlignment()->getZExtValue() < Alignment) {
7028 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007029 Changed = true;
7030 }
7031 }
7032
Chris Lattnerc66b2232006-01-13 20:11:04 +00007033 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007034 } else {
7035 switch (II->getIntrinsicID()) {
7036 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007037 case Intrinsic::ppc_altivec_lvx:
7038 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007039 case Intrinsic::x86_sse_loadu_ps:
7040 case Intrinsic::x86_sse2_loadu_pd:
7041 case Intrinsic::x86_sse2_loadu_dq:
7042 // Turn PPC lvx -> load if the pointer is known aligned.
7043 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007044 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007045 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007046 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007047 return new LoadInst(Ptr);
7048 }
7049 break;
7050 case Intrinsic::ppc_altivec_stvx:
7051 case Intrinsic::ppc_altivec_stvxl:
7052 // Turn stvx -> store if the pointer is known aligned.
7053 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007054 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007055 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7056 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007057 return new StoreInst(II->getOperand(1), Ptr);
7058 }
7059 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007060 case Intrinsic::x86_sse_storeu_ps:
7061 case Intrinsic::x86_sse2_storeu_pd:
7062 case Intrinsic::x86_sse2_storeu_dq:
7063 case Intrinsic::x86_sse2_storel_dq:
7064 // Turn X86 storeu -> store if the pointer is known aligned.
7065 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7066 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007067 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7068 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007069 return new StoreInst(II->getOperand(2), Ptr);
7070 }
7071 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007072
7073 case Intrinsic::x86_sse_cvttss2si: {
7074 // These intrinsics only demands the 0th element of its input vector. If
7075 // we can simplify the input based on that, do so now.
7076 uint64_t UndefElts;
7077 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7078 UndefElts)) {
7079 II->setOperand(1, V);
7080 return II;
7081 }
7082 break;
7083 }
7084
Chris Lattnere79d2492006-04-06 19:19:17 +00007085 case Intrinsic::ppc_altivec_vperm:
7086 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7087 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7088 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7089
7090 // Check that all of the elements are integer constants or undefs.
7091 bool AllEltsOk = true;
7092 for (unsigned i = 0; i != 16; ++i) {
7093 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7094 !isa<UndefValue>(Mask->getOperand(i))) {
7095 AllEltsOk = false;
7096 break;
7097 }
7098 }
7099
7100 if (AllEltsOk) {
7101 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007102 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7103 II->getOperand(1), Mask->getType(), CI);
7104 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7105 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007106 Value *Result = UndefValue::get(Op0->getType());
7107
7108 // Only extract each element once.
7109 Value *ExtractedElts[32];
7110 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7111
7112 for (unsigned i = 0; i != 16; ++i) {
7113 if (isa<UndefValue>(Mask->getOperand(i)))
7114 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007115 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007116 Idx &= 31; // Match the hardware behavior.
7117
7118 if (ExtractedElts[Idx] == 0) {
7119 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007120 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007121 InsertNewInstBefore(Elt, CI);
7122 ExtractedElts[Idx] = Elt;
7123 }
7124
7125 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007126 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007127 InsertNewInstBefore(cast<Instruction>(Result), CI);
7128 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007129 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007130 }
7131 }
7132 break;
7133
Chris Lattner503221f2006-01-13 21:28:09 +00007134 case Intrinsic::stackrestore: {
7135 // If the save is right next to the restore, remove the restore. This can
7136 // happen when variable allocas are DCE'd.
7137 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7138 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7139 BasicBlock::iterator BI = SS;
7140 if (&*++BI == II)
7141 return EraseInstFromFunction(CI);
7142 }
7143 }
7144
7145 // If the stack restore is in a return/unwind block and if there are no
7146 // allocas or calls between the restore and the return, nuke the restore.
7147 TerminatorInst *TI = II->getParent()->getTerminator();
7148 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7149 BasicBlock::iterator BI = II;
7150 bool CannotRemove = false;
7151 for (++BI; &*BI != TI; ++BI) {
7152 if (isa<AllocaInst>(BI) ||
7153 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7154 CannotRemove = true;
7155 break;
7156 }
7157 }
7158 if (!CannotRemove)
7159 return EraseInstFromFunction(CI);
7160 }
7161 break;
7162 }
7163 }
Chris Lattner00648e12004-10-12 04:52:52 +00007164 }
7165
Chris Lattnerc66b2232006-01-13 20:11:04 +00007166 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007167}
7168
7169// InvokeInst simplification
7170//
7171Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007172 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007173}
7174
Chris Lattneraec3d942003-10-07 22:32:43 +00007175// visitCallSite - Improvements for call and invoke instructions.
7176//
7177Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007178 bool Changed = false;
7179
7180 // If the callee is a constexpr cast of a function, attempt to move the cast
7181 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007182 if (transformConstExprCastCall(CS)) return 0;
7183
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007184 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007185
Chris Lattner61d9d812005-05-13 07:09:09 +00007186 if (Function *CalleeF = dyn_cast<Function>(Callee))
7187 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7188 Instruction *OldCall = CS.getInstruction();
7189 // If the call and callee calling conventions don't match, this call must
7190 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007191 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00007192 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7193 if (!OldCall->use_empty())
7194 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7195 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7196 return EraseInstFromFunction(*OldCall);
7197 return 0;
7198 }
7199
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007200 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7201 // This instruction is not reachable, just remove it. We insert a store to
7202 // undef so that we know that this code is not reachable, despite the fact
7203 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007204 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007205 UndefValue::get(PointerType::get(Type::BoolTy)),
7206 CS.getInstruction());
7207
7208 if (!CS.getInstruction()->use_empty())
7209 CS.getInstruction()->
7210 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7211
7212 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7213 // Don't break the CFG, insert a dummy cond branch.
7214 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00007215 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007216 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007217 return EraseInstFromFunction(*CS.getInstruction());
7218 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007219
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007220 const PointerType *PTy = cast<PointerType>(Callee->getType());
7221 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7222 if (FTy->isVarArg()) {
7223 // See if we can optimize any arguments passed through the varargs area of
7224 // the call.
7225 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7226 E = CS.arg_end(); I != E; ++I)
7227 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7228 // If this cast does not effect the value passed through the varargs
7229 // area, we can eliminate the use of the cast.
7230 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007231 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007232 *I = Op;
7233 Changed = true;
7234 }
7235 }
7236 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007237
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007238 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007239}
7240
Chris Lattner970c33a2003-06-19 17:00:31 +00007241// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7242// attempt to move the cast to the arguments of the call/invoke.
7243//
7244bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7245 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7246 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007247 if (CE->getOpcode() != Instruction::BitCast ||
7248 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007249 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007250 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007251 Instruction *Caller = CS.getInstruction();
7252
7253 // Okay, this is a cast from a function to a different type. Unless doing so
7254 // would cause a type conversion of one of our arguments, change this call to
7255 // be a direct call with arguments casted to the appropriate types.
7256 //
7257 const FunctionType *FT = Callee->getFunctionType();
7258 const Type *OldRetTy = Caller->getType();
7259
Chris Lattner1f7942f2004-01-14 06:06:08 +00007260 // Check to see if we are changing the return type...
7261 if (OldRetTy != FT->getReturnType()) {
7262 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007263 !Caller->use_empty() &&
7264 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00007265 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007266 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7267 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00007268 return false; // Cannot transform this return value...
7269
7270 // If the callsite is an invoke instruction, and the return value is used by
7271 // a PHI node in a successor, we cannot change the return type of the call
7272 // because there is no place to put the cast instruction (without breaking
7273 // the critical edge). Bail out in this case.
7274 if (!Caller->use_empty())
7275 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7276 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7277 UI != E; ++UI)
7278 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7279 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007280 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007281 return false;
7282 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007283
7284 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7285 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007286
Chris Lattner970c33a2003-06-19 17:00:31 +00007287 CallSite::arg_iterator AI = CS.arg_begin();
7288 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7289 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007290 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007291 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007292 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007293 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007294 (ParamTy->isIntegral() && ActTy->isIntegral() &&
7295 ParamTy->isSigned() == ActTy->isSigned() &&
7296 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7297 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007298 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007299 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007300 }
7301
7302 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7303 Callee->isExternal())
7304 return false; // Do not delete arguments unless we have a function body...
7305
7306 // Okay, we decided that this is a safe thing to do: go ahead and start
7307 // inserting cast instructions as necessary...
7308 std::vector<Value*> Args;
7309 Args.reserve(NumActualArgs);
7310
7311 AI = CS.arg_begin();
7312 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7313 const Type *ParamTy = FT->getParamType(i);
7314 if ((*AI)->getType() == ParamTy) {
7315 Args.push_back(*AI);
7316 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007317 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7318 (*AI)->getType()->isSigned(), ParamTy, ParamTy->isSigned());
7319 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007320 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007321 }
7322 }
7323
7324 // If the function takes more arguments than the call was taking, add them
7325 // now...
7326 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7327 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7328
7329 // If we are removing arguments to the function, emit an obnoxious warning...
7330 if (FT->getNumParams() < NumActualArgs)
7331 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007332 cerr << "WARNING: While resolving call to function '"
7333 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007334 } else {
7335 // Add all of the arguments in their promoted form to the arg list...
7336 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7337 const Type *PTy = getPromotedType((*AI)->getType());
7338 if (PTy != (*AI)->getType()) {
7339 // Must promote to pass through va_arg area!
Reid Spencer668d90f2006-12-18 08:47:13 +00007340 Instruction::CastOps opcode = CastInst::getCastOpcode(
7341 *AI, (*AI)->getType()->isSigned(), PTy, PTy->isSigned());
7342 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007343 InsertNewInstBefore(Cast, *Caller);
7344 Args.push_back(Cast);
7345 } else {
7346 Args.push_back(*AI);
7347 }
7348 }
7349 }
7350
7351 if (FT->getReturnType() == Type::VoidTy)
7352 Caller->setName(""); // Void type should not have a name...
7353
7354 Instruction *NC;
7355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007356 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007357 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007358 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007359 } else {
7360 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007361 if (cast<CallInst>(Caller)->isTailCall())
7362 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007363 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007364 }
7365
7366 // Insert a cast of the return type as necessary...
7367 Value *NV = NC;
7368 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7369 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007370 const Type *CallerTy = Caller->getType();
7371 Instruction::CastOps opcode = CastInst::getCastOpcode(
7372 NC, NC->getType()->isSigned(), CallerTy, CallerTy->isSigned());
7373 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007374
7375 // If this is an invoke instruction, we should insert it after the first
7376 // non-phi, instruction in the normal successor block.
7377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7378 BasicBlock::iterator I = II->getNormalDest()->begin();
7379 while (isa<PHINode>(I)) ++I;
7380 InsertNewInstBefore(NC, *I);
7381 } else {
7382 // Otherwise, it's a call, just insert cast right after the call instr
7383 InsertNewInstBefore(NC, *Caller);
7384 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007385 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007386 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007387 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007388 }
7389 }
7390
7391 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7392 Caller->replaceAllUsesWith(NV);
7393 Caller->getParent()->getInstList().erase(Caller);
7394 removeFromWorkList(Caller);
7395 return true;
7396}
7397
Chris Lattnercadac0c2006-11-01 04:51:18 +00007398/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7399/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7400/// and a single binop.
7401Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7402 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007403 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007404 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007405 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007406 Value *LHSVal = FirstInst->getOperand(0);
7407 Value *RHSVal = FirstInst->getOperand(1);
7408
7409 const Type *LHSType = LHSVal->getType();
7410 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007411
7412 // Scan to see if all operands are the same opcode, all have one use, and all
7413 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007414 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007415 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007416 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007417 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007418 // types or GEP's with different index types.
7419 I->getOperand(0)->getType() != LHSType ||
7420 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007421 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007422
7423 // If they are CmpInst instructions, check their predicates
7424 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7425 if (cast<CmpInst>(I)->getPredicate() !=
7426 cast<CmpInst>(FirstInst)->getPredicate())
7427 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007428
7429 // Keep track of which operand needs a phi node.
7430 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7431 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007432 }
7433
Chris Lattner4f218d52006-11-08 19:42:28 +00007434 // Otherwise, this is safe to transform, determine if it is profitable.
7435
7436 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7437 // Indexes are often folded into load/store instructions, so we don't want to
7438 // hide them behind a phi.
7439 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7440 return 0;
7441
Chris Lattnercadac0c2006-11-01 04:51:18 +00007442 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007443 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007444 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007445 if (LHSVal == 0) {
7446 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7447 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7448 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007449 InsertNewInstBefore(NewLHS, PN);
7450 LHSVal = NewLHS;
7451 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007452
7453 if (RHSVal == 0) {
7454 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7455 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7456 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007457 InsertNewInstBefore(NewRHS, PN);
7458 RHSVal = NewRHS;
7459 }
7460
Chris Lattnercd62f112006-11-08 19:29:23 +00007461 // Add all operands to the new PHIs.
7462 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7463 if (NewLHS) {
7464 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7465 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7466 }
7467 if (NewRHS) {
7468 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7469 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7470 }
7471 }
7472
Chris Lattnercadac0c2006-11-01 04:51:18 +00007473 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007474 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007475 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7476 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7477 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007478 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7479 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7480 else {
7481 assert(isa<GetElementPtrInst>(FirstInst));
7482 return new GetElementPtrInst(LHSVal, RHSVal);
7483 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007484}
7485
Chris Lattner14f82c72006-11-01 07:13:54 +00007486/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7487/// of the block that defines it. This means that it must be obvious the value
7488/// of the load is not changed from the point of the load to the end of the
7489/// block it is in.
7490static bool isSafeToSinkLoad(LoadInst *L) {
7491 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7492
7493 for (++BBI; BBI != E; ++BBI)
7494 if (BBI->mayWriteToMemory())
7495 return false;
7496 return true;
7497}
7498
Chris Lattner970c33a2003-06-19 17:00:31 +00007499
Chris Lattner7515cab2004-11-14 19:13:23 +00007500// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7501// operator and they all are only used by the PHI, PHI together their
7502// inputs, and do the operation once, to the result of the PHI.
7503Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7504 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7505
7506 // Scan the instruction, looking for input operations that can be folded away.
7507 // If all input operands to the phi are the same instruction (e.g. a cast from
7508 // the same type or "+42") we can pull the operation through the PHI, reducing
7509 // code size and simplifying code.
7510 Constant *ConstantOp = 0;
7511 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007512 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007513 if (isa<CastInst>(FirstInst)) {
7514 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007515 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7516 isa<CmpInst>(FirstInst)) {
7517 // Can fold binop, compare or shift here if the RHS is a constant,
7518 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007519 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007520 if (ConstantOp == 0)
7521 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007522 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7523 isVolatile = LI->isVolatile();
7524 // We can't sink the load if the loaded value could be modified between the
7525 // load and the PHI.
7526 if (LI->getParent() != PN.getIncomingBlock(0) ||
7527 !isSafeToSinkLoad(LI))
7528 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007529 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007530 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007531 return FoldPHIArgBinOpIntoPHI(PN);
7532 // Can't handle general GEPs yet.
7533 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007534 } else {
7535 return 0; // Cannot fold this operation.
7536 }
7537
7538 // Check to see if all arguments are the same operation.
7539 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7540 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7541 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007542 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007543 return 0;
7544 if (CastSrcTy) {
7545 if (I->getOperand(0)->getType() != CastSrcTy)
7546 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007547 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007548 // We can't sink the load if the loaded value could be modified between
7549 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007550 if (LI->isVolatile() != isVolatile ||
7551 LI->getParent() != PN.getIncomingBlock(i) ||
7552 !isSafeToSinkLoad(LI))
7553 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007554 } else if (I->getOperand(1) != ConstantOp) {
7555 return 0;
7556 }
7557 }
7558
7559 // Okay, they are all the same operation. Create a new PHI node of the
7560 // correct type, and PHI together all of the LHS's of the instructions.
7561 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7562 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007563 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007564
7565 Value *InVal = FirstInst->getOperand(0);
7566 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007567
7568 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007569 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7570 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7571 if (NewInVal != InVal)
7572 InVal = 0;
7573 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7574 }
7575
7576 Value *PhiVal;
7577 if (InVal) {
7578 // The new PHI unions all of the same values together. This is really
7579 // common, so we handle it intelligently here for compile-time speed.
7580 PhiVal = InVal;
7581 delete NewPN;
7582 } else {
7583 InsertNewInstBefore(NewPN, PN);
7584 PhiVal = NewPN;
7585 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007586
Chris Lattner7515cab2004-11-14 19:13:23 +00007587 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007588 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7589 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007590 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007591 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007592 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007593 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007594 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7595 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7596 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007597 else
7598 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007599 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007600}
Chris Lattner48a44f72002-05-02 17:06:02 +00007601
Chris Lattner71536432005-01-17 05:10:15 +00007602/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7603/// that is dead.
7604static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7605 if (PN->use_empty()) return true;
7606 if (!PN->hasOneUse()) return false;
7607
7608 // Remember this node, and if we find the cycle, return.
7609 if (!PotentiallyDeadPHIs.insert(PN).second)
7610 return true;
7611
7612 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7613 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007614
Chris Lattner71536432005-01-17 05:10:15 +00007615 return false;
7616}
7617
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007618// PHINode simplification
7619//
Chris Lattner113f4f42002-06-25 16:13:24 +00007620Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007621 // If LCSSA is around, don't mess with Phi nodes
7622 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007623
Owen Andersonae8aa642006-07-10 22:03:18 +00007624 if (Value *V = PN.hasConstantValue())
7625 return ReplaceInstUsesWith(PN, V);
7626
Owen Andersonae8aa642006-07-10 22:03:18 +00007627 // If all PHI operands are the same operation, pull them through the PHI,
7628 // reducing code size.
7629 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7630 PN.getIncomingValue(0)->hasOneUse())
7631 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7632 return Result;
7633
7634 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7635 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7636 // PHI)... break the cycle.
7637 if (PN.hasOneUse())
7638 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7639 std::set<PHINode*> PotentiallyDeadPHIs;
7640 PotentiallyDeadPHIs.insert(&PN);
7641 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7642 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7643 }
7644
Chris Lattner91daeb52003-12-19 05:58:40 +00007645 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007646}
7647
Reid Spencer13bc5d72006-12-12 09:18:51 +00007648static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7649 Instruction *InsertPoint,
7650 InstCombiner *IC) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007651 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007652 unsigned VTySize = V->getType()->getPrimitiveSize();
7653 // We must cast correctly to the pointer type. Ensure that we
7654 // sign extend the integer value if it is smaller as this is
7655 // used for address computation.
7656 Instruction::CastOps opcode =
7657 (VTySize < PtrSize ? Instruction::SExt :
7658 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7659 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007660}
7661
Chris Lattner48a44f72002-05-02 17:06:02 +00007662
Chris Lattner113f4f42002-06-25 16:13:24 +00007663Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007664 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007665 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007666 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007667 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007668 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007669
Chris Lattner81a7a232004-10-16 18:11:37 +00007670 if (isa<UndefValue>(GEP.getOperand(0)))
7671 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7672
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007673 bool HasZeroPointerIndex = false;
7674 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7675 HasZeroPointerIndex = C->isNullValue();
7676
7677 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007678 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007679
Chris Lattner69193f92004-04-05 01:30:19 +00007680 // Eliminate unneeded casts for indices.
7681 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007682 gep_type_iterator GTI = gep_type_begin(GEP);
7683 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7684 if (isa<SequentialType>(*GTI)) {
7685 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7686 Value *Src = CI->getOperand(0);
7687 const Type *SrcTy = Src->getType();
7688 const Type *DestTy = CI->getType();
7689 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007690 if (SrcTy->getPrimitiveSizeInBits() ==
7691 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007692 // We can always eliminate a cast from ulong or long to the other.
7693 // We can always eliminate a cast from uint to int or the other on
7694 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007695 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007696 MadeChange = true;
7697 GEP.setOperand(i, Src);
7698 }
7699 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7700 SrcTy->getPrimitiveSize() == 4) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007701 // We can eliminate a cast from [u]int to [u]long iff the target
7702 // is a 32-bit pointer target.
7703 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007704 MadeChange = true;
7705 GEP.setOperand(i, Src);
7706 }
Chris Lattner69193f92004-04-05 01:30:19 +00007707 }
7708 }
7709 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007710 // If we are using a wider index than needed for this platform, shrink it
7711 // to what we need. If the incoming value needs a cast instruction,
7712 // insert it. This explicit cast can make subsequent optimizations more
7713 // obvious.
7714 Value *Op = GEP.getOperand(i);
7715 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007716 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007717 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007718 MadeChange = true;
7719 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007720 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7721 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007722 GEP.setOperand(i, Op);
7723 MadeChange = true;
7724 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007725 // If this is a constant idx, make sure to canonicalize it to be a signed
7726 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007727 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7728 if (CUI->getType()->isUnsigned()) {
7729 GEP.setOperand(i,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007730 ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007731 MadeChange = true;
7732 }
Chris Lattner69193f92004-04-05 01:30:19 +00007733 }
7734 if (MadeChange) return &GEP;
7735
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007736 // Combine Indices - If the source pointer to this getelementptr instruction
7737 // is a getelementptr instruction, combine the indices of the two
7738 // getelementptr instructions into a single instruction.
7739 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007740 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007741 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007742 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007743
7744 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007745 // Note that if our source is a gep chain itself that we wait for that
7746 // chain to be resolved before we perform this transformation. This
7747 // avoids us creating a TON of code in some cases.
7748 //
7749 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7750 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7751 return 0; // Wait until our source is folded to completion.
7752
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007753 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007754
7755 // Find out whether the last index in the source GEP is a sequential idx.
7756 bool EndsWithSequential = false;
7757 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7758 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007759 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007760
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007761 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007762 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007763 // Replace: gep (gep %P, long B), long A, ...
7764 // With: T = long A+B; gep %P, T, ...
7765 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007766 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007767 if (SO1 == Constant::getNullValue(SO1->getType())) {
7768 Sum = GO1;
7769 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7770 Sum = SO1;
7771 } else {
7772 // If they aren't the same type, convert both to an integer of the
7773 // target's pointer size.
7774 if (SO1->getType() != GO1->getType()) {
7775 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007776 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007777 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007778 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007779 } else {
7780 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007781 if (SO1->getType()->getPrimitiveSize() == PS) {
7782 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007783 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007784
7785 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7786 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007787 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007788 } else {
7789 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007790 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7791 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007792 }
7793 }
7794 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007795 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7796 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7797 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007798 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7799 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007800 }
Chris Lattner69193f92004-04-05 01:30:19 +00007801 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007802
7803 // Recycle the GEP we already have if possible.
7804 if (SrcGEPOperands.size() == 2) {
7805 GEP.setOperand(0, SrcGEPOperands[0]);
7806 GEP.setOperand(1, Sum);
7807 return &GEP;
7808 } else {
7809 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7810 SrcGEPOperands.end()-1);
7811 Indices.push_back(Sum);
7812 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7813 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007814 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007815 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007816 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007817 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007818 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7819 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007820 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7821 }
7822
7823 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007824 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007825
Chris Lattner5f667a62004-05-07 22:09:22 +00007826 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007827 // GEP of global variable. If all of the indices for this GEP are
7828 // constants, we can promote this to a constexpr instead of an instruction.
7829
7830 // Scan for nonconstants...
7831 std::vector<Constant*> Indices;
7832 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7833 for (; I != E && isa<Constant>(*I); ++I)
7834 Indices.push_back(cast<Constant>(*I));
7835
7836 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007837 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007838
7839 // Replace all uses of the GEP with the new constexpr...
7840 return ReplaceInstUsesWith(GEP, CE);
7841 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007842 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007843 if (!isa<PointerType>(X->getType())) {
7844 // Not interesting. Source pointer must be a cast from pointer.
7845 } else if (HasZeroPointerIndex) {
7846 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7847 // into : GEP [10 x ubyte]* X, long 0, ...
7848 //
7849 // This occurs when the program declares an array extern like "int X[];"
7850 //
7851 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7852 const PointerType *XTy = cast<PointerType>(X->getType());
7853 if (const ArrayType *XATy =
7854 dyn_cast<ArrayType>(XTy->getElementType()))
7855 if (const ArrayType *CATy =
7856 dyn_cast<ArrayType>(CPTy->getElementType()))
7857 if (CATy->getElementType() == XATy->getElementType()) {
7858 // At this point, we know that the cast source type is a pointer
7859 // to an array of the same type as the destination pointer
7860 // array. Because the array type is never stepped over (there
7861 // is a leading zero) we can fold the cast into this GEP.
7862 GEP.setOperand(0, X);
7863 return &GEP;
7864 }
7865 } else if (GEP.getNumOperands() == 2) {
7866 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007867 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7868 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007869 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7870 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7871 if (isa<ArrayType>(SrcElTy) &&
7872 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7873 TD->getTypeSize(ResElTy)) {
7874 Value *V = InsertNewInstBefore(
7875 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7876 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007877 // V and GEP are both pointer types --> BitCast
7878 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007879 }
Chris Lattner2a893292005-09-13 18:36:04 +00007880
7881 // Transform things like:
7882 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7883 // (where tmp = 8*tmp2) into:
7884 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7885
7886 if (isa<ArrayType>(SrcElTy) &&
7887 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7888 uint64_t ArrayEltSize =
7889 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7890
7891 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7892 // allow either a mul, shift, or constant here.
7893 Value *NewIdx = 0;
7894 ConstantInt *Scale = 0;
7895 if (ArrayEltSize == 1) {
7896 NewIdx = GEP.getOperand(1);
7897 Scale = ConstantInt::get(NewIdx->getType(), 1);
7898 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007899 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007900 Scale = CI;
7901 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7902 if (Inst->getOpcode() == Instruction::Shl &&
7903 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007904 unsigned ShAmt =
7905 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007906 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007907 NewIdx = Inst->getOperand(0);
7908 } else if (Inst->getOpcode() == Instruction::Mul &&
7909 isa<ConstantInt>(Inst->getOperand(1))) {
7910 Scale = cast<ConstantInt>(Inst->getOperand(1));
7911 NewIdx = Inst->getOperand(0);
7912 }
7913 }
7914
7915 // If the index will be to exactly the right offset with the scale taken
7916 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007917 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007918 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007919 Scale = ConstantInt::get(Scale->getType(),
7920 Scale->getZExtValue() / ArrayEltSize);
7921 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007922 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7923 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007924 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7925 NewIdx = InsertNewInstBefore(Sc, GEP);
7926 }
7927
7928 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007929 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007930 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7931 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007932 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7933 // The NewGEP must be pointer typed, so must the old one -> BitCast
7934 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007935 }
7936 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007937 }
Chris Lattnerca081252001-12-14 16:52:21 +00007938 }
7939
Chris Lattnerca081252001-12-14 16:52:21 +00007940 return 0;
7941}
7942
Chris Lattner1085bdf2002-11-04 16:18:53 +00007943Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7944 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7945 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007946 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7947 const Type *NewTy =
7948 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007949 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007950
7951 // Create and insert the replacement instruction...
7952 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007953 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007954 else {
7955 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007956 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007957 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007958
7959 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007960
Chris Lattner1085bdf2002-11-04 16:18:53 +00007961 // Scan to the end of the allocation instructions, to skip over a block of
7962 // allocas if possible...
7963 //
7964 BasicBlock::iterator It = New;
7965 while (isa<AllocationInst>(*It)) ++It;
7966
7967 // Now that I is pointing to the first non-allocation-inst in the block,
7968 // insert our getelementptr instruction...
7969 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007970 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7971 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7972 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007973
7974 // Now make everything use the getelementptr instead of the original
7975 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007976 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007977 } else if (isa<UndefValue>(AI.getArraySize())) {
7978 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007979 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007980
7981 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7982 // Note that we only do this for alloca's, because malloc should allocate and
7983 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007984 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007985 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007986 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7987
Chris Lattner1085bdf2002-11-04 16:18:53 +00007988 return 0;
7989}
7990
Chris Lattner8427bff2003-12-07 01:24:23 +00007991Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7992 Value *Op = FI.getOperand(0);
7993
7994 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7995 if (CastInst *CI = dyn_cast<CastInst>(Op))
7996 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7997 FI.setOperand(0, CI->getOperand(0));
7998 return &FI;
7999 }
8000
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008001 // free undef -> unreachable.
8002 if (isa<UndefValue>(Op)) {
8003 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00008004 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008005 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
8006 return EraseInstFromFunction(FI);
8007 }
8008
Chris Lattnerf3a36602004-02-28 04:57:37 +00008009 // If we have 'free null' delete the instruction. This can happen in stl code
8010 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008011 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008012 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008013
Chris Lattner8427bff2003-12-07 01:24:23 +00008014 return 0;
8015}
8016
8017
Chris Lattner72684fe2005-01-31 05:51:45 +00008018/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008019static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8020 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008021 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008022
8023 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008024 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008025 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008026
Chris Lattnerebca4762006-04-02 05:37:12 +00008027 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8028 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008029 // If the source is an array, the code below will not succeed. Check to
8030 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8031 // constants.
8032 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8033 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8034 if (ASrcTy->getNumElements() != 0) {
8035 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
8036 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8037 SrcTy = cast<PointerType>(CastOp->getType());
8038 SrcPTy = SrcTy->getElementType();
8039 }
8040
Chris Lattnerebca4762006-04-02 05:37:12 +00008041 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8042 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008043 // Do not allow turning this into a load of an integer, which is then
8044 // casted to a pointer, this pessimizes pointer analysis a lot.
8045 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008046 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008047 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008048
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008049 // Okay, we are casting from one integer or pointer type to another of
8050 // the same size. Instead of casting the pointer before the load, cast
8051 // the result of the loaded value.
8052 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8053 CI->getName(),
8054 LI.isVolatile()),LI);
8055 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008056 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008057 }
Chris Lattner35e24772004-07-13 01:49:43 +00008058 }
8059 }
8060 return 0;
8061}
8062
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008063/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008064/// from this value cannot trap. If it is not obviously safe to load from the
8065/// specified pointer, we do a quick local scan of the basic block containing
8066/// ScanFrom, to determine if the address is already accessed.
8067static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8068 // If it is an alloca or global variable, it is always safe to load from.
8069 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8070
8071 // Otherwise, be a little bit agressive by scanning the local block where we
8072 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008073 // from/to. If so, the previous load or store would have already trapped,
8074 // so there is no harm doing an extra load (also, CSE will later eliminate
8075 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008076 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8077
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008078 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008079 --BBI;
8080
8081 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8082 if (LI->getOperand(0) == V) return true;
8083 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8084 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008085
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008086 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008087 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008088}
8089
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008090Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8091 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008092
Chris Lattnera9d84e32005-05-01 04:24:53 +00008093 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008094 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008095 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8096 return Res;
8097
8098 // None of the following transforms are legal for volatile loads.
8099 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008100
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008101 if (&LI.getParent()->front() != &LI) {
8102 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008103 // If the instruction immediately before this is a store to the same
8104 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008105 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8106 if (SI->getOperand(1) == LI.getOperand(0))
8107 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008108 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8109 if (LIB->getOperand(0) == LI.getOperand(0))
8110 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008111 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008112
8113 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8114 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8115 isa<UndefValue>(GEPI->getOperand(0))) {
8116 // Insert a new store to null instruction before the load to indicate
8117 // that this code is not reachable. We do this instead of inserting
8118 // an unreachable instruction directly because we cannot modify the
8119 // CFG.
8120 new StoreInst(UndefValue::get(LI.getType()),
8121 Constant::getNullValue(Op->getType()), &LI);
8122 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8123 }
8124
Chris Lattner81a7a232004-10-16 18:11:37 +00008125 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008126 // load null/undef -> undef
8127 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008128 // Insert a new store to null instruction before the load to indicate that
8129 // this code is not reachable. We do this instead of inserting an
8130 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008131 new StoreInst(UndefValue::get(LI.getType()),
8132 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008133 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008134 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008135
Chris Lattner81a7a232004-10-16 18:11:37 +00008136 // Instcombine load (constant global) into the value loaded.
8137 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8138 if (GV->isConstant() && !GV->isExternal())
8139 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008140
Chris Lattner81a7a232004-10-16 18:11:37 +00008141 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8142 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8143 if (CE->getOpcode() == Instruction::GetElementPtr) {
8144 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8145 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008146 if (Constant *V =
8147 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008148 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008149 if (CE->getOperand(0)->isNullValue()) {
8150 // Insert a new store to null instruction before the load to indicate
8151 // that this code is not reachable. We do this instead of inserting
8152 // an unreachable instruction directly because we cannot modify the
8153 // CFG.
8154 new StoreInst(UndefValue::get(LI.getType()),
8155 Constant::getNullValue(Op->getType()), &LI);
8156 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8157 }
8158
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008159 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008160 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8161 return Res;
8162 }
8163 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008164
Chris Lattnera9d84e32005-05-01 04:24:53 +00008165 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008166 // Change select and PHI nodes to select values instead of addresses: this
8167 // helps alias analysis out a lot, allows many others simplifications, and
8168 // exposes redundancy in the code.
8169 //
8170 // Note that we cannot do the transformation unless we know that the
8171 // introduced loads cannot trap! Something like this is valid as long as
8172 // the condition is always false: load (select bool %C, int* null, int* %G),
8173 // but it would not be valid if we transformed it to load from null
8174 // unconditionally.
8175 //
8176 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8177 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008178 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8179 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008180 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008181 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008182 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008183 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008184 return new SelectInst(SI->getCondition(), V1, V2);
8185 }
8186
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008187 // load (select (cond, null, P)) -> load P
8188 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8189 if (C->isNullValue()) {
8190 LI.setOperand(0, SI->getOperand(2));
8191 return &LI;
8192 }
8193
8194 // load (select (cond, P, null)) -> load P
8195 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8196 if (C->isNullValue()) {
8197 LI.setOperand(0, SI->getOperand(1));
8198 return &LI;
8199 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008200 }
8201 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008202 return 0;
8203}
8204
Chris Lattner72684fe2005-01-31 05:51:45 +00008205/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8206/// when possible.
8207static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8208 User *CI = cast<User>(SI.getOperand(1));
8209 Value *CastOp = CI->getOperand(0);
8210
8211 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8212 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8213 const Type *SrcPTy = SrcTy->getElementType();
8214
8215 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8216 // If the source is an array, the code below will not succeed. Check to
8217 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8218 // constants.
8219 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8220 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8221 if (ASrcTy->getNumElements() != 0) {
8222 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
8223 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8224 SrcTy = cast<PointerType>(CastOp->getType());
8225 SrcPTy = SrcTy->getElementType();
8226 }
8227
8228 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008229 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008230 IC.getTargetData().getTypeSize(DestPTy)) {
8231
8232 // Okay, we are casting from one integer or pointer type to another of
8233 // the same size. Instead of casting the pointer before the store, cast
8234 // the value to be stored.
8235 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008236 Instruction::CastOps opcode = Instruction::BitCast;
8237 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008238 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008239 if (SIOp0->getType()->isIntegral())
8240 opcode = Instruction::IntToPtr;
8241 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008242 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008243 opcode = Instruction::PtrToInt;
8244 }
8245 if (Constant *C = dyn_cast<Constant>(SIOp0))
8246 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008247 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008248 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008249 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008250 return new StoreInst(NewCast, CastOp);
8251 }
8252 }
8253 }
8254 return 0;
8255}
8256
Chris Lattner31f486c2005-01-31 05:36:43 +00008257Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8258 Value *Val = SI.getOperand(0);
8259 Value *Ptr = SI.getOperand(1);
8260
8261 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008262 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008263 ++NumCombined;
8264 return 0;
8265 }
8266
Chris Lattner5997cf92006-02-08 03:25:32 +00008267 // Do really simple DSE, to catch cases where there are several consequtive
8268 // stores to the same location, separated by a few arithmetic operations. This
8269 // situation often occurs with bitfield accesses.
8270 BasicBlock::iterator BBI = &SI;
8271 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8272 --ScanInsts) {
8273 --BBI;
8274
8275 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8276 // Prev store isn't volatile, and stores to the same location?
8277 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8278 ++NumDeadStore;
8279 ++BBI;
8280 EraseInstFromFunction(*PrevSI);
8281 continue;
8282 }
8283 break;
8284 }
8285
Chris Lattnerdab43b22006-05-26 19:19:20 +00008286 // If this is a load, we have to stop. However, if the loaded value is from
8287 // the pointer we're loading and is producing the pointer we're storing,
8288 // then *this* store is dead (X = load P; store X -> P).
8289 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8290 if (LI == Val && LI->getOperand(0) == Ptr) {
8291 EraseInstFromFunction(SI);
8292 ++NumCombined;
8293 return 0;
8294 }
8295 // Otherwise, this is a load from some other location. Stores before it
8296 // may not be dead.
8297 break;
8298 }
8299
Chris Lattner5997cf92006-02-08 03:25:32 +00008300 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008301 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008302 break;
8303 }
8304
8305
8306 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008307
8308 // store X, null -> turns into 'unreachable' in SimplifyCFG
8309 if (isa<ConstantPointerNull>(Ptr)) {
8310 if (!isa<UndefValue>(Val)) {
8311 SI.setOperand(0, UndefValue::get(Val->getType()));
8312 if (Instruction *U = dyn_cast<Instruction>(Val))
8313 WorkList.push_back(U); // Dropped a use.
8314 ++NumCombined;
8315 }
8316 return 0; // Do not modify these!
8317 }
8318
8319 // store undef, Ptr -> noop
8320 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008321 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008322 ++NumCombined;
8323 return 0;
8324 }
8325
Chris Lattner72684fe2005-01-31 05:51:45 +00008326 // If the pointer destination is a cast, see if we can fold the cast into the
8327 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008328 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008329 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8330 return Res;
8331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008332 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008333 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8334 return Res;
8335
Chris Lattner219175c2005-09-12 23:23:25 +00008336
8337 // If this store is the last instruction in the basic block, and if the block
8338 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008339 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008340 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8341 if (BI->isUnconditional()) {
8342 // Check to see if the successor block has exactly two incoming edges. If
8343 // so, see if the other predecessor contains a store to the same location.
8344 // if so, insert a PHI node (if needed) and move the stores down.
8345 BasicBlock *Dest = BI->getSuccessor(0);
8346
8347 pred_iterator PI = pred_begin(Dest);
8348 BasicBlock *Other = 0;
8349 if (*PI != BI->getParent())
8350 Other = *PI;
8351 ++PI;
8352 if (PI != pred_end(Dest)) {
8353 if (*PI != BI->getParent())
8354 if (Other)
8355 Other = 0;
8356 else
8357 Other = *PI;
8358 if (++PI != pred_end(Dest))
8359 Other = 0;
8360 }
8361 if (Other) { // If only one other pred...
8362 BBI = Other->getTerminator();
8363 // Make sure this other block ends in an unconditional branch and that
8364 // there is an instruction before the branch.
8365 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8366 BBI != Other->begin()) {
8367 --BBI;
8368 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8369
8370 // If this instruction is a store to the same location.
8371 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8372 // Okay, we know we can perform this transformation. Insert a PHI
8373 // node now if we need it.
8374 Value *MergedVal = OtherStore->getOperand(0);
8375 if (MergedVal != SI.getOperand(0)) {
8376 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8377 PN->reserveOperandSpace(2);
8378 PN->addIncoming(SI.getOperand(0), SI.getParent());
8379 PN->addIncoming(OtherStore->getOperand(0), Other);
8380 MergedVal = InsertNewInstBefore(PN, Dest->front());
8381 }
8382
8383 // Advance to a place where it is safe to insert the new store and
8384 // insert it.
8385 BBI = Dest->begin();
8386 while (isa<PHINode>(BBI)) ++BBI;
8387 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8388 OtherStore->isVolatile()), *BBI);
8389
8390 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008391 EraseInstFromFunction(SI);
8392 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008393 ++NumCombined;
8394 return 0;
8395 }
8396 }
8397 }
8398 }
8399
Chris Lattner31f486c2005-01-31 05:36:43 +00008400 return 0;
8401}
8402
8403
Chris Lattner9eef8a72003-06-04 04:46:00 +00008404Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8405 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008406 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008407 BasicBlock *TrueDest;
8408 BasicBlock *FalseDest;
8409 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8410 !isa<Constant>(X)) {
8411 // Swap Destinations and condition...
8412 BI.setCondition(X);
8413 BI.setSuccessor(0, FalseDest);
8414 BI.setSuccessor(1, TrueDest);
8415 return &BI;
8416 }
8417
Reid Spencer266e42b2006-12-23 06:05:41 +00008418 // Cannonicalize fcmp_one -> fcmp_oeq
8419 FCmpInst::Predicate FPred; Value *Y;
8420 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8421 TrueDest, FalseDest)))
8422 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8423 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8424 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008425 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008426 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8427 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8428 // Swap Destinations and condition...
8429 BI.setCondition(NewSCC);
8430 BI.setSuccessor(0, FalseDest);
8431 BI.setSuccessor(1, TrueDest);
8432 removeFromWorkList(I);
8433 I->getParent()->getInstList().erase(I);
8434 WorkList.push_back(cast<Instruction>(NewSCC));
8435 return &BI;
8436 }
8437
8438 // Cannonicalize icmp_ne -> icmp_eq
8439 ICmpInst::Predicate IPred;
8440 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8441 TrueDest, FalseDest)))
8442 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8443 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8444 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8445 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8446 std::string Name = I->getName(); I->setName("");
8447 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8448 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008449 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008450 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008451 BI.setSuccessor(0, FalseDest);
8452 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008453 removeFromWorkList(I);
8454 I->getParent()->getInstList().erase(I);
8455 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008456 return &BI;
8457 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008458
Chris Lattner9eef8a72003-06-04 04:46:00 +00008459 return 0;
8460}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008461
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008462Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8463 Value *Cond = SI.getCondition();
8464 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8465 if (I->getOpcode() == Instruction::Add)
8466 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8467 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8468 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008469 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008470 AddRHS));
8471 SI.setOperand(0, I->getOperand(0));
8472 WorkList.push_back(I);
8473 return &SI;
8474 }
8475 }
8476 return 0;
8477}
8478
Chris Lattner6bc98652006-03-05 00:22:33 +00008479/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8480/// is to leave as a vector operation.
8481static bool CheapToScalarize(Value *V, bool isConstant) {
8482 if (isa<ConstantAggregateZero>(V))
8483 return true;
8484 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8485 if (isConstant) return true;
8486 // If all elts are the same, we can extract.
8487 Constant *Op0 = C->getOperand(0);
8488 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8489 if (C->getOperand(i) != Op0)
8490 return false;
8491 return true;
8492 }
8493 Instruction *I = dyn_cast<Instruction>(V);
8494 if (!I) return false;
8495
8496 // Insert element gets simplified to the inserted element or is deleted if
8497 // this is constant idx extract element and its a constant idx insertelt.
8498 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8499 isa<ConstantInt>(I->getOperand(2)))
8500 return true;
8501 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8502 return true;
8503 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8504 if (BO->hasOneUse() &&
8505 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8506 CheapToScalarize(BO->getOperand(1), isConstant)))
8507 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008508 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8509 if (CI->hasOneUse() &&
8510 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8511 CheapToScalarize(CI->getOperand(1), isConstant)))
8512 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008513
8514 return false;
8515}
8516
Chris Lattner12249be2006-05-25 23:48:38 +00008517/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8518/// elements into values that are larger than the #elts in the input.
8519static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8520 unsigned NElts = SVI->getType()->getNumElements();
8521 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8522 return std::vector<unsigned>(NElts, 0);
8523 if (isa<UndefValue>(SVI->getOperand(2)))
8524 return std::vector<unsigned>(NElts, 2*NElts);
8525
8526 std::vector<unsigned> Result;
8527 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8528 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8529 if (isa<UndefValue>(CP->getOperand(i)))
8530 Result.push_back(NElts*2); // undef -> 8
8531 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008532 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008533 return Result;
8534}
8535
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008536/// FindScalarElement - Given a vector and an element number, see if the scalar
8537/// value is already around as a register, for example if it were inserted then
8538/// extracted from the vector.
8539static Value *FindScalarElement(Value *V, unsigned EltNo) {
8540 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8541 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008542 unsigned Width = PTy->getNumElements();
8543 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008544 return UndefValue::get(PTy->getElementType());
8545
8546 if (isa<UndefValue>(V))
8547 return UndefValue::get(PTy->getElementType());
8548 else if (isa<ConstantAggregateZero>(V))
8549 return Constant::getNullValue(PTy->getElementType());
8550 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8551 return CP->getOperand(EltNo);
8552 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8553 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008554 if (!isa<ConstantInt>(III->getOperand(2)))
8555 return 0;
8556 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008557
8558 // If this is an insert to the element we are looking for, return the
8559 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008560 if (EltNo == IIElt)
8561 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008562
8563 // Otherwise, the insertelement doesn't modify the value, recurse on its
8564 // vector input.
8565 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008566 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008567 unsigned InEl = getShuffleMask(SVI)[EltNo];
8568 if (InEl < Width)
8569 return FindScalarElement(SVI->getOperand(0), InEl);
8570 else if (InEl < Width*2)
8571 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8572 else
8573 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008574 }
8575
8576 // Otherwise, we don't know.
8577 return 0;
8578}
8579
Robert Bocchinoa8352962006-01-13 22:48:06 +00008580Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008581
Chris Lattner92346c32006-03-31 18:25:14 +00008582 // If packed val is undef, replace extract with scalar undef.
8583 if (isa<UndefValue>(EI.getOperand(0)))
8584 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8585
8586 // If packed val is constant 0, replace extract with scalar 0.
8587 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8588 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8589
Robert Bocchinoa8352962006-01-13 22:48:06 +00008590 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8591 // If packed val is constant with uniform operands, replace EI
8592 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008593 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008594 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008595 if (C->getOperand(i) != op0) {
8596 op0 = 0;
8597 break;
8598 }
8599 if (op0)
8600 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008601 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008602
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008603 // If extracting a specified index from the vector, see if we can recursively
8604 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008605 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008606 // This instruction only demands the single element from the input vector.
8607 // If the input vector has a single use, simplify it based on this use
8608 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008609 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008610 if (EI.getOperand(0)->hasOneUse()) {
8611 uint64_t UndefElts;
8612 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008613 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008614 UndefElts)) {
8615 EI.setOperand(0, V);
8616 return &EI;
8617 }
8618 }
8619
Reid Spencere0fc4df2006-10-20 07:07:24 +00008620 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008621 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008622 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008623
Chris Lattner83f65782006-05-25 22:53:38 +00008624 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008625 if (I->hasOneUse()) {
8626 // Push extractelement into predecessor operation if legal and
8627 // profitable to do so
8628 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008629 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8630 if (CheapToScalarize(BO, isConstantElt)) {
8631 ExtractElementInst *newEI0 =
8632 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8633 EI.getName()+".lhs");
8634 ExtractElementInst *newEI1 =
8635 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8636 EI.getName()+".rhs");
8637 InsertNewInstBefore(newEI0, EI);
8638 InsertNewInstBefore(newEI1, EI);
8639 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8640 }
Reid Spencerde46e482006-11-02 20:25:50 +00008641 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008642 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008643 PointerType::get(EI.getType()), EI);
8644 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008645 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008646 InsertNewInstBefore(GEP, EI);
8647 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008648 }
8649 }
8650 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8651 // Extracting the inserted element?
8652 if (IE->getOperand(2) == EI.getOperand(1))
8653 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8654 // If the inserted and extracted elements are constants, they must not
8655 // be the same value, extract from the pre-inserted value instead.
8656 if (isa<Constant>(IE->getOperand(2)) &&
8657 isa<Constant>(EI.getOperand(1))) {
8658 AddUsesToWorkList(EI);
8659 EI.setOperand(0, IE->getOperand(0));
8660 return &EI;
8661 }
8662 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8663 // If this is extracting an element from a shufflevector, figure out where
8664 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008665 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8666 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008667 Value *Src;
8668 if (SrcIdx < SVI->getType()->getNumElements())
8669 Src = SVI->getOperand(0);
8670 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8671 SrcIdx -= SVI->getType()->getNumElements();
8672 Src = SVI->getOperand(1);
8673 } else {
8674 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008675 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008676 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008677 }
8678 }
Chris Lattner83f65782006-05-25 22:53:38 +00008679 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008680 return 0;
8681}
8682
Chris Lattner90951862006-04-16 00:51:47 +00008683/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8684/// elements from either LHS or RHS, return the shuffle mask and true.
8685/// Otherwise, return false.
8686static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8687 std::vector<Constant*> &Mask) {
8688 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8689 "Invalid CollectSingleShuffleElements");
8690 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8691
8692 if (isa<UndefValue>(V)) {
8693 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8694 return true;
8695 } else if (V == LHS) {
8696 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008697 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008698 return true;
8699 } else if (V == RHS) {
8700 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008701 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008702 return true;
8703 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8704 // If this is an insert of an extract from some other vector, include it.
8705 Value *VecOp = IEI->getOperand(0);
8706 Value *ScalarOp = IEI->getOperand(1);
8707 Value *IdxOp = IEI->getOperand(2);
8708
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008709 if (!isa<ConstantInt>(IdxOp))
8710 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008711 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008712
8713 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8714 // Okay, we can handle this if the vector we are insertinting into is
8715 // transitively ok.
8716 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8717 // If so, update the mask to reflect the inserted undef.
8718 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8719 return true;
8720 }
8721 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8722 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008723 EI->getOperand(0)->getType() == V->getType()) {
8724 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008725 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008726
8727 // This must be extracting from either LHS or RHS.
8728 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8729 // Okay, we can handle this if the vector we are insertinting into is
8730 // transitively ok.
8731 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8732 // If so, update the mask to reflect the inserted value.
8733 if (EI->getOperand(0) == LHS) {
8734 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008735 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008736 } else {
8737 assert(EI->getOperand(0) == RHS);
8738 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008739 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008740
8741 }
8742 return true;
8743 }
8744 }
8745 }
8746 }
8747 }
8748 // TODO: Handle shufflevector here!
8749
8750 return false;
8751}
8752
8753/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8754/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8755/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008756static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008757 Value *&RHS) {
8758 assert(isa<PackedType>(V->getType()) &&
8759 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008760 "Invalid shuffle!");
8761 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8762
8763 if (isa<UndefValue>(V)) {
8764 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8765 return V;
8766 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008767 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008768 return V;
8769 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8770 // If this is an insert of an extract from some other vector, include it.
8771 Value *VecOp = IEI->getOperand(0);
8772 Value *ScalarOp = IEI->getOperand(1);
8773 Value *IdxOp = IEI->getOperand(2);
8774
8775 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8776 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8777 EI->getOperand(0)->getType() == V->getType()) {
8778 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008779 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8780 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008781
8782 // Either the extracted from or inserted into vector must be RHSVec,
8783 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008784 if (EI->getOperand(0) == RHS || RHS == 0) {
8785 RHS = EI->getOperand(0);
8786 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008787 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008788 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008789 return V;
8790 }
8791
Chris Lattner90951862006-04-16 00:51:47 +00008792 if (VecOp == RHS) {
8793 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008794 // Everything but the extracted element is replaced with the RHS.
8795 for (unsigned i = 0; i != NumElts; ++i) {
8796 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008797 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008798 }
8799 return V;
8800 }
Chris Lattner90951862006-04-16 00:51:47 +00008801
8802 // If this insertelement is a chain that comes from exactly these two
8803 // vectors, return the vector and the effective shuffle.
8804 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8805 return EI->getOperand(0);
8806
Chris Lattner39fac442006-04-15 01:39:45 +00008807 }
8808 }
8809 }
Chris Lattner90951862006-04-16 00:51:47 +00008810 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008811
8812 // Otherwise, can't do anything fancy. Return an identity vector.
8813 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008814 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008815 return V;
8816}
8817
8818Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8819 Value *VecOp = IE.getOperand(0);
8820 Value *ScalarOp = IE.getOperand(1);
8821 Value *IdxOp = IE.getOperand(2);
8822
8823 // If the inserted element was extracted from some other vector, and if the
8824 // indexes are constant, try to turn this into a shufflevector operation.
8825 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8826 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8827 EI->getOperand(0)->getType() == IE.getType()) {
8828 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008829 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8830 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008831
8832 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8833 return ReplaceInstUsesWith(IE, VecOp);
8834
8835 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8836 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8837
8838 // If we are extracting a value from a vector, then inserting it right
8839 // back into the same place, just use the input vector.
8840 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8841 return ReplaceInstUsesWith(IE, VecOp);
8842
8843 // We could theoretically do this for ANY input. However, doing so could
8844 // turn chains of insertelement instructions into a chain of shufflevector
8845 // instructions, and right now we do not merge shufflevectors. As such,
8846 // only do this in a situation where it is clear that there is benefit.
8847 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8848 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8849 // the values of VecOp, except then one read from EIOp0.
8850 // Build a new shuffle mask.
8851 std::vector<Constant*> Mask;
8852 if (isa<UndefValue>(VecOp))
8853 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8854 else {
8855 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008856 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008857 NumVectorElts));
8858 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008859 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008860 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8861 ConstantPacked::get(Mask));
8862 }
8863
8864 // If this insertelement isn't used by some other insertelement, turn it
8865 // (and any insertelements it points to), into one big shuffle.
8866 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8867 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008868 Value *RHS = 0;
8869 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8870 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8871 // We now have a shuffle of LHS, RHS, Mask.
8872 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008873 }
8874 }
8875 }
8876
8877 return 0;
8878}
8879
8880
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008881Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8882 Value *LHS = SVI.getOperand(0);
8883 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008884 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008885
8886 bool MadeChange = false;
8887
Chris Lattner2deeaea2006-10-05 06:55:50 +00008888 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008889 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008890 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8891
Chris Lattner39fac442006-04-15 01:39:45 +00008892 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8893 // the undef, change them to undefs.
8894
Chris Lattner12249be2006-05-25 23:48:38 +00008895 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8896 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8897 if (LHS == RHS || isa<UndefValue>(LHS)) {
8898 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008899 // shuffle(undef,undef,mask) -> undef.
8900 return ReplaceInstUsesWith(SVI, LHS);
8901 }
8902
Chris Lattner12249be2006-05-25 23:48:38 +00008903 // Remap any references to RHS to use LHS.
8904 std::vector<Constant*> Elts;
8905 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008906 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008907 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008908 else {
8909 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8910 (Mask[i] < e && isa<UndefValue>(LHS)))
8911 Mask[i] = 2*e; // Turn into undef.
8912 else
8913 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008914 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008915 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008916 }
Chris Lattner12249be2006-05-25 23:48:38 +00008917 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008918 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008919 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008920 LHS = SVI.getOperand(0);
8921 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008922 MadeChange = true;
8923 }
8924
Chris Lattner0e477162006-05-26 00:29:06 +00008925 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008926 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008927
Chris Lattner12249be2006-05-25 23:48:38 +00008928 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8929 if (Mask[i] >= e*2) continue; // Ignore undef values.
8930 // Is this an identity shuffle of the LHS value?
8931 isLHSID &= (Mask[i] == i);
8932
8933 // Is this an identity shuffle of the RHS value?
8934 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008935 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008936
Chris Lattner12249be2006-05-25 23:48:38 +00008937 // Eliminate identity shuffles.
8938 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8939 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008940
Chris Lattner0e477162006-05-26 00:29:06 +00008941 // If the LHS is a shufflevector itself, see if we can combine it with this
8942 // one without producing an unusual shuffle. Here we are really conservative:
8943 // we are absolutely afraid of producing a shuffle mask not in the input
8944 // program, because the code gen may not be smart enough to turn a merged
8945 // shuffle into two specific shuffles: it may produce worse code. As such,
8946 // we only merge two shuffles if the result is one of the two input shuffle
8947 // masks. In this case, merging the shuffles just removes one instruction,
8948 // which we know is safe. This is good for things like turning:
8949 // (splat(splat)) -> splat.
8950 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8951 if (isa<UndefValue>(RHS)) {
8952 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8953
8954 std::vector<unsigned> NewMask;
8955 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8956 if (Mask[i] >= 2*e)
8957 NewMask.push_back(2*e);
8958 else
8959 NewMask.push_back(LHSMask[Mask[i]]);
8960
8961 // If the result mask is equal to the src shuffle or this shuffle mask, do
8962 // the replacement.
8963 if (NewMask == LHSMask || NewMask == Mask) {
8964 std::vector<Constant*> Elts;
8965 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8966 if (NewMask[i] >= e*2) {
8967 Elts.push_back(UndefValue::get(Type::UIntTy));
8968 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008969 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008970 }
8971 }
8972 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8973 LHSSVI->getOperand(1),
8974 ConstantPacked::get(Elts));
8975 }
8976 }
8977 }
8978
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008979 return MadeChange ? &SVI : 0;
8980}
8981
8982
Robert Bocchinoa8352962006-01-13 22:48:06 +00008983
Chris Lattner99f48c62002-09-02 04:59:56 +00008984void InstCombiner::removeFromWorkList(Instruction *I) {
8985 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8986 WorkList.end());
8987}
8988
Chris Lattner39c98bb2004-12-08 23:43:58 +00008989
8990/// TryToSinkInstruction - Try to move the specified instruction from its
8991/// current block into the beginning of DestBlock, which can only happen if it's
8992/// safe to move the instruction past all of the instructions between it and the
8993/// end of its block.
8994static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8995 assert(I->hasOneUse() && "Invariants didn't hold!");
8996
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008997 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8998 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008999
Chris Lattner39c98bb2004-12-08 23:43:58 +00009000 // Do not sink alloca instructions out of the entry block.
9001 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9002 return false;
9003
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009004 // We can only sink load instructions if there is nothing between the load and
9005 // the end of block that could change the value.
9006 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009007 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9008 Scan != E; ++Scan)
9009 if (Scan->mayWriteToMemory())
9010 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009011 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009012
9013 BasicBlock::iterator InsertPos = DestBlock->begin();
9014 while (isa<PHINode>(InsertPos)) ++InsertPos;
9015
Chris Lattner9f269e42005-08-08 19:11:57 +00009016 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009017 ++NumSunkInst;
9018 return true;
9019}
9020
Chris Lattner1443bc52006-05-11 17:11:52 +00009021/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00009022/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00009023/// if possible.
9024static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9025 if (!TD) return CE;
9026
9027 Constant *Ptr = CE->getOperand(0);
9028 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9029 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9030 // If this is a constant expr gep that is effectively computing an
9031 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9032 bool isFoldableGEP = true;
9033 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9034 if (!isa<ConstantInt>(CE->getOperand(i)))
9035 isFoldableGEP = false;
9036 if (isFoldableGEP) {
9037 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9038 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00009039 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009040 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009041 }
9042 }
9043
9044 return CE;
9045}
9046
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009047
9048/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9049/// all reachable code to the worklist.
9050///
9051/// This has a couple of tricks to make the code faster and more powerful. In
9052/// particular, we constant fold and DCE instructions as we go, to avoid adding
9053/// them to the worklist (this significantly speeds up instcombine on code where
9054/// many instructions are dead or constant). Additionally, if we find a branch
9055/// whose condition is a known constant, we only visit the reachable successors.
9056///
9057static void AddReachableCodeToWorklist(BasicBlock *BB,
9058 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009059 std::vector<Instruction*> &WorkList,
9060 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009061 // We have now visited this block! If we've already been here, bail out.
9062 if (!Visited.insert(BB).second) return;
9063
9064 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9065 Instruction *Inst = BBI++;
9066
9067 // DCE instruction if trivially dead.
9068 if (isInstructionTriviallyDead(Inst)) {
9069 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009070 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009071 Inst->eraseFromParent();
9072 continue;
9073 }
9074
9075 // ConstantProp instruction if trivially constant.
9076 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009077 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9078 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009079 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009080 Inst->replaceAllUsesWith(C);
9081 ++NumConstProp;
9082 Inst->eraseFromParent();
9083 continue;
9084 }
9085
9086 WorkList.push_back(Inst);
9087 }
9088
9089 // Recursively visit successors. If this is a branch or switch on a constant,
9090 // only visit the reachable successor.
9091 TerminatorInst *TI = BB->getTerminator();
9092 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9093 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9094 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009095 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9096 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009097 return;
9098 }
9099 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9100 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9101 // See if this is an explicit destination.
9102 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9103 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009104 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009105 return;
9106 }
9107
9108 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009109 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009110 return;
9111 }
9112 }
9113
9114 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009115 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009116}
9117
Chris Lattner113f4f42002-06-25 16:13:24 +00009118bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009119 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009120 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009121
Chris Lattner4ed40f72005-07-07 20:40:38 +00009122 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009123 // Do a depth-first traversal of the function, populate the worklist with
9124 // the reachable instructions. Ignore blocks that are not reachable. Keep
9125 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009126 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009127 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009128
Chris Lattner4ed40f72005-07-07 20:40:38 +00009129 // Do a quick scan over the function. If we find any blocks that are
9130 // unreachable, remove any instructions inside of them. This prevents
9131 // the instcombine code from having to deal with some bad special cases.
9132 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9133 if (!Visited.count(BB)) {
9134 Instruction *Term = BB->getTerminator();
9135 while (Term != BB->begin()) { // Remove instrs bottom-up
9136 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009137
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009138 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009139 ++NumDeadInst;
9140
9141 if (!I->use_empty())
9142 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9143 I->eraseFromParent();
9144 }
9145 }
9146 }
Chris Lattnerca081252001-12-14 16:52:21 +00009147
9148 while (!WorkList.empty()) {
9149 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9150 WorkList.pop_back();
9151
Chris Lattner1443bc52006-05-11 17:11:52 +00009152 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009153 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009154 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009155 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009156 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009157 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009158
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009159 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009160
9161 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009162 removeFromWorkList(I);
9163 continue;
9164 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009165
Chris Lattner1443bc52006-05-11 17:11:52 +00009166 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009167 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009168 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9169 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009170 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009171
Chris Lattner1443bc52006-05-11 17:11:52 +00009172 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009173 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009174 ReplaceInstUsesWith(*I, C);
9175
Chris Lattner99f48c62002-09-02 04:59:56 +00009176 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009177 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009178 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009179 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009180 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009181
Chris Lattner39c98bb2004-12-08 23:43:58 +00009182 // See if we can trivially sink this instruction to a successor basic block.
9183 if (I->hasOneUse()) {
9184 BasicBlock *BB = I->getParent();
9185 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9186 if (UserParent != BB) {
9187 bool UserIsSuccessor = false;
9188 // See if the user is one of our successors.
9189 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9190 if (*SI == UserParent) {
9191 UserIsSuccessor = true;
9192 break;
9193 }
9194
9195 // If the user is one of our immediate successors, and if that successor
9196 // only has us as a predecessors (we'd have to split the critical edge
9197 // otherwise), we can keep going.
9198 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9199 next(pred_begin(UserParent)) == pred_end(UserParent))
9200 // Okay, the CFG is simple enough, try to sink this instruction.
9201 Changed |= TryToSinkInstruction(I, UserParent);
9202 }
9203 }
9204
Chris Lattnerca081252001-12-14 16:52:21 +00009205 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009206 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009207 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009208 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009209 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009210 DOUT << "IC: Old = " << *I
9211 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009212
Chris Lattner396dbfe2004-06-09 05:08:07 +00009213 // Everything uses the new instruction now.
9214 I->replaceAllUsesWith(Result);
9215
9216 // Push the new instruction and any users onto the worklist.
9217 WorkList.push_back(Result);
9218 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009219
9220 // Move the name to the new instruction first...
9221 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009222 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009223
9224 // Insert the new instruction into the basic block...
9225 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009226 BasicBlock::iterator InsertPos = I;
9227
9228 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9229 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9230 ++InsertPos;
9231
9232 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009233
Chris Lattner63d75af2004-05-01 23:27:23 +00009234 // Make sure that we reprocess all operands now that we reduced their
9235 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009236 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9237 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9238 WorkList.push_back(OpI);
9239
Chris Lattner396dbfe2004-06-09 05:08:07 +00009240 // Instructions can end up on the worklist more than once. Make sure
9241 // we do not process an instruction that has been deleted.
9242 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009243
9244 // Erase the old instruction.
9245 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009246 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009247 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009248
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009249 // If the instruction was modified, it's possible that it is now dead.
9250 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009251 if (isInstructionTriviallyDead(I)) {
9252 // Make sure we process all operands now that we are reducing their
9253 // use counts.
9254 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9255 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9256 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009257
Chris Lattner63d75af2004-05-01 23:27:23 +00009258 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009259 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009260 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009261 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009262 } else {
9263 WorkList.push_back(Result);
9264 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009265 }
Chris Lattner053c0932002-05-14 15:24:07 +00009266 }
Chris Lattner260ab202002-04-18 17:39:14 +00009267 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009268 }
9269 }
9270
Chris Lattner260ab202002-04-18 17:39:14 +00009271 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009272}
9273
Brian Gaeke38b79e82004-07-27 17:43:21 +00009274FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009275 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009276}
Brian Gaeke960707c2003-11-11 22:41:34 +00009277