blob: f81f10e71e1e15df6a70e071ab85c88915d7f22f [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
Zhou Sheng75b871f2007-01-11 12:24:14 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
306 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000307
Zhou Sheng75b871f2007-01-11 12:24:14 +0000308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000309 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) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000342 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
343 if (ITy->getBitWidth() < 32)
344 return Type::Int32Ty;
345 } else if (Ty == Type::FloatTy)
346 return Type::DoubleTy;
347 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000348}
349
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000350/// getBitCastOperand - If the specified operand is a CastInst or a constant
351/// expression bitcast, return the operand value, otherwise return null.
352static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000357 return CE->getOperand(0);
358 return 0;
359}
360
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000361/// This function is a wrapper around CastInst::isEliminableCastPair. It
362/// simply extracts arguments and returns what that function returns.
363/// @Determine if it is valid to eliminate a Convert pair
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000374
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000378
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000382}
383
384/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385/// in any code being generated. It does not require codegen if V is simple
386/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000387static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 if (V->getType() == Ty || isa<Constant>(V)) return false;
390
Chris Lattner99155be2006-05-25 23:24:33 +0000391 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000392 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000393 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000394 return false;
395 return true;
396}
397
398/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399/// InsertBefore instruction. This is specialized a bit to avoid inserting
400/// casts that are known to not do anything...
401///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000402Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000404 Instruction *InsertBefore) {
405 if (V->getType() == DestTy) return V;
406 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000407 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408
Reid Spencer13bc5d72006-12-12 09:18:51 +0000409 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410}
411
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000412// SimplifyCommutative - This performs a few simplifications for commutative
413// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000414//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000415// 1. Order operands such that they are listed from right (least complex) to
416// left (most complex). This puts constants before unary operators before
417// binary operators.
418//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000419// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000422bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000423 bool Changed = false;
424 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000426
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427 if (!I.isAssociative()) return Changed;
428 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000429 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000432 Constant *Folded = ConstantExpr::get(I.getOpcode(),
433 cast<Constant>(I.getOperand(1)),
434 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 I.setOperand(0, Op->getOperand(0));
436 I.setOperand(1, Folded);
437 return true;
438 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440 isOnlyUse(Op) && isOnlyUse(Op1)) {
441 Constant *C1 = cast<Constant>(Op->getOperand(1));
442 Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000445 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000446 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447 Op1->getOperand(0),
448 Op1->getName(), &I);
449 WorkList.push_back(New);
450 I.setOperand(0, New);
451 I.setOperand(1, Folded);
452 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000456}
Chris Lattnerca081252001-12-14 16:52:21 +0000457
Reid Spencer266e42b2006-12-23 06:05:41 +0000458/// SimplifyCompare - For a CmpInst this function just orders the operands
459/// so that theyare listed from right (least complex) to left (most complex).
460/// This puts constants before unary operators before binary operators.
461bool InstCombiner::SimplifyCompare(CmpInst &I) {
462 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463 return false;
464 I.swapOperands();
465 // Compare instructions are not associative so there's nothing else we can do.
466 return true;
467}
468
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000471//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472static inline Value *dyn_castNegVal(Value *V) {
473 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000474 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475
Chris Lattner9ad0d552004-12-14 20:08:06 +0000476 // Constants can be considered to be negated values if they can be folded.
477 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000480}
481
Chris Lattnerbb74e222003-03-10 23:06:50 +0000482static inline Value *dyn_castNotVal(Value *V) {
483 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000484 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485
486 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000487 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000488 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489 return 0;
490}
491
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492// dyn_castFoldableMul - If this value is a multiply that can be folded into
493// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000494// non-constant operand of the multiply, and set CST to point to the multiplier.
495// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000497static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000498 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000499 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000500 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000501 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000504 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 // The multiplier is really 1 << CST.
506 Constant *One = ConstantInt::get(V->getType(), 1);
507 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508 return I->getOperand(0);
509 }
510 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000511 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000512}
Chris Lattner31ae8632002-08-14 17:51:49 +0000513
Chris Lattner0798af32005-01-13 20:14:25 +0000514/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515/// expression, return it.
516static User *dyn_castGetElementPtr(Value *V) {
517 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519 if (CE->getOpcode() == Instruction::GetElementPtr)
520 return cast<User>(V);
521 return false;
522}
523
Chris Lattner623826c2004-09-28 21:48:02 +0000524// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000525static ConstantInt *AddOne(ConstantInt *C) {
526 return cast<ConstantInt>(ConstantExpr::getAdd(C,
527 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000528}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000529static ConstantInt *SubOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getSub(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000532}
533
Chris Lattner4534dd592006-02-09 07:38:58 +0000534/// ComputeMaskedBits - Determine which of the bits specified in Mask are
535/// known to be either zero or one and return them in the KnownZero/KnownOne
536/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
537/// processing.
538static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000540 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
541 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000542 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000543 // optimized based on the contradictory assumption that it is non-zero.
544 // Because instcombine aggressively folds operations with undef args anyway,
545 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000546 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000547 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000548 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000549 KnownZero = ~KnownOne & Mask;
550 return;
551 }
552
553 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000554 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000555 return; // Limit search depth.
556
557 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000558 Instruction *I = dyn_cast<Instruction>(V);
559 if (!I) return;
560
Chris Lattner03c49532007-01-15 02:27:26 +0000561 Mask &= V->getType()->getIntegerTypeMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000562
Chris Lattner0157e7f2006-02-11 09:31:47 +0000563 switch (I->getOpcode()) {
564 case Instruction::And:
565 // If either the LHS or the RHS are Zero, the result is zero.
566 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
567 Mask &= ~KnownZero;
568 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
570 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
571
572 // Output known-1 bits are only known if set in both the LHS & RHS.
573 KnownOne &= KnownOne2;
574 // Output known-0 are known to be clear if zero in either the LHS | RHS.
575 KnownZero |= KnownZero2;
576 return;
577 case Instruction::Or:
578 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
579 Mask &= ~KnownOne;
580 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
582 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
583
584 // Output known-0 bits are only known if clear in both the LHS & RHS.
585 KnownZero &= KnownZero2;
586 // Output known-1 are known to be set if set in either the LHS | RHS.
587 KnownOne |= KnownOne2;
588 return;
589 case Instruction::Xor: {
590 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
593 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
594
595 // Output known-0 bits are known if clear or set in both the LHS & RHS.
596 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597 // Output known-1 are known to be set if set in only one of the LHS, RHS.
598 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599 KnownZero = KnownZeroOut;
600 return;
601 }
602 case Instruction::Select:
603 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607
608 // Only known if known in both the LHS and RHS.
609 KnownOne &= KnownOne2;
610 KnownZero &= KnownZero2;
611 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000612 case Instruction::FPTrunc:
613 case Instruction::FPExt:
614 case Instruction::FPToUI:
615 case Instruction::FPToSI:
616 case Instruction::SIToFP:
617 case Instruction::PtrToInt:
618 case Instruction::UIToFP:
619 case Instruction::IntToPtr:
620 return; // Can't work with floating point or pointers
621 case Instruction::Trunc:
622 // All these have integer operands
623 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
624 return;
625 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000626 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000627 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000629 return;
630 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631 break;
632 }
633 case Instruction::ZExt: {
634 // Compute the bits in the result that are not present in the input.
635 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000636 uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
637 uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000638
Chris Lattner03c49532007-01-15 02:27:26 +0000639 Mask &= SrcTy->getIntegerTypeMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 // The top bits are known to be zero.
643 KnownZero |= NewBits;
644 return;
645 }
646 case Instruction::SExt: {
647 // Compute the bits in the result that are not present in the input.
648 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000649 uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
650 uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000651
Chris Lattner03c49532007-01-15 02:27:26 +0000652 Mask &= SrcTy->getIntegerTypeMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000655
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000656 // If the sign bit of the input is known set or clear, then we know the
657 // top bits of the result.
658 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659 if (KnownZero & InSignBit) { // Input sign bit known zero
660 KnownZero |= NewBits;
661 KnownOne &= ~NewBits;
662 } else if (KnownOne & InSignBit) { // Input sign bit known set
663 KnownOne |= NewBits;
664 KnownZero &= ~NewBits;
665 } else { // Input sign bit unknown
666 KnownZero &= ~NewBits;
667 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000668 }
669 return;
670 }
671 case Instruction::Shl:
672 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000673 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674 uint64_t ShiftAmt = SA->getZExtValue();
675 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000676 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000678 KnownZero <<= ShiftAmt;
679 KnownOne <<= ShiftAmt;
680 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 return;
682 }
683 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000684 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000685 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000688 uint64_t ShiftAmt = SA->getZExtValue();
689 uint64_t HighBits = (1ULL << ShiftAmt)-1;
690 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000691
Reid Spencerfdff9382006-11-08 06:47:33 +0000692 // Unsigned shift right.
693 Mask <<= ShiftAmt;
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
696 KnownZero >>= ShiftAmt;
697 KnownOne >>= ShiftAmt;
698 KnownZero |= HighBits; // high bits known zero.
699 return;
700 }
701 break;
702 case Instruction::AShr:
703 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
704 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705 // Compute the new bits that are at the top now.
706 uint64_t ShiftAmt = SA->getZExtValue();
707 uint64_t HighBits = (1ULL << ShiftAmt)-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
709
710 // Signed shift right.
711 Mask <<= ShiftAmt;
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= ShiftAmt;
715 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000716
Reid Spencerfdff9382006-11-08 06:47:33 +0000717 // Handle the sign bits.
718 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720
Reid Spencerfdff9382006-11-08 06:47:33 +0000721 if (KnownZero & SignBit) { // New bits are known zero.
722 KnownZero |= HighBits;
723 } else if (KnownOne & SignBit) { // New bits are known one.
724 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000725 }
726 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000727 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000728 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000729 }
Chris Lattner92a68652006-02-07 08:05:22 +0000730}
731
732/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
733/// this predicate to simplify operations downstream. Mask is known to be zero
734/// for bits that V cannot have.
735static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000736 uint64_t KnownZero, KnownOne;
737 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
739 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000740}
741
Chris Lattner0157e7f2006-02-11 09:31:47 +0000742/// ShrinkDemandedConstant - Check to see if the specified operand of the
743/// specified instruction is a constant integer. If so, check to see if there
744/// are any bits set in the constant that are not demanded. If so, shrink the
745/// constant and return true.
746static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
747 uint64_t Demanded) {
748 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749 if (!OpC) return false;
750
751 // If there are no bits set that aren't demanded, nothing to do.
752 if ((~Demanded & OpC->getZExtValue()) == 0)
753 return false;
754
755 // This is producing any bits that are not needed, shrink the RHS.
756 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000757 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000758 return true;
759}
760
Chris Lattneree0f2802006-02-12 02:07:56 +0000761// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
762// set of known zero and one bits, compute the maximum and minimum values that
763// could have the specified known zero and known one bits, returning them in
764// min/max.
765static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
766 uint64_t KnownZero,
767 uint64_t KnownOne,
768 int64_t &Min, int64_t &Max) {
Chris Lattner03c49532007-01-15 02:27:26 +0000769 uint64_t TypeBits = Ty->getIntegerTypeMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000770 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
771
772 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
773
774 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775 // bit if it is unknown.
776 Min = KnownOne;
777 Max = KnownOne|UnknownBits;
778
779 if (SignBit & UnknownBits) { // Sign bit is unknown
780 Min |= SignBit;
781 Max &= ~SignBit;
782 }
783
784 // Sign extend the min/max values.
785 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786 Min = (Min << ShAmt) >> ShAmt;
787 Max = (Max << ShAmt) >> ShAmt;
788}
789
790// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791// a set of known zero and one bits, compute the maximum and minimum values that
792// could have the specified known zero and known one bits, returning them in
793// min/max.
794static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
795 uint64_t KnownZero,
796 uint64_t KnownOne,
797 uint64_t &Min,
798 uint64_t &Max) {
Chris Lattner03c49532007-01-15 02:27:26 +0000799 uint64_t TypeBits = Ty->getIntegerTypeMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000800 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801
802 // The minimum value is when the unknown bits are all zeros.
803 Min = KnownOne;
804 // The maximum value is when the unknown bits are all ones.
805 Max = KnownOne|UnknownBits;
806}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000807
808
809/// SimplifyDemandedBits - Look at V. At this point, we know that only the
810/// DemandedMask bits of the result of V are ever used downstream. If we can
811/// use this information to simplify V, do so and return true. Otherwise,
812/// analyze the expression and return a mask of KnownOne and KnownZero bits for
813/// the expression (used to simplify the caller). The KnownZero/One bits may
814/// only be accurate for those bits in the DemandedMask.
815bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000817 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000818 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000819 // We know all of the bits for a constant!
820 KnownOne = CI->getZExtValue() & DemandedMask;
821 KnownZero = ~KnownOne & DemandedMask;
822 return false;
823 }
824
825 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000826 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000827 if (Depth != 0) { // Not at the root.
828 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000830 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 }
Chris Lattner2590e512006-02-07 06:56:34 +0000832 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000833 // just set the DemandedMask to all bits.
Chris Lattner03c49532007-01-15 02:27:26 +0000834 DemandedMask = V->getType()->getIntegerTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000836 if (V != UndefValue::get(V->getType()))
837 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
838 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000839 } else if (Depth == 6) { // Limit search depth.
840 return false;
841 }
842
843 Instruction *I = dyn_cast<Instruction>(V);
844 if (!I) return false; // Only analyze instructions.
845
Chris Lattner03c49532007-01-15 02:27:26 +0000846 DemandedMask &= V->getType()->getIntegerTypeMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000847
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000848 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000849 switch (I->getOpcode()) {
850 default: break;
851 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000852 // If either the LHS or the RHS are Zero, the result is zero.
853 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854 KnownZero, KnownOne, Depth+1))
855 return true;
856 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
857
858 // If something is known zero on the RHS, the bits aren't demanded on the
859 // LHS.
860 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861 KnownZero2, KnownOne2, Depth+1))
862 return true;
863 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
864
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000865 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000866 // These bits cannot contribute to the result of the 'and'.
867 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000871
872 // If all of the demanded bits in the inputs are known zeros, return zero.
873 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
875
Chris Lattner0157e7f2006-02-11 09:31:47 +0000876 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000877 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000878 return UpdateValueUsesWith(I, I);
879
880 // Output known-1 bits are only known if set in both the LHS & RHS.
881 KnownOne &= KnownOne2;
882 // Output known-0 are known to be clear if zero in either the LHS | RHS.
883 KnownZero |= KnownZero2;
884 break;
885 case Instruction::Or:
886 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
887 KnownZero, KnownOne, Depth+1))
888 return true;
889 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
890 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
891 KnownZero2, KnownOne2, Depth+1))
892 return true;
893 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
894
895 // If all of the demanded bits are known zero on one side, return the other.
896 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000897 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000899 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000900 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000901
902 // If all of the potentially set bits on one side are known to be set on
903 // the other side, just use the 'other' side.
904 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
905 (DemandedMask & (~KnownZero)))
906 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000907 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
908 (DemandedMask & (~KnownZero2)))
909 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000910
911 // If the RHS is a constant, see if we can simplify it.
912 if (ShrinkDemandedConstant(I, 1, DemandedMask))
913 return UpdateValueUsesWith(I, I);
914
915 // Output known-0 bits are only known if clear in both the LHS & RHS.
916 KnownZero &= KnownZero2;
917 // Output known-1 are known to be set if set in either the LHS | RHS.
918 KnownOne |= KnownOne2;
919 break;
920 case Instruction::Xor: {
921 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922 KnownZero, KnownOne, Depth+1))
923 return true;
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
926 KnownZero2, KnownOne2, Depth+1))
927 return true;
928 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
929
930 // If all of the demanded bits are known zero on one side, return the other.
931 // These bits cannot contribute to the result of the 'xor'.
932 if ((DemandedMask & KnownZero) == DemandedMask)
933 return UpdateValueUsesWith(I, I->getOperand(0));
934 if ((DemandedMask & KnownZero2) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(1));
936
937 // Output known-0 bits are known if clear or set in both the LHS & RHS.
938 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939 // Output known-1 are known to be set if set in only one of the LHS, RHS.
940 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
941
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000942 // If all of the demanded bits are known to be zero on one side or the
943 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000944 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000945 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
946 Instruction *Or =
947 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
948 I->getName());
949 InsertNewInstBefore(Or, *I);
950 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000951 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000952
Chris Lattner5b2edb12006-02-12 08:02:11 +0000953 // If all of the demanded bits on one side are known, and all of the set
954 // bits on that side are also known to be set on the other side, turn this
955 // into an AND, as we know the bits will be cleared.
956 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000959 Constant *AndC = ConstantInt::get(I->getType(),
960 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000961 Instruction *And =
962 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963 InsertNewInstBefore(And, *I);
964 return UpdateValueUsesWith(I, And);
965 }
966 }
967
Chris Lattner0157e7f2006-02-11 09:31:47 +0000968 // If the RHS is a constant, see if we can simplify it.
969 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
971 return UpdateValueUsesWith(I, I);
972
973 KnownZero = KnownZeroOut;
974 KnownOne = KnownOneOut;
975 break;
976 }
977 case Instruction::Select:
978 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979 KnownZero, KnownOne, Depth+1))
980 return true;
981 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
982 KnownZero2, KnownOne2, Depth+1))
983 return true;
984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
985 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
986
987 // If the operands are constants, see if we can simplify them.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
989 return UpdateValueUsesWith(I, I);
990 if (ShrinkDemandedConstant(I, 2, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992
993 // Only known if known in both the LHS and RHS.
994 KnownOne &= KnownOne2;
995 KnownZero &= KnownZero2;
996 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000997 case Instruction::Trunc:
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 KnownZero, KnownOne, Depth+1))
1000 return true;
1001 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1002 break;
1003 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001004 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001005 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001006
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 KnownZero, KnownOne, Depth+1))
1009 return true;
1010 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1011 break;
1012 case Instruction::ZExt: {
1013 // Compute the bits in the result that are not present in the input.
1014 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00001015 uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1016 uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001017
Chris Lattner03c49532007-01-15 02:27:26 +00001018 DemandedMask &= SrcTy->getIntegerTypeMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 // The top bits are known to be zero.
1024 KnownZero |= NewBits;
1025 break;
1026 }
1027 case Instruction::SExt: {
1028 // Compute the bits in the result that are not present in the input.
1029 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00001030 uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1031 uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001032
1033 // Get the sign bit for the source type
1034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Chris Lattner03c49532007-01-15 02:27:26 +00001035 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegerTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001036
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001037 // If any of the sign extended bits are demanded, we know that the sign
1038 // bit is demanded.
1039 if (NewBits & DemandedMask)
1040 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001041
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001042 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043 KnownZero, KnownOne, Depth+1))
1044 return true;
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001046
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001049
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
1052 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053 // Convert to ZExt cast
1054 CastInst *NewCast = CastInst::create(
1055 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1056 return UpdateValueUsesWith(I, NewCast);
1057 } else if (KnownOne & InSignBit) { // Input sign bit known set
1058 KnownOne |= NewBits;
1059 KnownZero &= ~NewBits;
1060 } else { // Input sign bit unknown
1061 KnownZero &= ~NewBits;
1062 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001063 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001064 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001065 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001066 case Instruction::Add:
1067 // If there is a constant on the RHS, there are a variety of xformations
1068 // we can do.
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1072 if (RHS->isNullValue())
1073 break;
1074
1075 // Figure out what the input bits are. If the top bits of the and result
1076 // are not demanded, then the add doesn't demand them from its input
1077 // either.
1078
1079 // Shift the demanded mask up so that it's at the top of the uint64_t.
1080 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1081 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1082
1083 // If the top bit of the output is demanded, demand everything from the
1084 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001085 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001086
1087 // Find information about known zero/one bits in the input.
1088 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1089 KnownZero2, KnownOne2, Depth+1))
1090 return true;
1091
1092 // If the RHS of the add has bits set that can't affect the input, reduce
1093 // the constant.
1094 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1095 return UpdateValueUsesWith(I, I);
1096
1097 // Avoid excess work.
1098 if (KnownZero2 == 0 && KnownOne2 == 0)
1099 break;
1100
1101 // Turn it into OR if input bits are zero.
1102 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1103 Instruction *Or =
1104 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1105 I->getName());
1106 InsertNewInstBefore(Or, *I);
1107 return UpdateValueUsesWith(I, Or);
1108 }
1109
1110 // We can say something about the output known-zero and known-one bits,
1111 // depending on potential carries from the input constant and the
1112 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1113 // bits set and the RHS constant is 0x01001, then we know we have a known
1114 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1115
1116 // To compute this, we first compute the potential carry bits. These are
1117 // the bits which may be modified. I'm not aware of a better way to do
1118 // this scan.
1119 uint64_t RHSVal = RHS->getZExtValue();
1120
1121 bool CarryIn = false;
1122 uint64_t CarryBits = 0;
1123 uint64_t CurBit = 1;
1124 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1125 // Record the current carry in.
1126 if (CarryIn) CarryBits |= CurBit;
1127
1128 bool CarryOut;
1129
1130 // This bit has a carry out unless it is "zero + zero" or
1131 // "zero + anything" with no carry in.
1132 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1133 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1134 } else if (!CarryIn &&
1135 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1136 CarryOut = false; // 0 + anything has no carry out if no carry in.
1137 } else {
1138 // Otherwise, we have to assume we have a carry out.
1139 CarryOut = true;
1140 }
1141
1142 // This stage's carry out becomes the next stage's carry-in.
1143 CarryIn = CarryOut;
1144 }
1145
1146 // Now that we know which bits have carries, compute the known-1/0 sets.
1147
1148 // Bits are known one if they are known zero in one operand and one in the
1149 // other, and there is no input carry.
1150 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1151
1152 // Bits are known zero if they are known zero in both operands and there
1153 // is no input carry.
1154 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1155 }
1156 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001157 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001158 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 uint64_t ShiftAmt = SA->getZExtValue();
1160 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001161 KnownZero, KnownOne, Depth+1))
1162 return true;
1163 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001164 KnownZero <<= ShiftAmt;
1165 KnownOne <<= ShiftAmt;
1166 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001167 }
Chris Lattner2590e512006-02-07 06:56:34 +00001168 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001169 case Instruction::LShr:
1170 // For a logical shift right
1171 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 unsigned ShiftAmt = SA->getZExtValue();
1173
1174 // Compute the new bits that are at the top now.
1175 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1176 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner03c49532007-01-15 02:27:26 +00001177 uint64_t TypeMask = I->getType()->getIntegerTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001178 // Unsigned shift right.
1179 if (SimplifyDemandedBits(I->getOperand(0),
1180 (DemandedMask << ShiftAmt) & TypeMask,
1181 KnownZero, KnownOne, Depth+1))
1182 return true;
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1184 KnownZero &= TypeMask;
1185 KnownOne &= TypeMask;
1186 KnownZero >>= ShiftAmt;
1187 KnownOne >>= ShiftAmt;
1188 KnownZero |= HighBits; // high bits known zero.
1189 }
1190 break;
1191 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001192 // If this is an arithmetic shift right and only the low-bit is set, we can
1193 // always convert this into a logical shr, even if the shift amount is
1194 // variable. The low bit of the shift cannot be an input sign bit unless
1195 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001196 if (DemandedMask == 1) {
1197 // Perform the logical shift right.
1198 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1199 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001200 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001201 return UpdateValueUsesWith(I, NewVal);
1202 }
1203
Reid Spencere0fc4df2006-10-20 07:07:24 +00001204 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001206
1207 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001208 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner03c49532007-01-15 02:27:26 +00001210 uint64_t TypeMask = I->getType()->getIntegerTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001211 // Signed shift right.
1212 if (SimplifyDemandedBits(I->getOperand(0),
1213 (DemandedMask << ShiftAmt) & TypeMask,
1214 KnownZero, KnownOne, Depth+1))
1215 return true;
1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1217 KnownZero &= TypeMask;
1218 KnownOne &= TypeMask;
1219 KnownZero >>= ShiftAmt;
1220 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001221
Reid Spencerfdff9382006-11-08 06:47:33 +00001222 // Handle the sign bits.
1223 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001225
Reid Spencerfdff9382006-11-08 06:47:33 +00001226 // If the input sign bit is known to be zero, or if none of the top bits
1227 // are demanded, turn this into an unsigned shift right.
1228 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229 // Perform the logical shift right.
1230 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1231 SA, I->getName());
1232 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233 return UpdateValueUsesWith(I, NewVal);
1234 } else if (KnownOne & SignBit) { // New bits are known one.
1235 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001236 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001237 }
Chris Lattner2590e512006-02-07 06:56:34 +00001238 break;
1239 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001240
1241 // If the client is only demanding bits that we know, return the known
1242 // constant.
1243 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001244 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001245 return false;
1246}
1247
Chris Lattner2deeaea2006-10-05 06:55:50 +00001248
1249/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250/// 64 or fewer elements. DemandedElts contains the set of elements that are
1251/// actually used by the caller. This method analyzes which elements of the
1252/// operand are undef and returns that information in UndefElts.
1253///
1254/// If the information about demanded elements can be used to simplify the
1255/// operation, the operation is simplified, then the resultant value is
1256/// returned. This returns null if no change was made.
1257Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258 uint64_t &UndefElts,
1259 unsigned Depth) {
1260 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261 assert(VWidth <= 64 && "Vector too wide to analyze!");
1262 uint64_t EltMask = ~0ULL >> (64-VWidth);
1263 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264 "Invalid DemandedElts!");
1265
1266 if (isa<UndefValue>(V)) {
1267 // If the entire vector is undefined, just return this info.
1268 UndefElts = EltMask;
1269 return 0;
1270 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271 UndefElts = EltMask;
1272 return UndefValue::get(V->getType());
1273 }
1274
1275 UndefElts = 0;
1276 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278 Constant *Undef = UndefValue::get(EltTy);
1279
1280 std::vector<Constant*> Elts;
1281 for (unsigned i = 0; i != VWidth; ++i)
1282 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1283 Elts.push_back(Undef);
1284 UndefElts |= (1ULL << i);
1285 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1286 Elts.push_back(Undef);
1287 UndefElts |= (1ULL << i);
1288 } else { // Otherwise, defined.
1289 Elts.push_back(CP->getOperand(i));
1290 }
1291
1292 // If we changed the constant, return it.
1293 Constant *NewCP = ConstantPacked::get(Elts);
1294 return NewCP != CP ? NewCP : 0;
1295 } else if (isa<ConstantAggregateZero>(V)) {
1296 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1297 // set to undef.
1298 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299 Constant *Zero = Constant::getNullValue(EltTy);
1300 Constant *Undef = UndefValue::get(EltTy);
1301 std::vector<Constant*> Elts;
1302 for (unsigned i = 0; i != VWidth; ++i)
1303 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304 UndefElts = DemandedElts ^ EltMask;
1305 return ConstantPacked::get(Elts);
1306 }
1307
1308 if (!V->hasOneUse()) { // Other users may use these bits.
1309 if (Depth != 0) { // Not at the root.
1310 // TODO: Just compute the UndefElts information recursively.
1311 return false;
1312 }
1313 return false;
1314 } else if (Depth == 10) { // Limit search depth.
1315 return false;
1316 }
1317
1318 Instruction *I = dyn_cast<Instruction>(V);
1319 if (!I) return false; // Only analyze instructions.
1320
1321 bool MadeChange = false;
1322 uint64_t UndefElts2;
1323 Value *TmpV;
1324 switch (I->getOpcode()) {
1325 default: break;
1326
1327 case Instruction::InsertElement: {
1328 // If this is a variable index, we don't know which element it overwrites.
1329 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001330 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001331 if (Idx == 0) {
1332 // Note that we can't propagate undef elt info, because we don't know
1333 // which elt is getting updated.
1334 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335 UndefElts2, Depth+1);
1336 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1337 break;
1338 }
1339
1340 // If this is inserting an element that isn't demanded, remove this
1341 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001342 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001343 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344 return AddSoonDeadInstToWorklist(*I, 0);
1345
1346 // Otherwise, the element inserted overwrites whatever was there, so the
1347 // input demanded set is simpler than the output set.
1348 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349 DemandedElts & ~(1ULL << IdxNo),
1350 UndefElts, Depth+1);
1351 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1352
1353 // The inserted element is defined.
1354 UndefElts |= 1ULL << IdxNo;
1355 break;
1356 }
1357
1358 case Instruction::And:
1359 case Instruction::Or:
1360 case Instruction::Xor:
1361 case Instruction::Add:
1362 case Instruction::Sub:
1363 case Instruction::Mul:
1364 // div/rem demand all inputs, because they don't want divide by zero.
1365 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366 UndefElts, Depth+1);
1367 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369 UndefElts2, Depth+1);
1370 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1371
1372 // Output elements are undefined if both are undefined. Consider things
1373 // like undef&0. The result is known zero, not undef.
1374 UndefElts &= UndefElts2;
1375 break;
1376
1377 case Instruction::Call: {
1378 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1379 if (!II) break;
1380 switch (II->getIntrinsicID()) {
1381 default: break;
1382
1383 // Binary vector operations that work column-wise. A dest element is a
1384 // function of the corresponding input elements from the two inputs.
1385 case Intrinsic::x86_sse_sub_ss:
1386 case Intrinsic::x86_sse_mul_ss:
1387 case Intrinsic::x86_sse_min_ss:
1388 case Intrinsic::x86_sse_max_ss:
1389 case Intrinsic::x86_sse2_sub_sd:
1390 case Intrinsic::x86_sse2_mul_sd:
1391 case Intrinsic::x86_sse2_min_sd:
1392 case Intrinsic::x86_sse2_max_sd:
1393 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394 UndefElts, Depth+1);
1395 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397 UndefElts2, Depth+1);
1398 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1399
1400 // If only the low elt is demanded and this is a scalarizable intrinsic,
1401 // scalarize it now.
1402 if (DemandedElts == 1) {
1403 switch (II->getIntrinsicID()) {
1404 default: break;
1405 case Intrinsic::x86_sse_sub_ss:
1406 case Intrinsic::x86_sse_mul_ss:
1407 case Intrinsic::x86_sse2_sub_sd:
1408 case Intrinsic::x86_sse2_mul_sd:
1409 // TODO: Lower MIN/MAX/ABS/etc
1410 Value *LHS = II->getOperand(1);
1411 Value *RHS = II->getOperand(2);
1412 // Extract the element as scalars.
1413 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1415
1416 switch (II->getIntrinsicID()) {
1417 default: assert(0 && "Case stmts out of sync!");
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse2_sub_sd:
1420 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421 II->getName()), *II);
1422 break;
1423 case Intrinsic::x86_sse_mul_ss:
1424 case Intrinsic::x86_sse2_mul_sd:
1425 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426 II->getName()), *II);
1427 break;
1428 }
1429
1430 Instruction *New =
1431 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1432 II->getName());
1433 InsertNewInstBefore(New, *II);
1434 AddSoonDeadInstToWorklist(*II, 0);
1435 return New;
1436 }
1437 }
1438
1439 // Output elements are undefined if both are undefined. Consider things
1440 // like undef&0. The result is known zero, not undef.
1441 UndefElts &= UndefElts2;
1442 break;
1443 }
1444 break;
1445 }
1446 }
1447 return MadeChange ? I : 0;
1448}
1449
Reid Spencer266e42b2006-12-23 06:05:41 +00001450/// @returns true if the specified compare instruction is
1451/// true when both operands are equal...
1452/// @brief Determine if the ICmpInst returns true if both operands are equal
1453static bool isTrueWhenEqual(ICmpInst &ICI) {
1454 ICmpInst::Predicate pred = ICI.getPredicate();
1455 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1456 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1457 pred == ICmpInst::ICMP_SLE;
1458}
1459
Chris Lattnerb8b97502003-08-13 19:01:45 +00001460/// AssociativeOpt - Perform an optimization on an associative operator. This
1461/// function is designed to check a chain of associative operators for a
1462/// potential to apply a certain optimization. Since the optimization may be
1463/// applicable if the expression was reassociated, this checks the chain, then
1464/// reassociates the expression as necessary to expose the optimization
1465/// opportunity. This makes use of a special Functor, which must define
1466/// 'shouldApply' and 'apply' methods.
1467///
1468template<typename Functor>
1469Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1470 unsigned Opcode = Root.getOpcode();
1471 Value *LHS = Root.getOperand(0);
1472
1473 // Quick check, see if the immediate LHS matches...
1474 if (F.shouldApply(LHS))
1475 return F.apply(Root);
1476
1477 // Otherwise, if the LHS is not of the same opcode as the root, return.
1478 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001479 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001480 // Should we apply this transform to the RHS?
1481 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1482
1483 // If not to the RHS, check to see if we should apply to the LHS...
1484 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1485 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1486 ShouldApply = true;
1487 }
1488
1489 // If the functor wants to apply the optimization to the RHS of LHSI,
1490 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1491 if (ShouldApply) {
1492 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001493
Chris Lattnerb8b97502003-08-13 19:01:45 +00001494 // Now all of the instructions are in the current basic block, go ahead
1495 // and perform the reassociation.
1496 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1497
1498 // First move the selected RHS to the LHS of the root...
1499 Root.setOperand(0, LHSI->getOperand(1));
1500
1501 // Make what used to be the LHS of the root be the user of the root...
1502 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001503 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001504 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1505 return 0;
1506 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001507 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001508 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001509 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1510 BasicBlock::iterator ARI = &Root; ++ARI;
1511 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1512 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001513
1514 // Now propagate the ExtraOperand down the chain of instructions until we
1515 // get to LHSI.
1516 while (TmpLHSI != LHSI) {
1517 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001518 // Move the instruction to immediately before the chain we are
1519 // constructing to avoid breaking dominance properties.
1520 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1521 BB->getInstList().insert(ARI, NextLHSI);
1522 ARI = NextLHSI;
1523
Chris Lattnerb8b97502003-08-13 19:01:45 +00001524 Value *NextOp = NextLHSI->getOperand(1);
1525 NextLHSI->setOperand(1, ExtraOperand);
1526 TmpLHSI = NextLHSI;
1527 ExtraOperand = NextOp;
1528 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001529
Chris Lattnerb8b97502003-08-13 19:01:45 +00001530 // Now that the instructions are reassociated, have the functor perform
1531 // the transformation...
1532 return F.apply(Root);
1533 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534
Chris Lattnerb8b97502003-08-13 19:01:45 +00001535 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1536 }
1537 return 0;
1538}
1539
1540
1541// AddRHS - Implements: X + X --> X << 1
1542struct AddRHS {
1543 Value *RHS;
1544 AddRHS(Value *rhs) : RHS(rhs) {}
1545 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1546 Instruction *apply(BinaryOperator &Add) const {
1547 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001548 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001549 }
1550};
1551
1552// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1553// iff C1&C2 == 0
1554struct AddMaskingAnd {
1555 Constant *C2;
1556 AddMaskingAnd(Constant *c) : C2(c) {}
1557 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001559 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001560 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001561 }
1562 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001563 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001564 }
1565};
1566
Chris Lattner86102b82005-01-01 16:22:27 +00001567static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001568 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001569 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001570 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001571 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001572
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001573 return IC->InsertNewInstBefore(CastInst::create(
1574 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001575 }
1576
Chris Lattner183b3362004-04-09 19:05:30 +00001577 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001578 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1579 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001580
Chris Lattner183b3362004-04-09 19:05:30 +00001581 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1582 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001583 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1584 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001585 }
1586
1587 Value *Op0 = SO, *Op1 = ConstOperand;
1588 if (!ConstIsRHS)
1589 std::swap(Op0, Op1);
1590 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1592 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001593 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1594 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1595 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001596 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001598 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001599 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001600 abort();
1601 }
Chris Lattner86102b82005-01-01 16:22:27 +00001602 return IC->InsertNewInstBefore(New, I);
1603}
1604
1605// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606// constant as the other operand, try to fold the binary operator into the
1607// select arguments. This also works for Cast instructions, which obviously do
1608// not have a second operand.
1609static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610 InstCombiner *IC) {
1611 // Don't modify shared select instructions
1612 if (!SI->hasOneUse()) return 0;
1613 Value *TV = SI->getOperand(1);
1614 Value *FV = SI->getOperand(2);
1615
1616 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001617 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001618 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001619
Chris Lattner86102b82005-01-01 16:22:27 +00001620 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623 return new SelectInst(SI->getCondition(), SelectTrueVal,
1624 SelectFalseVal);
1625 }
1626 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001627}
1628
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001629
1630/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631/// node as operand #0, see if we can fold the instruction into the PHI (which
1632/// is only possible if all operands to the PHI are constants).
1633Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001635 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001636 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001637
Chris Lattner04689872006-09-09 22:02:56 +00001638 // Check to see if all of the operands of the PHI are constants. If there is
1639 // one non-constant value, remember the BB it is. If there is more than one
1640 // bail out.
1641 BasicBlock *NonConstBB = 0;
1642 for (unsigned i = 0; i != NumPHIValues; ++i)
1643 if (!isa<Constant>(PN->getIncomingValue(i))) {
1644 if (NonConstBB) return 0; // More than one non-const value.
1645 NonConstBB = PN->getIncomingBlock(i);
1646
1647 // If the incoming non-constant value is in I's block, we have an infinite
1648 // loop.
1649 if (NonConstBB == I.getParent())
1650 return 0;
1651 }
1652
1653 // If there is exactly one non-constant value, we can insert a copy of the
1654 // operation in that block. However, if this is a critical edge, we would be
1655 // inserting the computation one some other paths (e.g. inside a loop). Only
1656 // do this if the pred block is unconditionally branching into the phi block.
1657 if (NonConstBB) {
1658 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659 if (!BI || !BI->isUnconditional()) return 0;
1660 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001661
1662 // Okay, we can do the transformation: create the new PHI node.
1663 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001665 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001666 InsertNewInstBefore(NewPN, *PN);
1667
1668 // Next, add all of the operands to the PHI.
1669 if (I.getNumOperands() == 2) {
1670 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001671 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001672 Value *InV;
1673 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001674 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1675 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1676 else
1677 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001678 } else {
1679 assert(PN->getIncomingBlock(i) == NonConstBB);
1680 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1681 InV = BinaryOperator::create(BO->getOpcode(),
1682 PN->getIncomingValue(i), C, "phitmp",
1683 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001684 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685 InV = CmpInst::create(CI->getOpcode(),
1686 CI->getPredicate(),
1687 PN->getIncomingValue(i), C, "phitmp",
1688 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001689 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1690 InV = new ShiftInst(SI->getOpcode(),
1691 PN->getIncomingValue(i), C, "phitmp",
1692 NonConstBB->getTerminator());
1693 else
1694 assert(0 && "Unknown binop!");
1695
1696 WorkList.push_back(cast<Instruction>(InV));
1697 }
1698 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001699 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001700 } else {
1701 CastInst *CI = cast<CastInst>(&I);
1702 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001703 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001704 Value *InV;
1705 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001706 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001707 } else {
1708 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001709 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1710 I.getType(), "phitmp",
1711 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001712 WorkList.push_back(cast<Instruction>(InV));
1713 }
1714 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001715 }
1716 }
1717 return ReplaceInstUsesWith(I, NewPN);
1718}
1719
Chris Lattner113f4f42002-06-25 16:13:24 +00001720Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001721 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001722 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001723
Chris Lattnercf4a9962004-04-10 22:01:55 +00001724 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001725 // X + undef -> undef
1726 if (isa<UndefValue>(RHS))
1727 return ReplaceInstUsesWith(I, RHS);
1728
Chris Lattnercf4a9962004-04-10 22:01:55 +00001729 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001730 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001731 if (RHSC->isNullValue())
1732 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001733 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1734 if (CFP->isExactlyValue(-0.0))
1735 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001736 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001737
Chris Lattnercf4a9962004-04-10 22:01:55 +00001738 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001739 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001740 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001741 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001742 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001743
1744 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1745 // (X & 254)+1 -> (X&254)|1
1746 uint64_t KnownZero, KnownOne;
1747 if (!isa<PackedType>(I.getType()) &&
Chris Lattner03c49532007-01-15 02:27:26 +00001748 SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001749 KnownZero, KnownOne))
1750 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001751 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001752
1753 if (isa<PHINode>(LHS))
1754 if (Instruction *NV = FoldOpIntoPhi(I))
1755 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001756
Chris Lattner330628a2006-01-06 17:59:59 +00001757 ConstantInt *XorRHS = 0;
1758 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001759 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1760 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1761 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1762 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1763
1764 uint64_t C0080Val = 1ULL << 31;
1765 int64_t CFF80Val = -C0080Val;
1766 unsigned Size = 32;
1767 do {
1768 if (TySizeBits > Size) {
1769 bool Found = false;
1770 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1771 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1772 if (RHSSExt == CFF80Val) {
1773 if (XorRHS->getZExtValue() == C0080Val)
1774 Found = true;
1775 } else if (RHSZExt == C0080Val) {
1776 if (XorRHS->getSExtValue() == CFF80Val)
1777 Found = true;
1778 }
1779 if (Found) {
1780 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001781 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001782 Mask <<= 64-(TySizeBits-Size);
Chris Lattner03c49532007-01-15 02:27:26 +00001783 Mask &= XorLHS->getType()->getIntegerTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001784 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001785 Size = 0; // Not a sign ext, but can't be any others either.
1786 goto FoundSExt;
1787 }
1788 }
1789 Size >>= 1;
1790 C0080Val >>= Size;
1791 CFF80Val >>= Size;
1792 } while (Size >= 8);
1793
1794FoundSExt:
1795 const Type *MiddleType = 0;
1796 switch (Size) {
1797 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001798 case 32: MiddleType = Type::Int32Ty; break;
1799 case 16: MiddleType = Type::Int16Ty; break;
1800 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001801 }
1802 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001803 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001804 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001805 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001806 }
1807 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001808 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001809
Chris Lattnerb8b97502003-08-13 19:01:45 +00001810 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001811 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001812 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001813
1814 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1815 if (RHSI->getOpcode() == Instruction::Sub)
1816 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1817 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1818 }
1819 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1820 if (LHSI->getOpcode() == Instruction::Sub)
1821 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1822 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1823 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001824 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001825
Chris Lattner147e9752002-05-08 22:46:53 +00001826 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001827 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001828 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001829
1830 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001831 if (!isa<Constant>(RHS))
1832 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001833 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001834
Misha Brukmanb1c93172005-04-21 23:48:37 +00001835
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001836 ConstantInt *C2;
1837 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1838 if (X == RHS) // X*C + X --> X * (C+1)
1839 return BinaryOperator::createMul(RHS, AddOne(C2));
1840
1841 // X*C1 + X*C2 --> X * (C1+C2)
1842 ConstantInt *C1;
1843 if (X == dyn_castFoldableMul(RHS, C1))
1844 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001845 }
1846
1847 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001848 if (dyn_castFoldableMul(RHS, C2) == LHS)
1849 return BinaryOperator::createMul(LHS, AddOne(C2));
1850
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001851 // X + ~X --> -1 since ~X = -X-1
1852 if (dyn_castNotVal(LHS) == RHS ||
1853 dyn_castNotVal(RHS) == LHS)
1854 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1855
Chris Lattner57c8d992003-02-18 19:57:07 +00001856
Chris Lattnerb8b97502003-08-13 19:01:45 +00001857 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001858 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001859 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1860 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001861
Chris Lattnerb9cde762003-10-02 15:11:26 +00001862 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001863 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001864 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1865 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1866 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001867 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001868
Chris Lattnerbff91d92004-10-08 05:07:56 +00001869 // (X & FF00) + xx00 -> (X+xx00) & FF00
1870 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1871 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1872 if (Anded == CRHS) {
1873 // See if all bits from the first bit set in the Add RHS up are included
1874 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001875 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001876
1877 // Form a mask of all bits from the lowest bit added through the top.
1878 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner03c49532007-01-15 02:27:26 +00001879 AddRHSHighBits &= C2->getType()->getIntegerTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001880
1881 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001882 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001883
Chris Lattnerbff91d92004-10-08 05:07:56 +00001884 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1885 // Okay, the xform is safe. Insert the new add pronto.
1886 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1887 LHS->getName()), I);
1888 return BinaryOperator::createAnd(NewAdd, C2);
1889 }
1890 }
1891 }
1892
Chris Lattnerd4252a72004-07-30 07:50:03 +00001893 // Try to fold constant add into select arguments.
1894 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001895 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001896 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001897 }
1898
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001899 // add (cast *A to intptrtype) B ->
1900 // cast (GEP (cast *A to sbyte*) B) ->
1901 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001902 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001903 CastInst *CI = dyn_cast<CastInst>(LHS);
1904 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001905 if (!CI) {
1906 CI = dyn_cast<CastInst>(RHS);
1907 Other = LHS;
1908 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001909 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001910 (CI->getType()->getPrimitiveSizeInBits() ==
1911 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001912 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001913 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001914 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001915 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001916 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001917 }
1918 }
1919
Chris Lattner113f4f42002-06-25 16:13:24 +00001920 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001921}
1922
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001923// isSignBit - Return true if the value represented by the constant only has the
1924// highest order bit set.
1925static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001926 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001927 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001928}
1929
Chris Lattner113f4f42002-06-25 16:13:24 +00001930Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001932
Chris Lattnere6794492002-08-12 21:17:25 +00001933 if (Op0 == Op1) // sub X, X -> 0
1934 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001935
Chris Lattnere6794492002-08-12 21:17:25 +00001936 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001937 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001938 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001939
Chris Lattner81a7a232004-10-16 18:11:37 +00001940 if (isa<UndefValue>(Op0))
1941 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1942 if (isa<UndefValue>(Op1))
1943 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1944
Chris Lattner8f2f5982003-11-05 01:06:05 +00001945 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1946 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001947 if (C->isAllOnesValue())
1948 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001949
Chris Lattner8f2f5982003-11-05 01:06:05 +00001950 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001951 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001952 if (match(Op1, m_Not(m_Value(X))))
1953 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001954 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001955 // -(X >>u 31) -> (X >>s 31)
1956 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001957 if (C->isNullValue()) {
Chris Lattner27df1db2007-01-15 07:02:54 +00001958 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001959 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001960 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001961 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 if (CU->getZExtValue() ==
1963 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001964 // Ok, the transformation is safe. Insert AShr.
Chris Lattner27df1db2007-01-15 07:02:54 +00001965 return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
Reid Spencer193df252006-12-24 00:40:59 +00001966 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001967 }
1968 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001969 }
1970 else if (SI->getOpcode() == Instruction::AShr) {
1971 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1972 // Check to see if we are shifting out everything but the sign bit.
1973 if (CU->getZExtValue() ==
1974 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00001975 // Ok, the transformation is safe. Insert LShr.
1976 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
1977 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001978 }
1979 }
1980 }
Chris Lattner022167f2004-03-13 00:11:49 +00001981 }
Chris Lattner183b3362004-04-09 19:05:30 +00001982
1983 // Try to fold constant sub into select arguments.
1984 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001986 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001987
1988 if (isa<PHINode>(Op0))
1989 if (Instruction *NV = FoldOpIntoPhi(I))
1990 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001991 }
1992
Chris Lattnera9be4492005-04-07 16:15:25 +00001993 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1994 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001995 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001996 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001997 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001998 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002000 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2001 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2002 // C1-(X+C2) --> (C1-C2)-X
2003 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2004 Op1I->getOperand(0));
2005 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002006 }
2007
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002008 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002009 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2010 // is not used by anyone else...
2011 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002012 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002013 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002014 // Swap the two operands of the subexpr...
2015 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2016 Op1I->setOperand(0, IIOp1);
2017 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002018
Chris Lattner3082c5a2003-02-18 19:28:33 +00002019 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002020 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 }
2022
2023 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024 //
2025 if (Op1I->getOpcode() == Instruction::And &&
2026 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2027 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2028
Chris Lattner396dbfe2004-06-09 05:08:07 +00002029 Value *NewNot =
2030 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002031 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002032 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002033
Reid Spencer3c514952006-10-16 23:08:08 +00002034 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002035 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002036 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002037 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002038 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002039 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002040 ConstantExpr::getNeg(DivRHS));
2041
Chris Lattner57c8d992003-02-18 19:57:07 +00002042 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002043 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002044 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002045 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002046 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002047 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002048 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002049 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002050 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051
Chris Lattner7a002fe2006-12-02 00:13:08 +00002052 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2054 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002055 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2056 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2057 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2058 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002059 } else if (Op0I->getOpcode() == Instruction::Sub) {
2060 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2061 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002062 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002063
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002064 ConstantInt *C1;
2065 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2066 if (X == Op1) { // X*C - X --> X * (C-1)
2067 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2068 return BinaryOperator::createMul(Op1, CP1);
2069 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002070
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002071 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2072 if (X == dyn_castFoldableMul(Op1, C2))
2073 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2074 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002075 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002076}
2077
Reid Spencer266e42b2006-12-23 06:05:41 +00002078/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002079/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002080static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2081 switch (pred) {
2082 case ICmpInst::ICMP_SLT:
2083 // True if LHS s< RHS and RHS == 0
2084 return RHS->isNullValue();
2085 case ICmpInst::ICMP_SLE:
2086 // True if LHS s<= RHS and RHS == -1
2087 return RHS->isAllOnesValue();
2088 case ICmpInst::ICMP_UGE:
2089 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2090 return RHS->getZExtValue() == (1ULL <<
2091 (RHS->getType()->getPrimitiveSizeInBits()-1));
2092 case ICmpInst::ICMP_UGT:
2093 // True if LHS u> RHS and RHS == high-bit-mask - 1
2094 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002095 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002096 default:
2097 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002098 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002099}
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002102 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002103 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002104
Chris Lattner81a7a232004-10-16 18:11:37 +00002105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
Chris Lattnere6794492002-08-12 21:17:25 +00002108 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002111
2112 // ((X << C1)*C2) == (X * (C2 << C1))
2113 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114 if (SI->getOpcode() == Instruction::Shl)
2115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002116 return BinaryOperator::createMul(SI->getOperand(0),
2117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118
Chris Lattnercce81be2003-09-11 22:24:54 +00002119 if (CI->isNullValue())
2120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2121 if (CI->equalsInt(1)) // X * 1 == X
2122 return ReplaceInstUsesWith(I, Op0);
2123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002124 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002125
Reid Spencere0fc4df2006-10-20 07:07:24 +00002126 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002127 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2128 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002129 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002130 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002131 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002132 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 if (Op1F->isNullValue())
2134 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002135
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2137 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138 if (Op1F->getValue() == 1.0)
2139 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2140 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002141
2142 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144 isa<ConstantInt>(Op0I->getOperand(1))) {
2145 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147 Op1, "tmp");
2148 InsertNewInstBefore(Add, I);
2149 Value *C1C2 = ConstantExpr::getMul(Op1,
2150 cast<Constant>(Op0I->getOperand(1)));
2151 return BinaryOperator::createAdd(Add, C1C2);
2152
2153 }
Chris Lattner183b3362004-04-09 19:05:30 +00002154
2155 // Try to fold constant mul into select arguments.
2156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002158 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002159
2160 if (isa<PHINode>(Op0))
2161 if (Instruction *NV = FoldOpIntoPhi(I))
2162 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002163 }
2164
Chris Lattner934a64cf2003-03-10 23:23:04 +00002165 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2166 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002167 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002168
Chris Lattner2635b522004-02-23 05:39:21 +00002169 // If one of the operands of the multiply is a cast from a boolean value, then
2170 // we know the bool is either zero or one, so this is a 'masking' multiply.
2171 // See if we can simplify things based on how the boolean was originally
2172 // formed.
2173 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002174 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002175 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002176 BoolCast = CI;
2177 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002178 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002179 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002180 BoolCast = CI;
2181 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002182 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002183 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184 const Type *SCOpTy = SCIOp0->getType();
2185
Reid Spencer266e42b2006-12-23 06:05:41 +00002186 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002187 // multiply into a shift/and combination.
2188 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002189 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002190 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002191 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002192 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002193 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002194 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002195 BoolCast->getOperand(0)->getName()+
2196 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002197
2198 // If the multiply type is not the same as the source type, sign extend
2199 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002200 if (I.getType() != V->getType()) {
2201 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2202 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2203 Instruction::CastOps opcode =
2204 (SrcBits == DstBits ? Instruction::BitCast :
2205 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2206 V = InsertCastBefore(opcode, V, I.getType(), I);
2207 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002208
Chris Lattner2635b522004-02-23 05:39:21 +00002209 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002210 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002211 }
2212 }
2213 }
2214
Chris Lattner113f4f42002-06-25 16:13:24 +00002215 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002216}
2217
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002218/// This function implements the transforms on div instructions that work
2219/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2220/// used by the visitors to those instructions.
2221/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002222Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002223 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002224
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002225 // undef / X -> 0
2226 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002227 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002228
2229 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002230 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002231 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002232
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002233 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002234 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2235 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002236 // same basic block, then we replace the select with Y, and the condition
2237 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002238 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002239 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002240 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2241 if (ST->isNullValue()) {
2242 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2243 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002244 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002245 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2246 I.setOperand(1, SI->getOperand(2));
2247 else
2248 UpdateValueUsesWith(SI, SI->getOperand(2));
2249 return &I;
2250 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002251
Chris Lattnerd79dc792006-09-09 20:26:32 +00002252 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2253 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2254 if (ST->isNullValue()) {
2255 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2256 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002257 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002258 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2259 I.setOperand(1, SI->getOperand(1));
2260 else
2261 UpdateValueUsesWith(SI, SI->getOperand(1));
2262 return &I;
2263 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002264 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002265
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266 return 0;
2267}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002268
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002269/// This function implements the transforms common to both integer division
2270/// instructions (udiv and sdiv). It is called by the visitors to those integer
2271/// division instructions.
2272/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002273Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2275
2276 if (Instruction *Common = commonDivTransforms(I))
2277 return Common;
2278
2279 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2280 // div X, 1 == X
2281 if (RHS->equalsInt(1))
2282 return ReplaceInstUsesWith(I, Op0);
2283
2284 // (X / C1) / C2 -> X / (C1*C2)
2285 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2286 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2287 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2288 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2289 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002290 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002291
2292 if (!RHS->isNullValue()) { // avoid X udiv 0
2293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2295 return R;
2296 if (isa<PHINode>(Op0))
2297 if (Instruction *NV = FoldOpIntoPhi(I))
2298 return NV;
2299 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002300 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002301
Chris Lattner3082c5a2003-02-18 19:28:33 +00002302 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002303 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002304 if (LHS->equalsInt(0))
2305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2306
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002307 return 0;
2308}
2309
2310Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2312
2313 // Handle the integer div common cases
2314 if (Instruction *Common = commonIDivTransforms(I))
2315 return Common;
2316
2317 // X udiv C^2 -> X >> C
2318 // Check to see if this is an unsigned division with an exact power of 2,
2319 // if so, convert to a right shift.
2320 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2321 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2322 if (isPowerOf2_64(Val)) {
2323 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002324 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002325 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002326 }
2327 }
2328
2329 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2330 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2331 if (RHSI->getOpcode() == Instruction::Shl &&
2332 isa<ConstantInt>(RHSI->getOperand(0))) {
2333 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2334 if (isPowerOf2_64(C1)) {
2335 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002336 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002337 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002338 Constant *C2V = ConstantInt::get(NTy, C2);
2339 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002340 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002341 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002342 }
2343 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002344 }
2345
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002346 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2347 // where C1&C2 are powers of two.
2348 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2349 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2350 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2351 if (!STO->isNullValue() && !STO->isNullValue()) {
2352 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2353 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2354 // Compute the shift amounts
2355 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002356 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002357 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002358 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002359 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002360 TSI = InsertNewInstBefore(TSI, I);
2361
2362 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002363 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002364 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002365 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366 FSI = InsertNewInstBefore(FSI, I);
2367
2368 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002369 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002370 }
2371 }
2372 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002373 return 0;
2374}
2375
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002376Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378
2379 // Handle the integer div common cases
2380 if (Instruction *Common = commonIDivTransforms(I))
2381 return Common;
2382
2383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2384 // sdiv X, -1 == -X
2385 if (RHS->isAllOnesValue())
2386 return BinaryOperator::createNeg(Op0);
2387
2388 // -X/C -> X/-C
2389 if (Value *LHSNeg = dyn_castNegVal(Op0))
2390 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2391 }
2392
2393 // If the sign bits of both operands are zero (i.e. we can prove they are
2394 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002395 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002396 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2397 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2398 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2399 }
2400 }
2401
2402 return 0;
2403}
2404
2405Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2406 return commonDivTransforms(I);
2407}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002408
Chris Lattner85dda9a2006-03-02 06:50:58 +00002409/// GetFactor - If we can prove that the specified value is at least a multiple
2410/// of some factor, return that factor.
2411static Constant *GetFactor(Value *V) {
2412 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2413 return CI;
2414
2415 // Unless we can be tricky, we know this is a multiple of 1.
2416 Constant *Result = ConstantInt::get(V->getType(), 1);
2417
2418 Instruction *I = dyn_cast<Instruction>(V);
2419 if (!I) return Result;
2420
2421 if (I->getOpcode() == Instruction::Mul) {
2422 // Handle multiplies by a constant, etc.
2423 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2424 GetFactor(I->getOperand(1)));
2425 } else if (I->getOpcode() == Instruction::Shl) {
2426 // (X<<C) -> X * (1 << C)
2427 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2428 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2429 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2430 }
2431 } else if (I->getOpcode() == Instruction::And) {
2432 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2433 // X & 0xFFF0 is known to be a multiple of 16.
2434 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2435 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2436 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002437 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002438 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002439 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002440 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002441 if (!CI->isIntegerCast())
2442 return Result;
2443 Value *Op = CI->getOperand(0);
2444 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002445 }
2446 return Result;
2447}
2448
Reid Spencer7eb55b32006-11-02 01:53:59 +00002449/// This function implements the transforms on rem instructions that work
2450/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2451/// is used by the visitors to those instructions.
2452/// @brief Transforms common to all three rem instructions
2453Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002454 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002455
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002456 // 0 % X == 0, we don't need to preserve faults!
2457 if (Constant *LHS = dyn_cast<Constant>(Op0))
2458 if (LHS->isNullValue())
2459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461 if (isa<UndefValue>(Op0)) // undef % X -> 0
2462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463 if (isa<UndefValue>(Op1))
2464 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002465
2466 // Handle cases involving: rem X, (select Cond, Y, Z)
2467 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2468 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2469 // the same basic block, then we replace the select with Y, and the
2470 // condition of the select with false (if the cond value is in the same
2471 // BB). If the select has uses other than the div, this allows them to be
2472 // simplified also.
2473 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2474 if (ST->isNullValue()) {
2475 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2476 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002477 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002478 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2479 I.setOperand(1, SI->getOperand(2));
2480 else
2481 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002482 return &I;
2483 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002484 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2485 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2486 if (ST->isNullValue()) {
2487 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2488 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002489 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002490 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2491 I.setOperand(1, SI->getOperand(1));
2492 else
2493 UpdateValueUsesWith(SI, SI->getOperand(1));
2494 return &I;
2495 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002496 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002497
Reid Spencer7eb55b32006-11-02 01:53:59 +00002498 return 0;
2499}
2500
2501/// This function implements the transforms common to both integer remainder
2502/// instructions (urem and srem). It is called by the visitors to those integer
2503/// remainder instructions.
2504/// @brief Common integer remainder transforms
2505Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508 if (Instruction *common = commonRemTransforms(I))
2509 return common;
2510
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002511 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002512 // X % 0 == undef, we don't need to preserve faults!
2513 if (RHS->equalsInt(0))
2514 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2515
Chris Lattner3082c5a2003-02-18 19:28:33 +00002516 if (RHS->equalsInt(1)) // X % 1 == 0
2517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
Chris Lattnerb70f1412006-02-28 05:49:21 +00002519 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2520 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2521 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2522 return R;
2523 } else if (isa<PHINode>(Op0I)) {
2524 if (Instruction *NV = FoldOpIntoPhi(I))
2525 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002526 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002527 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2528 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002529 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002530 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002531 }
2532
Reid Spencer7eb55b32006-11-02 01:53:59 +00002533 return 0;
2534}
2535
2536Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539 if (Instruction *common = commonIRemTransforms(I))
2540 return common;
2541
2542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2543 // X urem C^2 -> X and C
2544 // Check to see if this is an unsigned remainder with an exact power of 2,
2545 // if so, convert to a bitwise and.
2546 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2547 if (isPowerOf2_64(C->getZExtValue()))
2548 return BinaryOperator::createAnd(Op0, SubOne(C));
2549 }
2550
Chris Lattner2e90b732006-02-05 07:54:04 +00002551 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002552 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2553 if (RHSI->getOpcode() == Instruction::Shl &&
2554 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002555 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002556 if (isPowerOf2_64(C1)) {
2557 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2558 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2559 "tmp"), I);
2560 return BinaryOperator::createAnd(Op0, Add);
2561 }
2562 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002563 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002564
Reid Spencer7eb55b32006-11-02 01:53:59 +00002565 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2566 // where C1&C2 are powers of two.
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2568 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2569 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2570 // STO == 0 and SFO == 0 handled above.
2571 if (isPowerOf2_64(STO->getZExtValue()) &&
2572 isPowerOf2_64(SFO->getZExtValue())) {
2573 Value *TrueAnd = InsertNewInstBefore(
2574 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2575 Value *FalseAnd = InsertNewInstBefore(
2576 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2577 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2578 }
2579 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002580 }
2581
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002582 return 0;
2583}
2584
Reid Spencer7eb55b32006-11-02 01:53:59 +00002585Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2586 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588 if (Instruction *common = commonIRemTransforms(I))
2589 return common;
2590
2591 if (Value *RHSNeg = dyn_castNegVal(Op1))
2592 if (!isa<ConstantInt>(RHSNeg) ||
2593 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2594 // X % -Y -> X % Y
2595 AddUsesToWorkList(I);
2596 I.setOperand(1, RHSNeg);
2597 return &I;
2598 }
2599
2600 // If the top bits of both operands are zero (i.e. we can prove they are
2601 // unsigned inputs), turn this into a urem.
2602 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2603 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2604 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2605 return BinaryOperator::createURem(Op0, Op1, I.getName());
2606 }
2607
2608 return 0;
2609}
2610
2611Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002612 return commonRemTransforms(I);
2613}
2614
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002615// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002616static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2617 if (isSigned) {
2618 // Calculate 0111111111..11111
2619 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2620 int64_t Val = INT64_MAX; // All ones
2621 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2622 return C->getSExtValue() == Val-1;
2623 }
Chris Lattner03c49532007-01-15 02:27:26 +00002624 return C->getZExtValue() == C->getType()->getIntegerTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002625}
2626
2627// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002628static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2629 if (isSigned) {
2630 // Calculate 1111111111000000000000
2631 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2632 int64_t Val = -1; // All ones
2633 Val <<= TypeBits-1; // Shift over to the right spot
2634 return C->getSExtValue() == Val+1;
2635 }
2636 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002637}
2638
Chris Lattner35167c32004-06-09 07:59:58 +00002639// isOneBitSet - Return true if there is exactly one bit set in the specified
2640// constant.
2641static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002642 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002643 return V && (V & (V-1)) == 0;
2644}
2645
Chris Lattner8fc5af42004-09-23 21:46:38 +00002646#if 0 // Currently unused
2647// isLowOnes - Return true if the constant is of the form 0+1+.
2648static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002649 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002650
2651 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002652 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002653
2654 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2655 return U && V && (U & V) == 0;
2656}
2657#endif
2658
2659// isHighOnes - Return true if the constant is of the form 1+0+.
2660// This is the same as lowones(~X).
2661static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002662 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002663 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002664
2665 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002666 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002667
2668 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2669 return U && V && (U & V) == 0;
2670}
2671
Reid Spencer266e42b2006-12-23 06:05:41 +00002672/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002673/// are carefully arranged to allow folding of expressions such as:
2674///
2675/// (A < B) | (A > B) --> (A != B)
2676///
Reid Spencer266e42b2006-12-23 06:05:41 +00002677/// Note that this is only valid if the first and second predicates have the
2678/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002679///
Reid Spencer266e42b2006-12-23 06:05:41 +00002680/// Three bits are used to represent the condition, as follows:
2681/// 0 A > B
2682/// 1 A == B
2683/// 2 A < B
2684///
2685/// <=> Value Definition
2686/// 000 0 Always false
2687/// 001 1 A > B
2688/// 010 2 A == B
2689/// 011 3 A >= B
2690/// 100 4 A < B
2691/// 101 5 A != B
2692/// 110 6 A <= B
2693/// 111 7 Always true
2694///
2695static unsigned getICmpCode(const ICmpInst *ICI) {
2696 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002697 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002698 case ICmpInst::ICMP_UGT: return 1; // 001
2699 case ICmpInst::ICMP_SGT: return 1; // 001
2700 case ICmpInst::ICMP_EQ: return 2; // 010
2701 case ICmpInst::ICMP_UGE: return 3; // 011
2702 case ICmpInst::ICMP_SGE: return 3; // 011
2703 case ICmpInst::ICMP_ULT: return 4; // 100
2704 case ICmpInst::ICMP_SLT: return 4; // 100
2705 case ICmpInst::ICMP_NE: return 5; // 101
2706 case ICmpInst::ICMP_ULE: return 6; // 110
2707 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002708 // True -> 7
2709 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002710 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002711 return 0;
2712 }
2713}
2714
Reid Spencer266e42b2006-12-23 06:05:41 +00002715/// getICmpValue - This is the complement of getICmpCode, which turns an
2716/// opcode and two operands into either a constant true or false, or a brand
2717/// new /// ICmp instruction. The sign is passed in to determine which kind
2718/// of predicate to use in new icmp instructions.
2719static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2720 switch (code) {
2721 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002722 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002723 case 1:
2724 if (sign)
2725 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2726 else
2727 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2728 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2729 case 3:
2730 if (sign)
2731 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2732 else
2733 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2734 case 4:
2735 if (sign)
2736 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2737 else
2738 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2739 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2740 case 6:
2741 if (sign)
2742 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2743 else
2744 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002745 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002746 }
2747}
2748
Reid Spencer266e42b2006-12-23 06:05:41 +00002749static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2750 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2751 (ICmpInst::isSignedPredicate(p1) &&
2752 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2753 (ICmpInst::isSignedPredicate(p2) &&
2754 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2755}
2756
2757namespace {
2758// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2759struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002760 InstCombiner &IC;
2761 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002762 ICmpInst::Predicate pred;
2763 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2764 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2765 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002766 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002767 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2768 if (PredicatesFoldable(pred, ICI->getPredicate()))
2769 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2770 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002771 return false;
2772 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002773 Instruction *apply(Instruction &Log) const {
2774 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2775 if (ICI->getOperand(0) != LHS) {
2776 assert(ICI->getOperand(1) == LHS);
2777 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002778 }
2779
Reid Spencer266e42b2006-12-23 06:05:41 +00002780 unsigned LHSCode = getICmpCode(ICI);
2781 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002782 unsigned Code;
2783 switch (Log.getOpcode()) {
2784 case Instruction::And: Code = LHSCode & RHSCode; break;
2785 case Instruction::Or: Code = LHSCode | RHSCode; break;
2786 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002787 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002788 }
2789
Reid Spencer266e42b2006-12-23 06:05:41 +00002790 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 if (Instruction *I = dyn_cast<Instruction>(RV))
2792 return I;
2793 // Otherwise, it's a constant boolean value...
2794 return IC.ReplaceInstUsesWith(Log, RV);
2795 }
2796};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002797} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002798
Chris Lattnerba1cb382003-09-19 17:17:26 +00002799// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2800// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2801// guaranteed to be either a shift instruction or a binary operator.
2802Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002803 ConstantInt *OpRHS,
2804 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002805 BinaryOperator &TheAnd) {
2806 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002807 Constant *Together = 0;
2808 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002809 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002810
Chris Lattnerba1cb382003-09-19 17:17:26 +00002811 switch (Op->getOpcode()) {
2812 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002813 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002814 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2815 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002816 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002817 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002818 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002819 }
2820 break;
2821 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002822 if (Together == AndRHS) // (X | C) & C --> C
2823 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002824
Chris Lattner86102b82005-01-01 16:22:27 +00002825 if (Op->hasOneUse() && Together != OpRHS) {
2826 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2827 std::string Op0Name = Op->getName(); Op->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2829 InsertNewInstBefore(Or, TheAnd);
2830 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002831 }
2832 break;
2833 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002834 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002835 // Adding a one to a single bit bit-field should be turned into an XOR
2836 // of the bit. First thing to check is to see if this AND is with a
2837 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002838 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002839
2840 // Clear bits that are not part of the constant.
Chris Lattner03c49532007-01-15 02:27:26 +00002841 AndRHSV &= AndRHS->getType()->getIntegerTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842
2843 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002844 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845 // Ok, at this point, we know that we are masking the result of the
2846 // ADD down to exactly one bit. If the constant we are adding has
2847 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002848 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002849
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 // Check to see if any bits below the one bit set in AndRHSV are set.
2851 if ((AddRHS & (AndRHSV-1)) == 0) {
2852 // If not, the only thing that can effect the output of the AND is
2853 // the bit specified by AndRHSV. If that bit is set, the effect of
2854 // the XOR is to toggle the bit. If it is clear, then the ADD has
2855 // no effect.
2856 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2857 TheAnd.setOperand(0, X);
2858 return &TheAnd;
2859 } else {
2860 std::string Name = Op->getName(); Op->setName("");
2861 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002862 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002863 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002864 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002865 }
2866 }
2867 }
2868 }
2869 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002870
2871 case Instruction::Shl: {
2872 // We know that the AND will not produce any of the bits shifted in, so if
2873 // the anded constant includes them, clear them now!
2874 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002875 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002876 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2877 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002878
Chris Lattner7e794272004-09-24 15:21:34 +00002879 if (CI == ShlMask) { // Masking out bits that the shift already masks
2880 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2881 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002882 TheAnd.setOperand(1, CI);
2883 return &TheAnd;
2884 }
2885 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002886 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002887 case Instruction::LShr:
2888 {
Chris Lattner2da29172003-09-19 19:05:02 +00002889 // We know that the AND will not produce any of the bits shifted in, so if
2890 // the anded constant includes them, clear them now! This only applies to
2891 // unsigned shifts, because a signed shr may bring in set bits!
2892 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002893 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002894 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2895 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002896
Reid Spencerfdff9382006-11-08 06:47:33 +00002897 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2898 return ReplaceInstUsesWith(TheAnd, Op);
2899 } else if (CI != AndRHS) {
2900 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2901 return &TheAnd;
2902 }
2903 break;
2904 }
2905 case Instruction::AShr:
2906 // Signed shr.
2907 // See if this is shifting in some sign extension, then masking it out
2908 // with an and.
2909 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002910 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002911 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002912 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2913 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002914 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002915 // Make the argument unsigned.
2916 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002917 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2918 OpRHS, Op->getName()), TheAnd);
2919 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002920 }
Chris Lattner2da29172003-09-19 19:05:02 +00002921 }
2922 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002923 }
2924 return 0;
2925}
2926
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002927
Chris Lattner6862fbd2004-09-29 17:40:11 +00002928/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2929/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002930/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2931/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002932/// insert new instructions.
2933Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002934 bool isSigned, bool Inside,
2935 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002936 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002937 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002938 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002939
Chris Lattner6862fbd2004-09-29 17:40:11 +00002940 if (Inside) {
2941 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002942 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002943
Reid Spencer266e42b2006-12-23 06:05:41 +00002944 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002945 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002946 ICmpInst::Predicate pred = (isSigned ?
2947 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2948 return new ICmpInst(pred, V, Hi);
2949 }
2950
2951 // Emit V-Lo <u Hi-Lo
2952 Constant *NegLo = ConstantExpr::getNeg(Lo);
2953 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002954 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002955 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2956 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002957 }
2958
2959 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002960 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961
Reid Spencer266e42b2006-12-23 06:05:41 +00002962 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002963 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002964 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002965 ICmpInst::Predicate pred = (isSigned ?
2966 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2967 return new ICmpInst(pred, V, Hi);
2968 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00002969
Reid Spencer266e42b2006-12-23 06:05:41 +00002970 // Emit V-Lo > Hi-1-Lo
2971 Constant *NegLo = ConstantExpr::getNeg(Lo);
2972 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002973 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002974 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2975 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002976}
2977
Chris Lattnerb4b25302005-09-18 07:22:02 +00002978// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2979// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2980// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2981// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002982static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002983 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002984 if (!isShiftedMask_64(V)) return false;
2985
2986 // look for the first zero bit after the run of ones
2987 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2988 // look for the first non-zero bit
2989 ME = 64-CountLeadingZeros_64(V);
2990 return true;
2991}
2992
2993
2994
2995/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2996/// where isSub determines whether the operator is a sub. If we can fold one of
2997/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002998///
2999/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3000/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3001/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3002///
3003/// return (A +/- B).
3004///
3005Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003006 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003007 Instruction &I) {
3008 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3009 if (!LHSI || LHSI->getNumOperands() != 2 ||
3010 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3011
3012 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3013
3014 switch (LHSI->getOpcode()) {
3015 default: return 0;
3016 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003017 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3018 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003019 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003020 break;
3021
3022 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3023 // part, we don't need any explicit masks to take them out of A. If that
3024 // is all N is, ignore it.
3025 unsigned MB, ME;
3026 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner03c49532007-01-15 02:27:26 +00003027 uint64_t Mask = RHS->getType()->getIntegerTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003028 Mask >>= 64-MB+1;
3029 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003030 break;
3031 }
3032 }
Chris Lattneraf517572005-09-18 04:24:45 +00003033 return 0;
3034 case Instruction::Or:
3035 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003036 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003037 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003038 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003039 break;
3040 return 0;
3041 }
3042
3043 Instruction *New;
3044 if (isSub)
3045 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3046 else
3047 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3048 return InsertNewInstBefore(New, I);
3049}
3050
Chris Lattner113f4f42002-06-25 16:13:24 +00003051Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003052 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003054
Chris Lattner81a7a232004-10-16 18:11:37 +00003055 if (isa<UndefValue>(Op1)) // X & undef -> 0
3056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3057
Chris Lattner86102b82005-01-01 16:22:27 +00003058 // and X, X = X
3059 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003060 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003061
Chris Lattner5b2edb12006-02-12 08:02:11 +00003062 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003063 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003064 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003065 if (!isa<PackedType>(I.getType()) &&
Chris Lattner03c49532007-01-15 02:27:26 +00003066 SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003067 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003068 return &I;
3069
Zhou Sheng75b871f2007-01-11 12:24:14 +00003070 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003071 uint64_t AndRHSMask = AndRHS->getZExtValue();
Chris Lattner03c49532007-01-15 02:27:26 +00003072 uint64_t TypeMask = Op0->getType()->getIntegerTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003073 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003074
Chris Lattnerba1cb382003-09-19 17:17:26 +00003075 // Optimize a variety of ((val OP C1) & C2) combinations...
3076 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3077 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003078 Value *Op0LHS = Op0I->getOperand(0);
3079 Value *Op0RHS = Op0I->getOperand(1);
3080 switch (Op0I->getOpcode()) {
3081 case Instruction::Xor:
3082 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003083 // If the mask is only needed on one incoming arm, push it up.
3084 if (Op0I->hasOneUse()) {
3085 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3086 // Not masking anything out for the LHS, move to RHS.
3087 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3088 Op0RHS->getName()+".masked");
3089 InsertNewInstBefore(NewRHS, I);
3090 return BinaryOperator::create(
3091 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003092 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003093 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003094 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3095 // Not masking anything out for the RHS, move to LHS.
3096 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3097 Op0LHS->getName()+".masked");
3098 InsertNewInstBefore(NewLHS, I);
3099 return BinaryOperator::create(
3100 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3101 }
3102 }
3103
Chris Lattner86102b82005-01-01 16:22:27 +00003104 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003105 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003106 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3107 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3108 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3109 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3110 return BinaryOperator::createAnd(V, AndRHS);
3111 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3112 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003113 break;
3114
3115 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003116 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3117 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3118 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3119 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3120 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003121 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003122 }
3123
Chris Lattner16464b32003-07-23 19:25:52 +00003124 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003125 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003126 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003127 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003128 // If this is an integer truncation or change from signed-to-unsigned, and
3129 // if the source is an and/or with immediate, transform it. This
3130 // frequently occurs for bitfield accesses.
3131 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003132 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003133 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003134 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003135 if (CastOp->getOpcode() == Instruction::And) {
3136 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003137 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3138 // This will fold the two constants together, which may allow
3139 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003140 Instruction *NewCast = CastInst::createTruncOrBitCast(
3141 CastOp->getOperand(0), I.getType(),
3142 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003143 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003144 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003145 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003146 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003147 return BinaryOperator::createAnd(NewCast, C3);
3148 } else if (CastOp->getOpcode() == Instruction::Or) {
3149 // Change: and (cast (or X, C1) to T), C2
3150 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003151 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003152 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3153 return ReplaceInstUsesWith(I, AndRHS);
3154 }
3155 }
Chris Lattner33217db2003-07-23 19:36:21 +00003156 }
Chris Lattner183b3362004-04-09 19:05:30 +00003157
3158 // Try to fold constant and into select arguments.
3159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003161 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003162 if (isa<PHINode>(Op0))
3163 if (Instruction *NV = FoldOpIntoPhi(I))
3164 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003165 }
3166
Chris Lattnerbb74e222003-03-10 23:06:50 +00003167 Value *Op0NotVal = dyn_castNotVal(Op0);
3168 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003169
Chris Lattner023a4832004-06-18 06:07:51 +00003170 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3171 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3172
Misha Brukman9c003d82004-07-30 12:50:08 +00003173 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003174 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003175 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3176 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003177 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003178 return BinaryOperator::createNot(Or);
3179 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003180
3181 {
3182 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003183 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3184 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3185 return ReplaceInstUsesWith(I, Op1);
3186 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3187 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3188 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003189
3190 if (Op0->hasOneUse() &&
3191 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3192 if (A == Op1) { // (A^B)&A -> A&(A^B)
3193 I.swapOperands(); // Simplify below
3194 std::swap(Op0, Op1);
3195 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3196 cast<BinaryOperator>(Op0)->swapOperands();
3197 I.swapOperands(); // Simplify below
3198 std::swap(Op0, Op1);
3199 }
3200 }
3201 if (Op1->hasOneUse() &&
3202 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3203 if (B == Op0) { // B&(A^B) -> B&(B^A)
3204 cast<BinaryOperator>(Op1)->swapOperands();
3205 std::swap(A, B);
3206 }
3207 if (A == Op0) { // A&(A^B) -> A & ~B
3208 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3209 InsertNewInstBefore(NotB, I);
3210 return BinaryOperator::createAnd(A, NotB);
3211 }
3212 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003213 }
3214
Reid Spencer266e42b2006-12-23 06:05:41 +00003215 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3216 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3217 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003218 return R;
3219
Chris Lattner623826c2004-09-28 21:48:02 +00003220 Value *LHSVal, *RHSVal;
3221 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003222 ICmpInst::Predicate LHSCC, RHSCC;
3223 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3224 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3225 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3226 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3227 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3228 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3229 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3230 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003231 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003232 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3233 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3234 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3235 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003236 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003237 std::swap(LHS, RHS);
3238 std::swap(LHSCst, RHSCst);
3239 std::swap(LHSCC, RHSCC);
3240 }
3241
Reid Spencer266e42b2006-12-23 06:05:41 +00003242 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003243 // comparing a value against two constants and and'ing the result
3244 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003245 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3246 // (from the FoldICmpLogical check above), that the two constants
3247 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003248 assert(LHSCst != RHSCst && "Compares not folded above?");
3249
3250 switch (LHSCC) {
3251 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003252 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003253 switch (RHSCC) {
3254 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003255 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3256 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3257 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003258 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003259 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3260 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3261 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003262 return ReplaceInstUsesWith(I, LHS);
3263 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003264 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003265 switch (RHSCC) {
3266 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003267 case ICmpInst::ICMP_ULT:
3268 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3269 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3270 break; // (X != 13 & X u< 15) -> no change
3271 case ICmpInst::ICMP_SLT:
3272 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3273 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3274 break; // (X != 13 & X s< 15) -> no change
3275 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3276 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3277 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003278 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003279 case ICmpInst::ICMP_NE:
3280 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003281 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3282 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3283 LHSVal->getName()+".off");
3284 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003285 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003286 }
3287 break; // (X != 13 & X != 15) -> no change
3288 }
3289 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003290 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003291 switch (RHSCC) {
3292 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003293 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3294 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003295 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003296 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3297 break;
3298 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3299 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003300 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003301 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3302 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003303 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003304 break;
3305 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003306 switch (RHSCC) {
3307 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003308 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3309 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003310 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003311 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3312 break;
3313 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3314 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003315 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003316 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3317 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003318 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003319 break;
3320 case ICmpInst::ICMP_UGT:
3321 switch (RHSCC) {
3322 default: assert(0 && "Unknown integer condition code!");
3323 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3324 return ReplaceInstUsesWith(I, LHS);
3325 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3326 return ReplaceInstUsesWith(I, RHS);
3327 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3328 break;
3329 case ICmpInst::ICMP_NE:
3330 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3331 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3332 break; // (X u> 13 & X != 15) -> no change
3333 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3334 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3335 true, I);
3336 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3337 break;
3338 }
3339 break;
3340 case ICmpInst::ICMP_SGT:
3341 switch (RHSCC) {
3342 default: assert(0 && "Unknown integer condition code!");
3343 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3344 return ReplaceInstUsesWith(I, LHS);
3345 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3346 return ReplaceInstUsesWith(I, RHS);
3347 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3348 break;
3349 case ICmpInst::ICMP_NE:
3350 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3351 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3352 break; // (X s> 13 & X != 15) -> no change
3353 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3354 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3355 true, I);
3356 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3357 break;
3358 }
3359 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003360 }
3361 }
3362 }
3363
Chris Lattner3af10532006-05-05 06:39:07 +00003364 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003365 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3366 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3367 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3368 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003369 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003370 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003371 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3372 I.getType(), TD) &&
3373 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3374 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003375 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3376 Op1C->getOperand(0),
3377 I.getName());
3378 InsertNewInstBefore(NewOp, I);
3379 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3380 }
Chris Lattner3af10532006-05-05 06:39:07 +00003381 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003382
3383 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3384 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3385 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3386 if (SI0->getOpcode() == SI1->getOpcode() &&
3387 SI0->getOperand(1) == SI1->getOperand(1) &&
3388 (SI0->hasOneUse() || SI1->hasOneUse())) {
3389 Instruction *NewOp =
3390 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3391 SI1->getOperand(0),
3392 SI0->getName()), I);
3393 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3394 }
Chris Lattner3af10532006-05-05 06:39:07 +00003395 }
3396
Chris Lattner113f4f42002-06-25 16:13:24 +00003397 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003398}
3399
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003400/// CollectBSwapParts - Look to see if the specified value defines a single byte
3401/// in the result. If it does, and if the specified byte hasn't been filled in
3402/// yet, fill it in and return false.
3403static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3404 Instruction *I = dyn_cast<Instruction>(V);
3405 if (I == 0) return true;
3406
3407 // If this is an or instruction, it is an inner node of the bswap.
3408 if (I->getOpcode() == Instruction::Or)
3409 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3410 CollectBSwapParts(I->getOperand(1), ByteValues);
3411
3412 // If this is a shift by a constant int, and it is "24", then its operand
3413 // defines a byte. We only handle unsigned types here.
3414 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3415 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003416 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003417 8*(ByteValues.size()-1))
3418 return true;
3419
3420 unsigned DestNo;
3421 if (I->getOpcode() == Instruction::Shl) {
3422 // X << 24 defines the top byte with the lowest of the input bytes.
3423 DestNo = ByteValues.size()-1;
3424 } else {
3425 // X >>u 24 defines the low byte with the highest of the input bytes.
3426 DestNo = 0;
3427 }
3428
3429 // If the destination byte value is already defined, the values are or'd
3430 // together, which isn't a bswap (unless it's an or of the same bits).
3431 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3432 return true;
3433 ByteValues[DestNo] = I->getOperand(0);
3434 return false;
3435 }
3436
3437 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3438 // don't have this.
3439 Value *Shift = 0, *ShiftLHS = 0;
3440 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3441 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3442 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3443 return true;
3444 Instruction *SI = cast<Instruction>(Shift);
3445
3446 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003447 if (ShiftAmt->getZExtValue() & 7 ||
3448 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003449 return true;
3450
3451 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3452 unsigned DestByte;
3453 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003454 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003455 break;
3456 // Unknown mask for bswap.
3457 if (DestByte == ByteValues.size()) return true;
3458
Reid Spencere0fc4df2006-10-20 07:07:24 +00003459 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003460 unsigned SrcByte;
3461 if (SI->getOpcode() == Instruction::Shl)
3462 SrcByte = DestByte - ShiftBytes;
3463 else
3464 SrcByte = DestByte + ShiftBytes;
3465
3466 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3467 if (SrcByte != ByteValues.size()-DestByte-1)
3468 return true;
3469
3470 // If the destination byte value is already defined, the values are or'd
3471 // together, which isn't a bswap (unless it's an or of the same bits).
3472 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3473 return true;
3474 ByteValues[DestByte] = SI->getOperand(0);
3475 return false;
3476}
3477
3478/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3479/// If so, insert the new bswap intrinsic and return it.
3480Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3481 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003482 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003483 return 0;
3484
3485 /// ByteValues - For each byte of the result, we keep track of which value
3486 /// defines each byte.
3487 std::vector<Value*> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003488 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003489
3490 // Try to find all the pieces corresponding to the bswap.
3491 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3492 CollectBSwapParts(I.getOperand(1), ByteValues))
3493 return 0;
3494
3495 // Check to see if all of the bytes come from the same value.
3496 Value *V = ByteValues[0];
3497 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3498
3499 // Check to make sure that all of the bytes come from the same value.
3500 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3501 if (ByteValues[i] != V)
3502 return 0;
3503
3504 // If they do then *success* we can turn this into a bswap. Figure out what
3505 // bswap to make it into.
3506 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003507 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003508 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003509 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003510 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003511 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003512 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003513 FnName = "llvm.bswap.i64";
3514 else
3515 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003516 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003517 return new CallInst(F, V);
3518}
3519
3520
Chris Lattner113f4f42002-06-25 16:13:24 +00003521Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003522 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003524
Chris Lattner81a7a232004-10-16 18:11:37 +00003525 if (isa<UndefValue>(Op1))
3526 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003527 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003528
Chris Lattner5b2edb12006-02-12 08:02:11 +00003529 // or X, X = X
3530 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003531 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003532
Chris Lattner5b2edb12006-02-12 08:02:11 +00003533 // See if we can simplify any instructions used by the instruction whose sole
3534 // purpose is to compute bits we don't care about.
3535 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003536 if (!isa<PackedType>(I.getType()) &&
Chris Lattner03c49532007-01-15 02:27:26 +00003537 SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003538 KnownZero, KnownOne))
3539 return &I;
3540
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003541 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003543 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003544 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3545 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003546 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3547 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003548 InsertNewInstBefore(Or, I);
3549 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3550 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003551
Chris Lattnerd4252a72004-07-30 07:50:03 +00003552 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3553 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3554 std::string Op0Name = Op0->getName(); Op0->setName("");
3555 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3556 InsertNewInstBefore(Or, I);
3557 return BinaryOperator::createXor(Or,
3558 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003559 }
Chris Lattner183b3362004-04-09 19:05:30 +00003560
3561 // Try to fold constant and into select arguments.
3562 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003563 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003564 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003565 if (isa<PHINode>(Op0))
3566 if (Instruction *NV = FoldOpIntoPhi(I))
3567 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003568 }
3569
Chris Lattner330628a2006-01-06 17:59:59 +00003570 Value *A = 0, *B = 0;
3571 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003572
3573 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3574 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3575 return ReplaceInstUsesWith(I, Op1);
3576 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3577 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3578 return ReplaceInstUsesWith(I, Op0);
3579
Chris Lattnerb7845d62006-07-10 20:25:24 +00003580 // (A | B) | C and A | (B | C) -> bswap if possible.
3581 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003582 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003583 match(Op1, m_Or(m_Value(), m_Value())) ||
3584 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3585 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003586 if (Instruction *BSwap = MatchBSwap(I))
3587 return BSwap;
3588 }
3589
Chris Lattnerb62f5082005-05-09 04:58:36 +00003590 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3591 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003592 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003593 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3594 Op0->setName("");
3595 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3596 }
3597
3598 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3599 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003600 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003601 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3602 Op0->setName("");
3603 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3604 }
3605
Chris Lattner15212982005-09-18 03:42:07 +00003606 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003607 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003608 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3609
3610 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3611 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3612
3613
Chris Lattner01f56c62005-09-18 06:02:59 +00003614 // If we have: ((V + N) & C1) | (V & C2)
3615 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3616 // replace with V+N.
3617 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003618 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003619 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003620 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3621 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003622 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003623 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003624 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003625 return ReplaceInstUsesWith(I, A);
3626 }
3627 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003628 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003629 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3630 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003631 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003632 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003633 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003634 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003635 }
3636 }
3637 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003638
3639 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3640 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3641 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3642 if (SI0->getOpcode() == SI1->getOpcode() &&
3643 SI0->getOperand(1) == SI1->getOperand(1) &&
3644 (SI0->hasOneUse() || SI1->hasOneUse())) {
3645 Instruction *NewOp =
3646 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3647 SI1->getOperand(0),
3648 SI0->getName()), I);
3649 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3650 }
3651 }
Chris Lattner812aab72003-08-12 19:11:07 +00003652
Chris Lattnerd4252a72004-07-30 07:50:03 +00003653 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3654 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003655 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003656 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003657 } else {
3658 A = 0;
3659 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003660 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003661 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3662 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003663 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003664 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003665
Misha Brukman9c003d82004-07-30 12:50:08 +00003666 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003667 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3668 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3669 I.getName()+".demorgan"), I);
3670 return BinaryOperator::createNot(And);
3671 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003672 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003673
Reid Spencer266e42b2006-12-23 06:05:41 +00003674 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3675 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3676 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003677 return R;
3678
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003679 Value *LHSVal, *RHSVal;
3680 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003681 ICmpInst::Predicate LHSCC, RHSCC;
3682 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3683 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3684 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3685 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3686 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3687 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3688 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3689 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003690 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003691 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3692 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3693 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3694 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003695 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003696 std::swap(LHS, RHS);
3697 std::swap(LHSCst, RHSCst);
3698 std::swap(LHSCC, RHSCC);
3699 }
3700
Reid Spencer266e42b2006-12-23 06:05:41 +00003701 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003702 // comparing a value against two constants and or'ing the result
3703 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003704 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3705 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003706 // equal.
3707 assert(LHSCst != RHSCst && "Compares not folded above?");
3708
3709 switch (LHSCC) {
3710 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003711 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003712 switch (RHSCC) {
3713 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003714 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003715 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3716 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3717 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3718 LHSVal->getName()+".off");
3719 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003720 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003721 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003722 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003723 break; // (X == 13 | X == 15) -> no change
3724 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3725 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003726 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003727 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3728 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3729 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003730 return ReplaceInstUsesWith(I, RHS);
3731 }
3732 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003733 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003734 switch (RHSCC) {
3735 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003736 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3737 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3738 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003739 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003740 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3741 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3742 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003743 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003744 }
3745 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003746 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003747 switch (RHSCC) {
3748 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003749 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003750 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003751 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3752 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3753 false, I);
3754 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3755 break;
3756 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3757 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003758 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003759 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3760 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 }
3762 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003763 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003764 switch (RHSCC) {
3765 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003766 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3767 break;
3768 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3769 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3770 false, I);
3771 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3772 break;
3773 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3774 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3775 return ReplaceInstUsesWith(I, RHS);
3776 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3777 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003778 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003779 break;
3780 case ICmpInst::ICMP_UGT:
3781 switch (RHSCC) {
3782 default: assert(0 && "Unknown integer condition code!");
3783 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3784 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3785 return ReplaceInstUsesWith(I, LHS);
3786 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3787 break;
3788 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3789 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003790 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003791 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3792 break;
3793 }
3794 break;
3795 case ICmpInst::ICMP_SGT:
3796 switch (RHSCC) {
3797 default: assert(0 && "Unknown integer condition code!");
3798 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3799 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3800 return ReplaceInstUsesWith(I, LHS);
3801 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3802 break;
3803 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3804 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003805 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003806 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3807 break;
3808 }
3809 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003810 }
3811 }
3812 }
Chris Lattner3af10532006-05-05 06:39:07 +00003813
3814 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003815 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003816 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003817 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3818 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003819 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003820 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003821 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3822 I.getType(), TD) &&
3823 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3824 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003825 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3826 Op1C->getOperand(0),
3827 I.getName());
3828 InsertNewInstBefore(NewOp, I);
3829 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3830 }
Chris Lattner3af10532006-05-05 06:39:07 +00003831 }
Chris Lattner3af10532006-05-05 06:39:07 +00003832
Chris Lattner15212982005-09-18 03:42:07 +00003833
Chris Lattner113f4f42002-06-25 16:13:24 +00003834 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003835}
3836
Chris Lattnerc2076352004-02-16 01:20:27 +00003837// XorSelf - Implements: X ^ X --> 0
3838struct XorSelf {
3839 Value *RHS;
3840 XorSelf(Value *rhs) : RHS(rhs) {}
3841 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3842 Instruction *apply(BinaryOperator &Xor) const {
3843 return &Xor;
3844 }
3845};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003846
3847
Chris Lattner113f4f42002-06-25 16:13:24 +00003848Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003849 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003851
Chris Lattner81a7a232004-10-16 18:11:37 +00003852 if (isa<UndefValue>(Op1))
3853 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3854
Chris Lattnerc2076352004-02-16 01:20:27 +00003855 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3856 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3857 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003858 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003859 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003860
3861 // See if we can simplify any instructions used by the instruction whose sole
3862 // purpose is to compute bits we don't care about.
3863 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003864 if (!isa<PackedType>(I.getType()) &&
Chris Lattner03c49532007-01-15 02:27:26 +00003865 SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003866 KnownZero, KnownOne))
3867 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003868
Zhou Sheng75b871f2007-01-11 12:24:14 +00003869 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003870 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3871 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003872 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003873 return new ICmpInst(ICI->getInversePredicate(),
3874 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003875
Reid Spencer266e42b2006-12-23 06:05:41 +00003876 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003877 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003878 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3879 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003880 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3881 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003882 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003883 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003884 }
Chris Lattner023a4832004-06-18 06:07:51 +00003885
3886 // ~(~X & Y) --> (X | ~Y)
3887 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3888 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3889 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3890 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003891 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003892 Op0I->getOperand(1)->getName()+".not");
3893 InsertNewInstBefore(NotY, I);
3894 return BinaryOperator::createOr(Op0NotVal, NotY);
3895 }
3896 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003897
Chris Lattner97638592003-07-23 21:37:07 +00003898 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003899 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003900 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003901 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003902 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3903 return BinaryOperator::createSub(
3904 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003905 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003906 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003907 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003908 } else if (Op0I->getOpcode() == Instruction::Or) {
3909 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3910 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3911 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3912 // Anything in both C1 and C2 is known to be zero, remove it from
3913 // NewRHS.
3914 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3915 NewRHS = ConstantExpr::getAnd(NewRHS,
3916 ConstantExpr::getNot(CommonBits));
3917 WorkList.push_back(Op0I);
3918 I.setOperand(0, Op0I->getOperand(0));
3919 I.setOperand(1, NewRHS);
3920 return &I;
3921 }
Chris Lattner97638592003-07-23 21:37:07 +00003922 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003923 }
Chris Lattner183b3362004-04-09 19:05:30 +00003924
3925 // Try to fold constant and into select arguments.
3926 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003927 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003928 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003929 if (isa<PHINode>(Op0))
3930 if (Instruction *NV = FoldOpIntoPhi(I))
3931 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003932 }
3933
Chris Lattnerbb74e222003-03-10 23:06:50 +00003934 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003935 if (X == Op1)
3936 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003937 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003938
Chris Lattnerbb74e222003-03-10 23:06:50 +00003939 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003940 if (X == Op0)
3941 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003942 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003943
Chris Lattnerdcd07922006-04-01 08:03:55 +00003944 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003945 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003946 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003947 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003948 I.swapOperands();
3949 std::swap(Op0, Op1);
3950 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003951 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003952 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003953 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003954 } else if (Op1I->getOpcode() == Instruction::Xor) {
3955 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3956 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3957 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3958 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003959 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3960 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3961 Op1I->swapOperands();
3962 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3963 I.swapOperands(); // Simplified below.
3964 std::swap(Op0, Op1);
3965 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003966 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003967
Chris Lattnerdcd07922006-04-01 08:03:55 +00003968 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003969 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003970 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003971 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003972 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003973 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3974 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003975 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003976 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003977 } else if (Op0I->getOpcode() == Instruction::Xor) {
3978 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3979 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3980 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3981 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003982 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3983 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3984 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003985 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3986 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003987 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3988 InsertNewInstBefore(N, I);
3989 return BinaryOperator::createAnd(N, Op1);
3990 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003991 }
3992
Reid Spencer266e42b2006-12-23 06:05:41 +00003993 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3994 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
3995 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003996 return R;
3997
Chris Lattner3af10532006-05-05 06:39:07 +00003998 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003999 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004000 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004001 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4002 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004003 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004004 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004005 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4006 I.getType(), TD) &&
4007 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4008 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004009 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4010 Op1C->getOperand(0),
4011 I.getName());
4012 InsertNewInstBefore(NewOp, I);
4013 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4014 }
Chris Lattner3af10532006-05-05 06:39:07 +00004015 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004016
4017 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4018 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4019 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4020 if (SI0->getOpcode() == SI1->getOpcode() &&
4021 SI0->getOperand(1) == SI1->getOperand(1) &&
4022 (SI0->hasOneUse() || SI1->hasOneUse())) {
4023 Instruction *NewOp =
4024 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4025 SI1->getOperand(0),
4026 SI0->getName()), I);
4027 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4028 }
4029 }
Chris Lattner3af10532006-05-05 06:39:07 +00004030
Chris Lattner113f4f42002-06-25 16:13:24 +00004031 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004032}
4033
Chris Lattner6862fbd2004-09-29 17:40:11 +00004034static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004035 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004036}
4037
4038/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4039/// overflowed for this type.
4040static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4041 ConstantInt *In2) {
4042 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4043
Reid Spencerc635f472006-12-31 05:48:39 +00004044 return cast<ConstantInt>(Result)->getZExtValue() <
4045 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004046}
4047
Chris Lattner0798af32005-01-13 20:14:25 +00004048/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4049/// code necessary to compute the offset from the base pointer (without adding
4050/// in the base pointer). Return the result as a signed integer of intptr size.
4051static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4052 TargetData &TD = IC.getTargetData();
4053 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004054 const Type *IntPtrTy = TD.getIntPtrType();
4055 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004056
4057 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004058 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004059
Chris Lattner0798af32005-01-13 20:14:25 +00004060 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4061 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004062 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004063 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004064 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4065 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004066 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004067 Scale = ConstantExpr::getMul(OpC, Scale);
4068 if (Constant *RC = dyn_cast<Constant>(Result))
4069 Result = ConstantExpr::getAdd(RC, Scale);
4070 else {
4071 // Emit an add instruction.
4072 Result = IC.InsertNewInstBefore(
4073 BinaryOperator::createAdd(Result, Scale,
4074 GEP->getName()+".offs"), I);
4075 }
4076 }
4077 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004078 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004079 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004080 Op->getName()+".c"), I);
4081 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004082 // We'll let instcombine(mul) convert this to a shl if possible.
4083 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4084 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004085
4086 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004087 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004088 GEP->getName()+".offs"), I);
4089 }
4090 }
4091 return Result;
4092}
4093
Reid Spencer266e42b2006-12-23 06:05:41 +00004094/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004095/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004096Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4097 ICmpInst::Predicate Cond,
4098 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004099 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004100
4101 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4102 if (isa<PointerType>(CI->getOperand(0)->getType()))
4103 RHS = CI->getOperand(0);
4104
Chris Lattner0798af32005-01-13 20:14:25 +00004105 Value *PtrBase = GEPLHS->getOperand(0);
4106 if (PtrBase == RHS) {
4107 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004108 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4109 // each index is zero or not.
4110 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004111 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004112 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4113 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004114 bool EmitIt = true;
4115 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4116 if (isa<UndefValue>(C)) // undef index -> undef.
4117 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4118 if (C->isNullValue())
4119 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004120 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4121 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004122 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004123 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004124 ConstantInt::get(Type::Int1Ty,
4125 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004126 }
4127
4128 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004129 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004130 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004131 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4132 if (InVal == 0)
4133 InVal = Comp;
4134 else {
4135 InVal = InsertNewInstBefore(InVal, I);
4136 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004137 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004138 InVal = BinaryOperator::createOr(InVal, Comp);
4139 else // True if all are equal
4140 InVal = BinaryOperator::createAnd(InVal, Comp);
4141 }
4142 }
4143 }
4144
4145 if (InVal)
4146 return InVal;
4147 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004148 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004149 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4150 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004151 }
Chris Lattner0798af32005-01-13 20:14:25 +00004152
Reid Spencer266e42b2006-12-23 06:05:41 +00004153 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004154 // the result to fold to a constant!
4155 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4156 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4157 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004158 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4159 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004160 }
4161 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004162 // If the base pointers are different, but the indices are the same, just
4163 // compare the base pointer.
4164 if (PtrBase != GEPRHS->getOperand(0)) {
4165 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004166 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004167 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004168 if (IndicesTheSame)
4169 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4170 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4171 IndicesTheSame = false;
4172 break;
4173 }
4174
4175 // If all indices are the same, just compare the base pointers.
4176 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004177 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4178 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004179
4180 // Otherwise, the base pointers are different and the indices are
4181 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004182 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004183 }
Chris Lattner0798af32005-01-13 20:14:25 +00004184
Chris Lattner81e84172005-01-13 22:25:21 +00004185 // If one of the GEPs has all zero indices, recurse.
4186 bool AllZeros = true;
4187 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4188 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4189 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4190 AllZeros = false;
4191 break;
4192 }
4193 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004194 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4195 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004196
4197 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004198 AllZeros = true;
4199 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4200 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4201 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4202 AllZeros = false;
4203 break;
4204 }
4205 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004206 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004207
Chris Lattner4fa89822005-01-14 00:20:05 +00004208 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4209 // If the GEPs only differ by one index, compare it.
4210 unsigned NumDifferences = 0; // Keep track of # differences.
4211 unsigned DiffOperand = 0; // The operand that differs.
4212 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4213 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004214 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4215 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004216 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004217 NumDifferences = 2;
4218 break;
4219 } else {
4220 if (NumDifferences++) break;
4221 DiffOperand = i;
4222 }
4223 }
4224
4225 if (NumDifferences == 0) // SAME GEP?
4226 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004227 ConstantInt::get(Type::Int1Ty,
4228 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004229 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004230 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4231 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004232 // Make sure we do a signed comparison here.
4233 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004234 }
4235 }
4236
Reid Spencer266e42b2006-12-23 06:05:41 +00004237 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004238 // the result to fold to a constant!
4239 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4240 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4241 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4242 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4243 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004244 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004245 }
4246 }
4247 return 0;
4248}
4249
Reid Spencer266e42b2006-12-23 06:05:41 +00004250Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4251 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004253
Chris Lattner6ee923f2007-01-14 19:42:17 +00004254 // Fold trivial predicates.
4255 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4256 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4257 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4258 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4259
4260 // Simplify 'fcmp pred X, X'
4261 if (Op0 == Op1) {
4262 switch (I.getPredicate()) {
4263 default: assert(0 && "Unknown predicate!");
4264 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4265 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4266 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4267 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4268 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4269 case FCmpInst::FCMP_OLT: // True if ordered and less than
4270 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4271 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4272
4273 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4274 case FCmpInst::FCMP_ULT: // True if unordered or less than
4275 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4276 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4277 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4278 I.setPredicate(FCmpInst::FCMP_UNO);
4279 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4280 return &I;
4281
4282 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4283 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4284 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4285 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4286 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4287 I.setPredicate(FCmpInst::FCMP_ORD);
4288 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4289 return &I;
4290 }
4291 }
4292
Reid Spencer266e42b2006-12-23 06:05:41 +00004293 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004294 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004295
Reid Spencer266e42b2006-12-23 06:05:41 +00004296 // Handle fcmp with constant RHS
4297 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4298 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4299 switch (LHSI->getOpcode()) {
4300 case Instruction::PHI:
4301 if (Instruction *NV = FoldOpIntoPhi(I))
4302 return NV;
4303 break;
4304 case Instruction::Select:
4305 // If either operand of the select is a constant, we can fold the
4306 // comparison into the select arms, which will cause one to be
4307 // constant folded and the select turned into a bitwise or.
4308 Value *Op1 = 0, *Op2 = 0;
4309 if (LHSI->hasOneUse()) {
4310 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4311 // Fold the known value into the constant operand.
4312 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4313 // Insert a new FCmp of the other select operand.
4314 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4315 LHSI->getOperand(2), RHSC,
4316 I.getName()), I);
4317 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4318 // Fold the known value into the constant operand.
4319 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4320 // Insert a new FCmp of the other select operand.
4321 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4322 LHSI->getOperand(1), RHSC,
4323 I.getName()), I);
4324 }
4325 }
4326
4327 if (Op1)
4328 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4329 break;
4330 }
4331 }
4332
4333 return Changed ? &I : 0;
4334}
4335
4336Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4337 bool Changed = SimplifyCompare(I);
4338 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4339 const Type *Ty = Op0->getType();
4340
4341 // icmp X, X
4342 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004343 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4344 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004345
4346 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004347 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004348
4349 // icmp of GlobalValues can never equal each other as long as they aren't
4350 // external weak linkage type.
4351 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4352 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4353 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004354 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4355 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004356
4357 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004358 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004359 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4360 isa<ConstantPointerNull>(Op0)) &&
4361 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004362 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004363 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4364 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004365
Reid Spencer266e42b2006-12-23 06:05:41 +00004366 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004367 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004368 switch (I.getPredicate()) {
4369 default: assert(0 && "Invalid icmp instruction!");
4370 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004371 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004372 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004373 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004374 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004375 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004376 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004377
Reid Spencer266e42b2006-12-23 06:05:41 +00004378 case ICmpInst::ICMP_UGT:
4379 case ICmpInst::ICMP_SGT:
4380 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004381 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004382 case ICmpInst::ICMP_ULT:
4383 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004384 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4385 InsertNewInstBefore(Not, I);
4386 return BinaryOperator::createAnd(Not, Op1);
4387 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004388 case ICmpInst::ICMP_UGE:
4389 case ICmpInst::ICMP_SGE:
4390 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004391 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004392 case ICmpInst::ICMP_ULE:
4393 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004394 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4395 InsertNewInstBefore(Not, I);
4396 return BinaryOperator::createOr(Not, Op1);
4397 }
4398 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004399 }
4400
Chris Lattner2dd01742004-06-09 04:24:29 +00004401 // See if we are doing a comparison between a constant and an instruction that
4402 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004403 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004404 switch (I.getPredicate()) {
4405 default: break;
4406 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4407 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004408 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004409 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4410 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4411 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4412 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4413 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004414
Reid Spencer266e42b2006-12-23 06:05:41 +00004415 case ICmpInst::ICMP_SLT:
4416 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004417 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004418 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4419 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4420 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4421 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4422 break;
4423
4424 case ICmpInst::ICMP_UGT:
4425 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004426 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004427 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4428 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4429 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4430 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4431 break;
4432
4433 case ICmpInst::ICMP_SGT:
4434 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004436 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4437 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4438 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4439 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4440 break;
4441
4442 case ICmpInst::ICMP_ULE:
4443 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004444 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004445 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4446 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4447 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4448 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4449 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004450
Reid Spencer266e42b2006-12-23 06:05:41 +00004451 case ICmpInst::ICMP_SLE:
4452 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004453 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004454 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4455 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4456 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4457 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4458 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004459
Reid Spencer266e42b2006-12-23 06:05:41 +00004460 case ICmpInst::ICMP_UGE:
4461 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004462 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004463 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4464 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4465 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4466 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4467 break;
4468
4469 case ICmpInst::ICMP_SGE:
4470 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004471 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004472 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4473 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4474 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4475 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4476 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004477 }
4478
Reid Spencer266e42b2006-12-23 06:05:41 +00004479 // If we still have a icmp le or icmp ge instruction, turn it into the
4480 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004481 // already been handled above, this requires little checking.
4482 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004483 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4484 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4485 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4486 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4487 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4488 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4489 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4490 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004491
4492 // See if we can fold the comparison based on bits known to be zero or one
4493 // in the input.
4494 uint64_t KnownZero, KnownOne;
Chris Lattner03c49532007-01-15 02:27:26 +00004495 if (SimplifyDemandedBits(Op0, Ty->getIntegerTypeMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004496 KnownZero, KnownOne, 0))
4497 return &I;
4498
4499 // Given the known and unknown bits, compute a range that the LHS could be
4500 // in.
4501 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004502 // Compute the Min, Max and RHS values based on the known bits. For the
4503 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004504 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4505 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004506 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4507 SRHSVal = CI->getSExtValue();
4508 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4509 SMax);
4510 } else {
4511 URHSVal = CI->getZExtValue();
4512 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4513 UMax);
4514 }
4515 switch (I.getPredicate()) { // LE/GE have been folded already.
4516 default: assert(0 && "Unknown icmp opcode!");
4517 case ICmpInst::ICMP_EQ:
4518 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004519 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004520 break;
4521 case ICmpInst::ICMP_NE:
4522 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004523 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004524 break;
4525 case ICmpInst::ICMP_ULT:
4526 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004527 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004528 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004529 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 break;
4531 case ICmpInst::ICMP_UGT:
4532 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004534 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004535 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004536 break;
4537 case ICmpInst::ICMP_SLT:
4538 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004539 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004541 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 break;
4543 case ICmpInst::ICMP_SGT:
4544 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004545 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004546 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004547 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004548 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004549 }
4550 }
4551
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004553 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004555 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004556 switch (LHSI->getOpcode()) {
4557 case Instruction::And:
4558 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4559 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004560 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4561
Reid Spencer266e42b2006-12-23 06:05:41 +00004562 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004563 // and/compare to be the input width without changing the value
4564 // produced, eliminating a cast.
4565 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4566 // We can do this transformation if either the AND constant does not
4567 // have its sign bit set or if it is an equality comparison.
4568 // Extending a relational comparison when we're checking the sign
4569 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004570 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004571 (I.isEquality() ||
4572 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4573 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4574 ConstantInt *NewCST;
4575 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004576 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4577 AndCST->getZExtValue());
4578 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4579 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004580 Instruction *NewAnd =
4581 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4582 LHSI->getName());
4583 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004584 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004585 }
4586 }
4587
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004588 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4589 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4590 // happens a LOT in code produced by the C front-end, for bitfield
4591 // access.
4592 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004593
4594 // Check to see if there is a noop-cast between the shift and the and.
4595 if (!Shift) {
4596 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004597 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004598 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4599 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004600
Reid Spencere0fc4df2006-10-20 07:07:24 +00004601 ConstantInt *ShAmt;
4602 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004603 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4604 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004605
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004606 // We can fold this as long as we can't shift unknown bits
4607 // into the mask. This can only happen with signed shift
4608 // rights, as they sign-extend.
4609 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004610 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004611 if (!CanFold) {
4612 // To test for the bad case of the signed shr, see if any
4613 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004614 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004615 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4616
Reid Spencerc635f472006-12-31 05:48:39 +00004617 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004618 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004619 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4620 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004621 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4622 CanFold = true;
4623 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004624
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004625 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004626 Constant *NewCst;
4627 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004628 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004629 else
4630 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004631
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004632 // Check to see if we are shifting out any of the bits being
4633 // compared.
4634 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4635 // If we shifted bits out, the fold is not going to work out.
4636 // As a special case, check to see if this means that the
4637 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004638 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004639 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004640 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004641 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004642 } else {
4643 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004644 Constant *NewAndCST;
4645 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004646 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004647 else
4648 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4649 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004650 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004651 WorkList.push_back(Shift); // Shift is dead.
4652 AddUsesToWorkList(I);
4653 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004654 }
4655 }
Chris Lattner35167c32004-06-09 07:59:58 +00004656 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004657
4658 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4659 // preferable because it allows the C<<Y expression to be hoisted out
4660 // of a loop if Y is invariant and X is not.
4661 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004662 I.isEquality() && !Shift->isArithmeticShift() &&
4663 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004664 // Compute C << Y.
4665 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004666 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004667 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4668 "tmp");
4669 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004670 // Insert a logical shift.
4671 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004672 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004673 }
4674 InsertNewInstBefore(cast<Instruction>(NS), I);
4675
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004676 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004677 Instruction *NewAnd = BinaryOperator::createAnd(
4678 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004679 InsertNewInstBefore(NewAnd, I);
4680
4681 I.setOperand(0, NewAnd);
4682 return &I;
4683 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004684 }
4685 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004686
Reid Spencer266e42b2006-12-23 06:05:41 +00004687 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004688 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004689 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004690 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4691
4692 // Check that the shift amount is in range. If not, don't perform
4693 // undefined shifts. When the shift is visited it will be
4694 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004695 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004696 break;
4697
Chris Lattner272d5ca2004-09-28 18:22:15 +00004698 // If we are comparing against bits always shifted out, the
4699 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004700 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004701 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004702 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004703 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004704 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004705 return ReplaceInstUsesWith(I, Cst);
4706 }
4707
4708 if (LHSI->hasOneUse()) {
4709 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004710 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004711 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004712 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004713
Chris Lattner272d5ca2004-09-28 18:22:15 +00004714 Instruction *AndI =
4715 BinaryOperator::createAnd(LHSI->getOperand(0),
4716 Mask, LHSI->getName()+".mask");
4717 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004718 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004719 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004720 }
4721 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004722 }
4723 break;
4724
Reid Spencer266e42b2006-12-23 06:05:41 +00004725 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004726 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004727 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004728 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004729 // Check that the shift amount is in range. If not, don't perform
4730 // undefined shifts. When the shift is visited it will be
4731 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004732 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004733 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004734 break;
4735
Chris Lattner1023b872004-09-27 16:18:50 +00004736 // If we are comparing against bits always shifted out, the
4737 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004738 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004739 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004740 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4741 ShAmt);
4742 else
4743 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4744 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004745
Chris Lattner1023b872004-09-27 16:18:50 +00004746 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004747 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004748 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004749 return ReplaceInstUsesWith(I, Cst);
4750 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004751
Chris Lattner1023b872004-09-27 16:18:50 +00004752 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004753 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004754
Chris Lattner1023b872004-09-27 16:18:50 +00004755 // Otherwise strength reduce the shift into an and.
4756 uint64_t Val = ~0ULL; // All ones.
4757 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004758 Val &= ~0ULL >> (64-TypeBits);
4759 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004760
Chris Lattner1023b872004-09-27 16:18:50 +00004761 Instruction *AndI =
4762 BinaryOperator::createAnd(LHSI->getOperand(0),
4763 Mask, LHSI->getName()+".mask");
4764 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004765 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004766 ConstantExpr::getShl(CI, ShAmt));
4767 }
Chris Lattner1023b872004-09-27 16:18:50 +00004768 }
4769 }
4770 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004771
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004772 case Instruction::SDiv:
4773 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004774 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004775 // Fold this div into the comparison, producing a range check.
4776 // Determine, based on the divide type, what the range is being
4777 // checked. If there is an overflow on the low or high side, remember
4778 // it, otherwise compute the range [low, hi) bounding the new value.
4779 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004780 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004781 // FIXME: If the operand types don't match the type of the divide
4782 // then don't attempt this transform. The code below doesn't have the
4783 // logic to deal with a signed divide and an unsigned compare (and
4784 // vice versa). This is because (x /s C1) <s C2 produces different
4785 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4786 // (x /u C1) <u C2. Simply casting the operands and result won't
4787 // work. :( The if statement below tests that condition and bails
4788 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004789 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4790 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004791 break;
4792
4793 // Initialize the variables that will indicate the nature of the
4794 // range check.
4795 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004796 ConstantInt *LoBound = 0, *HiBound = 0;
4797
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004798 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4799 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4800 // C2 (CI). By solving for X we can turn this into a range check
4801 // instead of computing a divide.
4802 ConstantInt *Prod =
4803 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004804
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004805 // Determine if the product overflows by seeing if the product is
4806 // not equal to the divide. Make sure we do the same kind of divide
4807 // as in the LHS instruction that we're folding.
4808 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004809 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004810 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4811
Reid Spencer266e42b2006-12-23 06:05:41 +00004812 // Get the ICmp opcode
4813 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004814
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004815 if (DivRHS->isNullValue()) {
4816 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004817 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004818 LoBound = Prod;
4819 LoOverflow = ProdOV;
4820 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004821 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004822 if (CI->isNullValue()) { // (X / pos) op 0
4823 // Can't overflow.
4824 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4825 HiBound = DivRHS;
4826 } else if (isPositive(CI)) { // (X / pos) op pos
4827 LoBound = Prod;
4828 LoOverflow = ProdOV;
4829 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4830 } else { // (X / pos) op neg
4831 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4832 LoOverflow = AddWithOverflow(LoBound, Prod,
4833 cast<ConstantInt>(DivRHSH));
4834 HiBound = Prod;
4835 HiOverflow = ProdOV;
4836 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004837 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004838 if (CI->isNullValue()) { // (X / neg) op 0
4839 LoBound = AddOne(DivRHS);
4840 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004841 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004842 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004843 } else if (isPositive(CI)) { // (X / neg) op pos
4844 HiOverflow = LoOverflow = ProdOV;
4845 if (!LoOverflow)
4846 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4847 HiBound = AddOne(Prod);
4848 } else { // (X / neg) op neg
4849 LoBound = Prod;
4850 LoOverflow = HiOverflow = ProdOV;
4851 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4852 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004853
Chris Lattnera92af962004-10-11 19:40:04 +00004854 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004855 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004856 }
4857
4858 if (LoBound) {
4859 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004860 switch (predicate) {
4861 default: assert(0 && "Unhandled icmp opcode!");
4862 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004863 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004864 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004865 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004866 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4867 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004868 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004869 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4870 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004871 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004872 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4873 true, I);
4874 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004875 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004876 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004877 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004878 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4879 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004880 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004881 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4882 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004883 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004884 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4885 false, I);
4886 case ICmpInst::ICMP_ULT:
4887 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004888 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004889 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004890 return new ICmpInst(predicate, X, LoBound);
4891 case ICmpInst::ICMP_UGT:
4892 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004893 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004894 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004895 if (predicate == ICmpInst::ICMP_UGT)
4896 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4897 else
4898 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004899 }
4900 }
4901 }
4902 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004903 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004904
Reid Spencer266e42b2006-12-23 06:05:41 +00004905 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004906 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004907 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004908
Reid Spencere0fc4df2006-10-20 07:07:24 +00004909 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4910 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4912 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004913 case Instruction::SRem:
4914 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4915 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4916 BO->hasOneUse()) {
4917 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4918 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004919 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4920 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 return new ICmpInst(I.getPredicate(), NewRem,
4922 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004923 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004924 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004925 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004926 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004927 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4928 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004929 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004930 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4931 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004932 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004933 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4934 // efficiently invertible, or if the add has just this one use.
4935 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004936
Chris Lattnerc992add2003-08-13 05:33:12 +00004937 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004938 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004939 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004940 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004941 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004942 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4943 BO->setName("");
4944 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004946 }
4947 }
4948 break;
4949 case Instruction::Xor:
4950 // For the xor case, we can xor two constants together, eliminating
4951 // the explicit xor.
4952 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004953 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4954 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004955
4956 // FALLTHROUGH
4957 case Instruction::Sub:
4958 // Replace (([sub|xor] A, B) != 0) with (A != B)
4959 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004960 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4961 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004962 break;
4963
4964 case Instruction::Or:
4965 // If bits are being or'd in that are not present in the constant we
4966 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004967 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004968 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004969 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004970 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4971 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004972 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004973 break;
4974
4975 case Instruction::And:
4976 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004977 // If bits are being compared against that are and'd out, then the
4978 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004979 if (!ConstantExpr::getAnd(CI,
4980 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004981 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4982 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004983
Chris Lattner35167c32004-06-09 07:59:58 +00004984 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004985 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004986 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4987 ICmpInst::ICMP_NE, Op0,
4988 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004989
Reid Spencer266e42b2006-12-23 06:05:41 +00004990 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00004991 if (isSignBit(BOC)) {
4992 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004993 Constant *Zero = Constant::getNullValue(X->getType());
4994 ICmpInst::Predicate pred = isICMP_NE ?
4995 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4996 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00004997 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004998
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004999 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005000 if (CI->isNullValue() && isHighOnes(BOC)) {
5001 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005002 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005003 ICmpInst::Predicate pred = isICMP_NE ?
5004 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5005 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005006 }
5007
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005008 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005009 default: break;
5010 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005011 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5012 // Handle set{eq|ne} <intrinsic>, intcst.
5013 switch (II->getIntrinsicID()) {
5014 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005015 case Intrinsic::bswap_i16:
5016 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005017 WorkList.push_back(II); // Dead?
5018 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005019 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005020 ByteSwap_16(CI->getZExtValue())));
5021 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005022 case Intrinsic::bswap_i32:
5023 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005024 WorkList.push_back(II); // Dead?
5025 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005026 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005027 ByteSwap_32(CI->getZExtValue())));
5028 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005029 case Intrinsic::bswap_i64:
5030 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005031 WorkList.push_back(II); // Dead?
5032 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005033 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005034 ByteSwap_64(CI->getZExtValue())));
5035 return &I;
5036 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005037 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005038 } else { // Not a ICMP_EQ/ICMP_NE
5039 // If the LHS is a cast from an integral value of the same size, then
5040 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005041 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5042 Value *CastOp = Cast->getOperand(0);
5043 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005044 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005045 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005046 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005047 // If this is an unsigned comparison, try to make the comparison use
5048 // smaller constant values.
5049 switch (I.getPredicate()) {
5050 default: break;
5051 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5052 ConstantInt *CUI = cast<ConstantInt>(CI);
5053 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5054 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5055 ConstantInt::get(SrcTy, -1));
5056 break;
5057 }
5058 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5059 ConstantInt *CUI = cast<ConstantInt>(CI);
5060 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5061 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5062 Constant::getNullValue(SrcTy));
5063 break;
5064 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005065 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005066
Chris Lattner2b55ea32004-02-23 07:16:20 +00005067 }
5068 }
Chris Lattnere967b342003-06-04 05:10:11 +00005069 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005070 }
5071
Reid Spencer266e42b2006-12-23 06:05:41 +00005072 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005073 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5074 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5075 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005076 case Instruction::GetElementPtr:
5077 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005078 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005079 bool isAllZeros = true;
5080 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5081 if (!isa<Constant>(LHSI->getOperand(i)) ||
5082 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5083 isAllZeros = false;
5084 break;
5085 }
5086 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005087 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005088 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5089 }
5090 break;
5091
Chris Lattner77c32c32005-04-23 15:31:55 +00005092 case Instruction::PHI:
5093 if (Instruction *NV = FoldOpIntoPhi(I))
5094 return NV;
5095 break;
5096 case Instruction::Select:
5097 // If either operand of the select is a constant, we can fold the
5098 // comparison into the select arms, which will cause one to be
5099 // constant folded and the select turned into a bitwise or.
5100 Value *Op1 = 0, *Op2 = 0;
5101 if (LHSI->hasOneUse()) {
5102 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5103 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005104 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5105 // Insert a new ICmp of the other select operand.
5106 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5107 LHSI->getOperand(2), RHSC,
5108 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005109 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5110 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005111 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5112 // Insert a new ICmp of the other select operand.
5113 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5114 LHSI->getOperand(1), RHSC,
5115 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005116 }
5117 }
Jeff Cohen82639852005-04-23 21:38:35 +00005118
Chris Lattner77c32c32005-04-23 15:31:55 +00005119 if (Op1)
5120 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5121 break;
5122 }
5123 }
5124
Reid Spencer266e42b2006-12-23 06:05:41 +00005125 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005126 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005127 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005128 return NI;
5129 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005130 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5131 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005132 return NI;
5133
Reid Spencer266e42b2006-12-23 06:05:41 +00005134 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005135 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5136 // now.
5137 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5138 if (isa<PointerType>(Op0->getType()) &&
5139 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005140 // We keep moving the cast from the left operand over to the right
5141 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005142 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005143
Chris Lattner64d87b02007-01-06 01:45:59 +00005144 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5145 // so eliminate it as well.
5146 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5147 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005148
Chris Lattner16930792003-11-03 04:25:02 +00005149 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005150 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005151 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005152 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005153 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005154 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005155 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005156 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005157 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005158 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005159 }
5160
5161 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005162 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005163 // This comes up when you have code like
5164 // int X = A < B;
5165 // if (X) ...
5166 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005167 // with a constant or another cast from the same type.
5168 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005169 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005170 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005171 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005172
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005173 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005174 Value *A, *B, *C, *D;
5175 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5176 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5177 Value *OtherVal = A == Op1 ? B : A;
5178 return new ICmpInst(I.getPredicate(), OtherVal,
5179 Constant::getNullValue(A->getType()));
5180 }
5181
5182 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5183 // A^c1 == C^c2 --> A == C^(c1^c2)
5184 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5185 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5186 if (Op1->hasOneUse()) {
5187 Constant *NC = ConstantExpr::getXor(C1, C2);
5188 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5189 return new ICmpInst(I.getPredicate(), A,
5190 InsertNewInstBefore(Xor, I));
5191 }
5192
5193 // A^B == A^D -> B == D
5194 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5195 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5196 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5197 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5198 }
5199 }
5200
5201 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5202 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005203 // A == (A^B) -> B == 0
5204 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005205 return new ICmpInst(I.getPredicate(), OtherVal,
5206 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005207 }
5208 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005209 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005210 return new ICmpInst(I.getPredicate(), B,
5211 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005212 }
5213 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005214 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005215 return new ICmpInst(I.getPredicate(), B,
5216 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005217 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005218
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005219 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5220 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5221 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5222 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5223 Value *X = 0, *Y = 0, *Z = 0;
5224
5225 if (A == C) {
5226 X = B; Y = D; Z = A;
5227 } else if (A == D) {
5228 X = B; Y = C; Z = A;
5229 } else if (B == C) {
5230 X = A; Y = D; Z = B;
5231 } else if (B == D) {
5232 X = A; Y = C; Z = B;
5233 }
5234
5235 if (X) { // Build (X^Y) & Z
5236 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5237 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5238 I.setOperand(0, Op1);
5239 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5240 return &I;
5241 }
5242 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005243 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005244 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005245}
5246
Reid Spencer266e42b2006-12-23 06:05:41 +00005247// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005248// We only handle extending casts so far.
5249//
Reid Spencer266e42b2006-12-23 06:05:41 +00005250Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5251 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005252 Value *LHSCIOp = LHSCI->getOperand(0);
5253 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005254 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005255 Value *RHSCIOp;
5256
Reid Spencer266e42b2006-12-23 06:05:41 +00005257 // We only handle extension cast instructions, so far. Enforce this.
5258 if (LHSCI->getOpcode() != Instruction::ZExt &&
5259 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005260 return 0;
5261
Reid Spencer266e42b2006-12-23 06:05:41 +00005262 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5263 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005264
Reid Spencer266e42b2006-12-23 06:05:41 +00005265 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005266 // Not an extension from the same type?
5267 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005268 if (RHSCIOp->getType() != LHSCIOp->getType())
5269 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005270
5271 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5272 // and the other is a zext), then we can't handle this.
5273 if (CI->getOpcode() != LHSCI->getOpcode())
5274 return 0;
5275
5276 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5277 // then we can't handle this.
5278 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5279 return 0;
5280
5281 // Okay, just insert a compare of the reduced operands now!
5282 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005283 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005284
Reid Spencer266e42b2006-12-23 06:05:41 +00005285 // If we aren't dealing with a constant on the RHS, exit early
5286 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5287 if (!CI)
5288 return 0;
5289
5290 // Compute the constant that would happen if we truncated to SrcTy then
5291 // reextended to DestTy.
5292 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5293 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5294
5295 // If the re-extended constant didn't change...
5296 if (Res2 == CI) {
5297 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5298 // For example, we might have:
5299 // %A = sext short %X to uint
5300 // %B = icmp ugt uint %A, 1330
5301 // It is incorrect to transform this into
5302 // %B = icmp ugt short %X, 1330
5303 // because %A may have negative value.
5304 //
5305 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5306 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005307 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005308 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5309 else
5310 return 0;
5311 }
5312
5313 // The re-extended constant changed so the constant cannot be represented
5314 // in the shorter type. Consequently, we cannot emit a simple comparison.
5315
5316 // First, handle some easy cases. We know the result cannot be equal at this
5317 // point so handle the ICI.isEquality() cases
5318 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005319 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005320 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005321 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005322
5323 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5324 // should have been folded away previously and not enter in here.
5325 Value *Result;
5326 if (isSignedCmp) {
5327 // We're performing a signed comparison.
5328 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005329 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005330 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005331 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005332 } else {
5333 // We're performing an unsigned comparison.
5334 if (isSignedExt) {
5335 // We're performing an unsigned comp with a sign extended value.
5336 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005337 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005338 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5339 NegOne, ICI.getName()), ICI);
5340 } else {
5341 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005342 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005343 }
5344 }
5345
5346 // Finally, return the value computed.
5347 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5348 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5349 return ReplaceInstUsesWith(ICI, Result);
5350 } else {
5351 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5352 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5353 "ICmp should be folded!");
5354 if (Constant *CI = dyn_cast<Constant>(Result))
5355 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5356 else
5357 return BinaryOperator::createNot(Result);
5358 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005359}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005360
Chris Lattnere8d6c602003-03-10 19:16:08 +00005361Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005362 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005364
5365 // shl X, 0 == X and shr X, 0 == X
5366 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005367 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005368 Op0 == Constant::getNullValue(Op0->getType()))
5369 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005370
Reid Spencer266e42b2006-12-23 06:05:41 +00005371 if (isa<UndefValue>(Op0)) {
5372 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005373 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005374 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005375 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5376 }
5377 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005378 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5379 return ReplaceInstUsesWith(I, Op0);
5380 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005381 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005382 }
5383
Chris Lattnerd4dee402006-11-10 23:38:52 +00005384 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5385 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005386 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005387 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005388 return ReplaceInstUsesWith(I, CSI);
5389
Chris Lattner183b3362004-04-09 19:05:30 +00005390 // Try to fold constant and into select arguments.
5391 if (isa<Constant>(Op0))
5392 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005394 return R;
5395
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005396 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005397 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005398 if (MaskedValueIsZero(Op0,
5399 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005400 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005401 }
5402 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005403
Reid Spencere0fc4df2006-10-20 07:07:24 +00005404 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005405 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5406 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005407 return 0;
5408}
5409
Reid Spencere0fc4df2006-10-20 07:07:24 +00005410Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005411 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5413 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005414 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005415
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005416 // See if we can simplify any instructions used by the instruction whose sole
5417 // purpose is to compute bits we don't care about.
5418 uint64_t KnownZero, KnownOne;
Chris Lattner03c49532007-01-15 02:27:26 +00005419 if (SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005420 KnownZero, KnownOne))
5421 return &I;
5422
Chris Lattner14553932006-01-06 07:12:35 +00005423 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5424 // of a signed value.
5425 //
5426 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005427 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005428 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005429 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5430 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005431 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005432 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005433 }
Chris Lattner14553932006-01-06 07:12:35 +00005434 }
5435
5436 // ((X*C1) << C2) == (X * (C1 << C2))
5437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5438 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5439 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5440 return BinaryOperator::createMul(BO->getOperand(0),
5441 ConstantExpr::getShl(BOOp, Op1));
5442
5443 // Try to fold constant and into select arguments.
5444 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5445 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5446 return R;
5447 if (isa<PHINode>(Op0))
5448 if (Instruction *NV = FoldOpIntoPhi(I))
5449 return NV;
5450
5451 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005452 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5453 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5454 Value *V1, *V2;
5455 ConstantInt *CC;
5456 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005457 default: break;
5458 case Instruction::Add:
5459 case Instruction::And:
5460 case Instruction::Or:
5461 case Instruction::Xor:
5462 // These operators commute.
5463 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005464 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5465 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005466 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005467 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005468 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005469 Op0BO->getName());
5470 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005471 Instruction *X =
5472 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5473 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005474 InsertNewInstBefore(X, I); // (X + (Y << C))
5475 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005476 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005477 return BinaryOperator::createAnd(X, C2);
5478 }
Chris Lattner14553932006-01-06 07:12:35 +00005479
Chris Lattner797dee72005-09-18 06:30:59 +00005480 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5481 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5482 match(Op0BO->getOperand(1),
5483 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005484 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005485 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005486 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005487 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005488 Op0BO->getName());
5489 InsertNewInstBefore(YS, I); // (Y << C)
5490 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005491 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005492 V1->getName()+".mask");
5493 InsertNewInstBefore(XM, I); // X & (CC << C)
5494
5495 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5496 }
Chris Lattner14553932006-01-06 07:12:35 +00005497
Chris Lattner797dee72005-09-18 06:30:59 +00005498 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005499 case Instruction::Sub:
5500 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005501 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5502 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005503 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005504 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005505 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005506 Op0BO->getName());
5507 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005508 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005509 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005510 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005511 InsertNewInstBefore(X, I); // (X + (Y << C))
5512 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005513 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005514 return BinaryOperator::createAnd(X, C2);
5515 }
Chris Lattner14553932006-01-06 07:12:35 +00005516
Chris Lattner1df0e982006-05-31 21:14:00 +00005517 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005518 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5519 match(Op0BO->getOperand(0),
5520 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005521 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005522 cast<BinaryOperator>(Op0BO->getOperand(0))
5523 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005524 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005525 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005526 Op0BO->getName());
5527 InsertNewInstBefore(YS, I); // (Y << C)
5528 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005529 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005530 V1->getName()+".mask");
5531 InsertNewInstBefore(XM, I); // X & (CC << C)
5532
Chris Lattner1df0e982006-05-31 21:14:00 +00005533 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005534 }
Chris Lattner14553932006-01-06 07:12:35 +00005535
Chris Lattner27cb9db2005-09-18 05:12:10 +00005536 break;
Chris Lattner14553932006-01-06 07:12:35 +00005537 }
5538
5539
5540 // If the operand is an bitwise operator with a constant RHS, and the
5541 // shift is the only use, we can pull it out of the shift.
5542 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5543 bool isValid = true; // Valid only for And, Or, Xor
5544 bool highBitSet = false; // Transform if high bit of constant set?
5545
5546 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005547 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005548 case Instruction::Add:
5549 isValid = isLeftShift;
5550 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005551 case Instruction::Or:
5552 case Instruction::Xor:
5553 highBitSet = false;
5554 break;
5555 case Instruction::And:
5556 highBitSet = true;
5557 break;
Chris Lattner14553932006-01-06 07:12:35 +00005558 }
5559
5560 // If this is a signed shift right, and the high bit is modified
5561 // by the logical operation, do not perform the transformation.
5562 // The highBitSet boolean indicates the value of the high bit of
5563 // the constant which would cause it to be modified for this
5564 // operation.
5565 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005566 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005567 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005568 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5569 }
5570
5571 if (isValid) {
5572 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5573
5574 Instruction *NewShift =
5575 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5576 Op0BO->getName());
5577 Op0BO->setName("");
5578 InsertNewInstBefore(NewShift, I);
5579
5580 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5581 NewRHS);
5582 }
5583 }
5584 }
5585 }
5586
Chris Lattnereb372a02006-01-06 07:52:12 +00005587 // Find out if this is a shift of a shift by a constant.
5588 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005589 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005590 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005591 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5592 // If this is a noop-integer cast of a shift instruction, use the shift.
5593 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005594 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5595 }
5596 }
5597
Reid Spencere0fc4df2006-10-20 07:07:24 +00005598 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005599 // Find the operands and properties of the input shift. Note that the
5600 // signedness of the input shift may differ from the current shift if there
5601 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005602 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5603 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005604 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005605
Reid Spencere0fc4df2006-10-20 07:07:24 +00005606 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005607
Reid Spencere0fc4df2006-10-20 07:07:24 +00005608 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5609 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005610
5611 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5612 if (isLeftShift == isShiftOfLeftShift) {
5613 // Do not fold these shifts if the first one is signed and the second one
5614 // is unsigned and this is a right shift. Further, don't do any folding
5615 // on them.
5616 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5617 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005618
Chris Lattnereb372a02006-01-06 07:52:12 +00005619 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5620 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5621 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005622
Chris Lattnereb372a02006-01-06 07:52:12 +00005623 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005624 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005625 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005626 if (I.getType() == ShiftResult->getType())
5627 return ShiftResult;
5628 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005629 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005630 }
5631
5632 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5633 // signed types, we can only support the (A >> c1) << c2 configuration,
5634 // because it can not turn an arbitrary bit of A into a sign bit.
5635 if (isUnsignedShift || isLeftShift) {
5636 // Calculate bitmask for what gets shifted off the edge.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005637 Constant *C = ConstantInt::getAllOnesValue(I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005638 if (isLeftShift)
5639 C = ConstantExpr::getShl(C, ShiftAmt1C);
5640 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005641 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005642
5643 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005644
5645 Instruction *Mask =
5646 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5647 InsertNewInstBefore(Mask, I);
5648
5649 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005650 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005651 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005652 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005653 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005654 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005655 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5656 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005657 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005658 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005659 } else {
5660 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005661 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005662 }
5663 } else {
5664 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005665 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005666 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005667 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005668 InsertNewInstBefore(Shift, I);
5669
Zhou Sheng75b871f2007-01-11 12:24:14 +00005670 C = ConstantInt::getAllOnesValue(Shift->getType());
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005671 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005672 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005673 }
5674 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005675 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005676 // this case, C1 == C2 and C1 is 8, 16, or 32.
5677 if (ShiftAmt1 == ShiftAmt2) {
5678 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005679 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005680 case 8 : SExtType = Type::Int8Ty; break;
5681 case 16: SExtType = Type::Int16Ty; break;
5682 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005683 }
5684
5685 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005686 Instruction *NewTrunc =
5687 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005688 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005689 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005690 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005691 }
Chris Lattner86102b82005-01-01 16:22:27 +00005692 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005693 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005694 return 0;
5695}
5696
Chris Lattner48a44f72002-05-02 17:06:02 +00005697
Chris Lattner8f663e82005-10-29 04:36:15 +00005698/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5699/// expression. If so, decompose it, returning some value X, such that Val is
5700/// X*Scale+Offset.
5701///
5702static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5703 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005704 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005705 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005706 Offset = CI->getZExtValue();
5707 Scale = 1;
5708 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005709 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5710 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005711 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005712 if (I->getOpcode() == Instruction::Shl) {
5713 // This is a value scaled by '1 << the shift amt'.
5714 Scale = 1U << CUI->getZExtValue();
5715 Offset = 0;
5716 return I->getOperand(0);
5717 } else if (I->getOpcode() == Instruction::Mul) {
5718 // This value is scaled by 'CUI'.
5719 Scale = CUI->getZExtValue();
5720 Offset = 0;
5721 return I->getOperand(0);
5722 } else if (I->getOpcode() == Instruction::Add) {
5723 // We have X+C. Check to see if we really have (X*C2)+C1,
5724 // where C1 is divisible by C2.
5725 unsigned SubScale;
5726 Value *SubVal =
5727 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5728 Offset += CUI->getZExtValue();
5729 if (SubScale > 1 && (Offset % SubScale == 0)) {
5730 Scale = SubScale;
5731 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005732 }
5733 }
5734 }
5735 }
5736 }
5737
5738 // Otherwise, we can't look past this.
5739 Scale = 1;
5740 Offset = 0;
5741 return Val;
5742}
5743
5744
Chris Lattner216be912005-10-24 06:03:58 +00005745/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5746/// try to eliminate the cast by moving the type information into the alloc.
5747Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5748 AllocationInst &AI) {
5749 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005750 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005751
Chris Lattnerac87beb2005-10-24 06:22:12 +00005752 // Remove any uses of AI that are dead.
5753 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5754 std::vector<Instruction*> DeadUsers;
5755 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5756 Instruction *User = cast<Instruction>(*UI++);
5757 if (isInstructionTriviallyDead(User)) {
5758 while (UI != E && *UI == User)
5759 ++UI; // If this instruction uses AI more than once, don't break UI.
5760
5761 // Add operands to the worklist.
5762 AddUsesToWorkList(*User);
5763 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005764 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005765
5766 User->eraseFromParent();
5767 removeFromWorkList(User);
5768 }
5769 }
5770
Chris Lattner216be912005-10-24 06:03:58 +00005771 // Get the type really allocated and the type casted to.
5772 const Type *AllocElTy = AI.getAllocatedType();
5773 const Type *CastElTy = PTy->getElementType();
5774 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005775
Chris Lattner7d190672006-10-01 19:40:58 +00005776 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5777 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005778 if (CastElTyAlign < AllocElTyAlign) return 0;
5779
Chris Lattner46705b22005-10-24 06:35:18 +00005780 // If the allocation has multiple uses, only promote it if we are strictly
5781 // increasing the alignment of the resultant allocation. If we keep it the
5782 // same, we open the door to infinite loops of various kinds.
5783 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5784
Chris Lattner216be912005-10-24 06:03:58 +00005785 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5786 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005787 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005788
Chris Lattner8270c332005-10-29 03:19:53 +00005789 // See if we can satisfy the modulus by pulling a scale out of the array
5790 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005791 unsigned ArraySizeScale, ArrayOffset;
5792 Value *NumElements = // See if the array size is a decomposable linear expr.
5793 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5794
Chris Lattner8270c332005-10-29 03:19:53 +00005795 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5796 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005797 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5798 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005799
Chris Lattner8270c332005-10-29 03:19:53 +00005800 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5801 Value *Amt = 0;
5802 if (Scale == 1) {
5803 Amt = NumElements;
5804 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005805 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005806 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5807 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005808 Amt = ConstantExpr::getMul(
5809 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5810 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005811 else if (Scale != 1) {
5812 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5813 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005814 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005815 }
5816
Chris Lattner8f663e82005-10-29 04:36:15 +00005817 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005818 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005819 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5820 Amt = InsertNewInstBefore(Tmp, AI);
5821 }
5822
Chris Lattner216be912005-10-24 06:03:58 +00005823 std::string Name = AI.getName(); AI.setName("");
5824 AllocationInst *New;
5825 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005826 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005827 else
Nate Begeman848622f2005-11-05 09:21:28 +00005828 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005829 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005830
5831 // If the allocation has multiple uses, insert a cast and change all things
5832 // that used it to use the new cast. This will also hack on CI, but it will
5833 // die soon.
5834 if (!AI.hasOneUse()) {
5835 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005836 // New is the allocation instruction, pointer typed. AI is the original
5837 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5838 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005839 InsertNewInstBefore(NewCast, AI);
5840 AI.replaceAllUsesWith(NewCast);
5841 }
Chris Lattner216be912005-10-24 06:03:58 +00005842 return ReplaceInstUsesWith(CI, New);
5843}
5844
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005845/// CanEvaluateInDifferentType - Return true if we can take the specified value
5846/// and return it without inserting any new casts. This is used by code that
5847/// tries to decide whether promoting or shrinking integer operations to wider
5848/// or smaller types will allow us to eliminate a truncate or extend.
5849static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5850 int &NumCastsRemoved) {
5851 if (isa<Constant>(V)) return true;
5852
5853 Instruction *I = dyn_cast<Instruction>(V);
5854 if (!I || !I->hasOneUse()) return false;
5855
5856 switch (I->getOpcode()) {
5857 case Instruction::And:
5858 case Instruction::Or:
5859 case Instruction::Xor:
5860 // These operators can all arbitrarily be extended or truncated.
5861 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5862 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005863 case Instruction::AShr:
5864 case Instruction::LShr:
5865 case Instruction::Shl:
5866 // If this is just a bitcast changing the sign of the operation, we can
5867 // convert if the operand can be converted.
5868 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5869 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5870 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005871 case Instruction::Trunc:
5872 case Instruction::ZExt:
5873 case Instruction::SExt:
5874 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005875 // If this is a cast from the destination type, we can trivially eliminate
5876 // it, and this will remove a cast overall.
5877 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005878 // If the first operand is itself a cast, and is eliminable, do not count
5879 // this as an eliminable cast. We would prefer to eliminate those two
5880 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005881 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005882 return true;
5883
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005884 ++NumCastsRemoved;
5885 return true;
5886 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005887 break;
5888 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005889 // TODO: Can handle more cases here.
5890 break;
5891 }
5892
5893 return false;
5894}
5895
5896/// EvaluateInDifferentType - Given an expression that
5897/// CanEvaluateInDifferentType returns true for, actually insert the code to
5898/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005899Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5900 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005901 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005902 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005903
5904 // Otherwise, it must be an instruction.
5905 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005906 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005907 switch (I->getOpcode()) {
5908 case Instruction::And:
5909 case Instruction::Or:
5910 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005911 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5912 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005913 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5914 LHS, RHS, I->getName());
5915 break;
5916 }
Chris Lattner960acb02006-11-29 07:18:39 +00005917 case Instruction::AShr:
5918 case Instruction::LShr:
5919 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005920 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005921 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5922 I->getOperand(1), I->getName());
5923 break;
5924 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005925 case Instruction::Trunc:
5926 case Instruction::ZExt:
5927 case Instruction::SExt:
5928 case Instruction::BitCast:
5929 // If the source type of the cast is the type we're trying for then we can
5930 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005931 if (I->getOperand(0)->getType() == Ty)
5932 return I->getOperand(0);
5933
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005934 // Some other kind of cast, which shouldn't happen, so just ..
5935 // FALL THROUGH
5936 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005937 // TODO: Can handle more cases here.
5938 assert(0 && "Unreachable!");
5939 break;
5940 }
5941
5942 return InsertNewInstBefore(Res, *I);
5943}
5944
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005945/// @brief Implement the transforms common to all CastInst visitors.
5946Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005947 Value *Src = CI.getOperand(0);
5948
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005949 // Casting undef to anything results in undef so might as just replace it and
5950 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005951 if (isa<UndefValue>(Src)) // cast undef -> undef
5952 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5953
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005954 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5955 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005956 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005957 if (Instruction::CastOps opc =
5958 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5959 // The first cast (CSrc) is eliminable so we need to fix up or replace
5960 // the second cast (CI). CSrc will then have a good chance of being dead.
5961 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005962 }
5963 }
Chris Lattner03841652004-05-25 04:29:21 +00005964
Chris Lattnerd0d51602003-06-21 23:12:02 +00005965 // If casting the result of a getelementptr instruction with no offset, turn
5966 // this into a cast of the original pointer!
5967 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005968 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005969 bool AllZeroOperands = true;
5970 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5971 if (!isa<Constant>(GEP->getOperand(i)) ||
5972 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5973 AllZeroOperands = false;
5974 break;
5975 }
5976 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005977 // Changing the cast operand is usually not a good idea but it is safe
5978 // here because the pointer operand is being replaced with another
5979 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005980 CI.setOperand(0, GEP->getOperand(0));
5981 return &CI;
5982 }
5983 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005984
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005985 // If we are casting a malloc or alloca to a pointer to a type of the same
5986 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005987 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005988 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5989 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005990
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005991 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005992 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5993 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5994 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005995
5996 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005997 if (isa<PHINode>(Src))
5998 if (Instruction *NV = FoldOpIntoPhi(CI))
5999 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006000
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006001 return 0;
6002}
6003
6004/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6005/// integers. This function implements the common transforms for all those
6006/// cases.
6007/// @brief Implement the transforms common to CastInst with integer operands
6008Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6009 if (Instruction *Result = commonCastTransforms(CI))
6010 return Result;
6011
6012 Value *Src = CI.getOperand(0);
6013 const Type *SrcTy = Src->getType();
6014 const Type *DestTy = CI.getType();
6015 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6016 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6017
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006018 // See if we can simplify any instructions used by the LHS whose sole
6019 // purpose is to compute bits we don't care about.
6020 uint64_t KnownZero = 0, KnownOne = 0;
Chris Lattner03c49532007-01-15 02:27:26 +00006021 if (SimplifyDemandedBits(&CI, DestTy->getIntegerTypeMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006022 KnownZero, KnownOne))
6023 return &CI;
6024
6025 // If the source isn't an instruction or has more than one use then we
6026 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006027 Instruction *SrcI = dyn_cast<Instruction>(Src);
6028 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006029 return 0;
6030
6031 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006032 int NumCastsRemoved = 0;
6033 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6034 // If this cast is a truncate, evaluting in a different type always
6035 // eliminates the cast, so it is always a win. If this is a noop-cast
6036 // this just removes a noop cast which isn't pointful, but simplifies
6037 // the code. If this is a zero-extension, we need to do an AND to
6038 // maintain the clear top-part of the computation, so we require that
6039 // the input have eliminated at least one cast. If this is a sign
6040 // extension, we insert two new casts (to do the extension) so we
6041 // require that two casts have been eliminated.
6042 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6043 if (!DoXForm) {
6044 switch (CI.getOpcode()) {
6045 case Instruction::Trunc:
6046 DoXForm = true;
6047 break;
6048 case Instruction::ZExt:
6049 DoXForm = NumCastsRemoved >= 1;
6050 break;
6051 case Instruction::SExt:
6052 DoXForm = NumCastsRemoved >= 2;
6053 break;
6054 case Instruction::BitCast:
6055 DoXForm = false;
6056 break;
6057 default:
6058 // All the others use floating point so we shouldn't actually
6059 // get here because of the check above.
6060 assert(!"Unknown cast type .. unreachable");
6061 break;
6062 }
6063 }
6064
6065 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006066 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6067 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006068 assert(Res->getType() == DestTy);
6069 switch (CI.getOpcode()) {
6070 default: assert(0 && "Unknown cast type!");
6071 case Instruction::Trunc:
6072 case Instruction::BitCast:
6073 // Just replace this cast with the result.
6074 return ReplaceInstUsesWith(CI, Res);
6075 case Instruction::ZExt: {
6076 // We need to emit an AND to clear the high bits.
6077 assert(SrcBitSize < DestBitSize && "Not a zext?");
6078 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006079 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006080 if (DestBitSize < 64)
6081 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006082 return BinaryOperator::createAnd(Res, C);
6083 }
6084 case Instruction::SExt:
6085 // We need to emit a cast to truncate, then a cast to sext.
6086 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006087 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6088 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006089 }
6090 }
6091 }
6092
6093 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6094 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6095
6096 switch (SrcI->getOpcode()) {
6097 case Instruction::Add:
6098 case Instruction::Mul:
6099 case Instruction::And:
6100 case Instruction::Or:
6101 case Instruction::Xor:
6102 // If we are discarding information, or just changing the sign,
6103 // rewrite.
6104 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6105 // Don't insert two casts if they cannot be eliminated. We allow
6106 // two casts to be inserted if the sizes are the same. This could
6107 // only be converting signedness, which is a noop.
6108 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006109 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6110 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006111 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006112 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6113 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6114 return BinaryOperator::create(
6115 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006116 }
6117 }
6118
6119 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6120 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6121 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006122 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006123 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006124 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006125 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6126 }
6127 break;
6128 case Instruction::SDiv:
6129 case Instruction::UDiv:
6130 case Instruction::SRem:
6131 case Instruction::URem:
6132 // If we are just changing the sign, rewrite.
6133 if (DestBitSize == SrcBitSize) {
6134 // Don't insert two casts if they cannot be eliminated. We allow
6135 // two casts to be inserted if the sizes are the same. This could
6136 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006137 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6138 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006139 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6140 Op0, DestTy, SrcI);
6141 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6142 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006143 return BinaryOperator::create(
6144 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6145 }
6146 }
6147 break;
6148
6149 case Instruction::Shl:
6150 // Allow changing the sign of the source operand. Do not allow
6151 // changing the size of the shift, UNLESS the shift amount is a
6152 // constant. We must not change variable sized shifts to a smaller
6153 // size, because it is undefined to shift more bits out than exist
6154 // in the value.
6155 if (DestBitSize == SrcBitSize ||
6156 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006157 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6158 Instruction::BitCast : Instruction::Trunc);
6159 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006160 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6161 }
6162 break;
6163 case Instruction::AShr:
6164 // If this is a signed shr, and if all bits shifted in are about to be
6165 // truncated off, turn it into an unsigned shr to allow greater
6166 // simplifications.
6167 if (DestBitSize < SrcBitSize &&
6168 isa<ConstantInt>(Op1)) {
6169 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6170 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6171 // Insert the new logical shift right.
6172 return new ShiftInst(Instruction::LShr, Op0, Op1);
6173 }
6174 }
6175 break;
6176
Reid Spencer266e42b2006-12-23 06:05:41 +00006177 case Instruction::ICmp:
6178 // If we are just checking for a icmp eq of a single bit and casting it
6179 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006180 // cast to integer to avoid the comparison.
6181 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6182 uint64_t Op1CV = Op1C->getZExtValue();
6183 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6184 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6185 // cast (X == 1) to int --> X iff X has only the low bit set.
6186 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6187 // cast (X != 0) to int --> X iff X has only the low bit set.
6188 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6189 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6190 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6191 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6192 // If Op1C some other power of two, convert:
6193 uint64_t KnownZero, KnownOne;
Chris Lattner03c49532007-01-15 02:27:26 +00006194 uint64_t TypeMask = Op1->getType()->getIntegerTypeMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006195 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006196
6197 // This only works for EQ and NE
6198 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6199 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6200 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006201
6202 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006203 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006204 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6205 // (X&4) == 2 --> false
6206 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006207 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006208 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006209 return ReplaceInstUsesWith(CI, Res);
6210 }
6211
6212 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6213 Value *In = Op0;
6214 if (ShiftAmt) {
6215 // Perform a logical shr by shiftamt.
6216 // Insert the shift to put the result in the low bit.
6217 In = InsertNewInstBefore(
6218 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006219 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006220 In->getName()+".lobit"), CI);
6221 }
6222
Reid Spencer266e42b2006-12-23 06:05:41 +00006223 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006224 Constant *One = ConstantInt::get(In->getType(), 1);
6225 In = BinaryOperator::createXor(In, One, "tmp");
6226 InsertNewInstBefore(cast<Instruction>(In), CI);
6227 }
6228
6229 if (CI.getType() == In->getType())
6230 return ReplaceInstUsesWith(CI, In);
6231 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006232 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006233 }
6234 }
6235 }
6236 break;
6237 }
6238 return 0;
6239}
6240
6241Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006242 if (Instruction *Result = commonIntCastTransforms(CI))
6243 return Result;
6244
6245 Value *Src = CI.getOperand(0);
6246 const Type *Ty = CI.getType();
6247 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6248
6249 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6250 switch (SrcI->getOpcode()) {
6251 default: break;
6252 case Instruction::LShr:
6253 // We can shrink lshr to something smaller if we know the bits shifted in
6254 // are already zeros.
6255 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6256 unsigned ShAmt = ShAmtV->getZExtValue();
6257
6258 // Get a mask for the bits shifting in.
6259 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006260 Value* SrcIOp0 = SrcI->getOperand(0);
6261 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006262 if (ShAmt >= DestBitWidth) // All zeros.
6263 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6264
6265 // Okay, we can shrink this. Truncate the input, then return a new
6266 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006267 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006268 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6269 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006270 } else { // This is a variable shr.
6271
6272 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6273 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6274 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006275 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006276 Value *One = ConstantInt::get(SrcI->getType(), 1);
6277
6278 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6279 SrcI->getOperand(1),
6280 "tmp"), CI);
6281 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6282 SrcI->getOperand(0),
6283 "tmp"), CI);
6284 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006285 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006286 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006287 }
6288 break;
6289 }
6290 }
6291
6292 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006293}
6294
6295Instruction *InstCombiner::visitZExt(CastInst &CI) {
6296 // If one of the common conversion will work ..
6297 if (Instruction *Result = commonIntCastTransforms(CI))
6298 return Result;
6299
6300 Value *Src = CI.getOperand(0);
6301
6302 // If this is a cast of a cast
6303 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006304 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6305 // types and if the sizes are just right we can convert this into a logical
6306 // 'and' which will be much cheaper than the pair of casts.
6307 if (isa<TruncInst>(CSrc)) {
6308 // Get the sizes of the types involved
6309 Value *A = CSrc->getOperand(0);
6310 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6311 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6312 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6313 // If we're actually extending zero bits and the trunc is a no-op
6314 if (MidSize < DstSize && SrcSize == DstSize) {
6315 // Replace both of the casts with an And of the type mask.
Chris Lattner03c49532007-01-15 02:27:26 +00006316 uint64_t AndValue = CSrc->getType()->getIntegerTypeMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006317 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6318 Instruction *And =
6319 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6320 // Unfortunately, if the type changed, we need to cast it back.
6321 if (And->getType() != CI.getType()) {
6322 And->setName(CSrc->getName()+".mask");
6323 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006324 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006325 }
6326 return And;
6327 }
6328 }
6329 }
6330
6331 return 0;
6332}
6333
6334Instruction *InstCombiner::visitSExt(CastInst &CI) {
6335 return commonIntCastTransforms(CI);
6336}
6337
6338Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6339 return commonCastTransforms(CI);
6340}
6341
6342Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6343 return commonCastTransforms(CI);
6344}
6345
6346Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006347 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006348}
6349
6350Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006351 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006352}
6353
6354Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6355 return commonCastTransforms(CI);
6356}
6357
6358Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6359 return commonCastTransforms(CI);
6360}
6361
6362Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006363 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006364}
6365
6366Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6367 return commonCastTransforms(CI);
6368}
6369
6370Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6371
6372 // If the operands are integer typed then apply the integer transforms,
6373 // otherwise just apply the common ones.
6374 Value *Src = CI.getOperand(0);
6375 const Type *SrcTy = Src->getType();
6376 const Type *DestTy = CI.getType();
6377
Chris Lattner03c49532007-01-15 02:27:26 +00006378 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006379 if (Instruction *Result = commonIntCastTransforms(CI))
6380 return Result;
6381 } else {
6382 if (Instruction *Result = commonCastTransforms(CI))
6383 return Result;
6384 }
6385
6386
6387 // Get rid of casts from one type to the same type. These are useless and can
6388 // be replaced by the operand.
6389 if (DestTy == Src->getType())
6390 return ReplaceInstUsesWith(CI, Src);
6391
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006392 // If the source and destination are pointers, and this cast is equivalent to
6393 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6394 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006395 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6396 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6397 const Type *DstElTy = DstPTy->getElementType();
6398 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006399
Reid Spencerc635f472006-12-31 05:48:39 +00006400 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006401 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006402 while (SrcElTy != DstElTy &&
6403 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6404 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6405 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006406 ++NumZeros;
6407 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006408
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006409 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006410 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006411 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6412 return new GetElementPtrInst(Src, Idxs);
6413 }
6414 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006415 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006416
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006417 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6418 if (SVI->hasOneUse()) {
6419 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6420 // a bitconvert to a vector with the same # elts.
6421 if (isa<PackedType>(DestTy) &&
6422 cast<PackedType>(DestTy)->getNumElements() ==
6423 SVI->getType()->getNumElements()) {
6424 CastInst *Tmp;
6425 // If either of the operands is a cast from CI.getType(), then
6426 // evaluating the shuffle in the casted destination's type will allow
6427 // us to eliminate at least one cast.
6428 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6429 Tmp->getOperand(0)->getType() == DestTy) ||
6430 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6431 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006432 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6433 SVI->getOperand(0), DestTy, &CI);
6434 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6435 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006436 // Return a new shuffle vector. Use the same element ID's, as we
6437 // know the vector types match #elts.
6438 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006439 }
6440 }
6441 }
6442 }
Chris Lattner260ab202002-04-18 17:39:14 +00006443 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006444}
6445
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006446/// GetSelectFoldableOperands - We want to turn code that looks like this:
6447/// %C = or %A, %B
6448/// %D = select %cond, %C, %A
6449/// into:
6450/// %C = select %cond, %B, 0
6451/// %D = or %A, %C
6452///
6453/// Assuming that the specified instruction is an operand to the select, return
6454/// a bitmask indicating which operands of this instruction are foldable if they
6455/// equal the other incoming value of the select.
6456///
6457static unsigned GetSelectFoldableOperands(Instruction *I) {
6458 switch (I->getOpcode()) {
6459 case Instruction::Add:
6460 case Instruction::Mul:
6461 case Instruction::And:
6462 case Instruction::Or:
6463 case Instruction::Xor:
6464 return 3; // Can fold through either operand.
6465 case Instruction::Sub: // Can only fold on the amount subtracted.
6466 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006467 case Instruction::LShr:
6468 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006469 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006470 default:
6471 return 0; // Cannot fold
6472 }
6473}
6474
6475/// GetSelectFoldableConstant - For the same transformation as the previous
6476/// function, return the identity constant that goes into the select.
6477static Constant *GetSelectFoldableConstant(Instruction *I) {
6478 switch (I->getOpcode()) {
6479 default: assert(0 && "This cannot happen!"); abort();
6480 case Instruction::Add:
6481 case Instruction::Sub:
6482 case Instruction::Or:
6483 case Instruction::Xor:
6484 return Constant::getNullValue(I->getType());
6485 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006486 case Instruction::LShr:
6487 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006488 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006489 case Instruction::And:
6490 return ConstantInt::getAllOnesValue(I->getType());
6491 case Instruction::Mul:
6492 return ConstantInt::get(I->getType(), 1);
6493 }
6494}
6495
Chris Lattner411336f2005-01-19 21:50:18 +00006496/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6497/// have the same opcode and only one use each. Try to simplify this.
6498Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6499 Instruction *FI) {
6500 if (TI->getNumOperands() == 1) {
6501 // If this is a non-volatile load or a cast from the same type,
6502 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006503 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006504 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6505 return 0;
6506 } else {
6507 return 0; // unknown unary op.
6508 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006509
Chris Lattner411336f2005-01-19 21:50:18 +00006510 // Fold this by inserting a select from the input values.
6511 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6512 FI->getOperand(0), SI.getName()+".v");
6513 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006514 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6515 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006516 }
6517
Reid Spencer266e42b2006-12-23 06:05:41 +00006518 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006519 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006520 return 0;
6521
6522 // Figure out if the operations have any operands in common.
6523 Value *MatchOp, *OtherOpT, *OtherOpF;
6524 bool MatchIsOpZero;
6525 if (TI->getOperand(0) == FI->getOperand(0)) {
6526 MatchOp = TI->getOperand(0);
6527 OtherOpT = TI->getOperand(1);
6528 OtherOpF = FI->getOperand(1);
6529 MatchIsOpZero = true;
6530 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6531 MatchOp = TI->getOperand(1);
6532 OtherOpT = TI->getOperand(0);
6533 OtherOpF = FI->getOperand(0);
6534 MatchIsOpZero = false;
6535 } else if (!TI->isCommutative()) {
6536 return 0;
6537 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6538 MatchOp = TI->getOperand(0);
6539 OtherOpT = TI->getOperand(1);
6540 OtherOpF = FI->getOperand(0);
6541 MatchIsOpZero = true;
6542 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6543 MatchOp = TI->getOperand(1);
6544 OtherOpT = TI->getOperand(0);
6545 OtherOpF = FI->getOperand(1);
6546 MatchIsOpZero = true;
6547 } else {
6548 return 0;
6549 }
6550
6551 // If we reach here, they do have operations in common.
6552 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6553 OtherOpF, SI.getName()+".v");
6554 InsertNewInstBefore(NewSI, SI);
6555
6556 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6557 if (MatchIsOpZero)
6558 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6559 else
6560 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006561 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006562
6563 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6564 if (MatchIsOpZero)
6565 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6566 else
6567 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006568}
6569
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006570Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006571 Value *CondVal = SI.getCondition();
6572 Value *TrueVal = SI.getTrueValue();
6573 Value *FalseVal = SI.getFalseValue();
6574
6575 // select true, X, Y -> X
6576 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006577 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006578 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006579
6580 // select C, X, X -> X
6581 if (TrueVal == FalseVal)
6582 return ReplaceInstUsesWith(SI, TrueVal);
6583
Chris Lattner81a7a232004-10-16 18:11:37 +00006584 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6585 return ReplaceInstUsesWith(SI, FalseVal);
6586 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6587 return ReplaceInstUsesWith(SI, TrueVal);
6588 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6589 if (isa<Constant>(TrueVal))
6590 return ReplaceInstUsesWith(SI, TrueVal);
6591 else
6592 return ReplaceInstUsesWith(SI, FalseVal);
6593 }
6594
Reid Spencer542964f2007-01-11 18:21:29 +00006595 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006596 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006597 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006598 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006599 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006600 } else {
6601 // Change: A = select B, false, C --> A = and !B, C
6602 Value *NotCond =
6603 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6604 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006605 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006606 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006607 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006608 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006609 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006610 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006611 } else {
6612 // Change: A = select B, C, true --> A = or !B, C
6613 Value *NotCond =
6614 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6615 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006616 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006617 }
6618 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006619 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006620
Chris Lattner183b3362004-04-09 19:05:30 +00006621 // Selecting between two integer constants?
6622 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6623 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6624 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006625 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006626 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006627 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006628 // select C, 0, 1 -> cast !C to int
6629 Value *NotCond =
6630 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006631 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006632 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006633 }
Chris Lattner35167c32004-06-09 07:59:58 +00006634
Reid Spencer266e42b2006-12-23 06:05:41 +00006635 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006636
Reid Spencer266e42b2006-12-23 06:05:41 +00006637 // (x <s 0) ? -1 : 0 -> ashr x, 31
6638 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006639 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6640 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6641 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006642 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006643 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006644 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006645 else {
6646 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006647 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006648 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006649 }
6650
6651 if (CanXForm) {
6652 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006653 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006654 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006655 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006656 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006657 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006658 ShAmt, "ones");
6659 InsertNewInstBefore(SRA, SI);
6660
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006661 // Finally, convert to the type of the select RHS. We figure out
6662 // if this requires a SExt, Trunc or BitCast based on the sizes.
6663 Instruction::CastOps opc = Instruction::BitCast;
6664 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6665 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6666 if (SRASize < SISize)
6667 opc = Instruction::SExt;
6668 else if (SRASize > SISize)
6669 opc = Instruction::Trunc;
6670 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006671 }
6672 }
6673
6674
6675 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006676 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006677 // non-constant value, eliminate this whole mess. This corresponds to
6678 // cases like this: ((X & 27) ? 27 : 0)
6679 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006680 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006681 cast<Constant>(IC->getOperand(1))->isNullValue())
6682 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6683 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006684 isa<ConstantInt>(ICA->getOperand(1)) &&
6685 (ICA->getOperand(1) == TrueValC ||
6686 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006687 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6688 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006689 // know whether we have a icmp_ne or icmp_eq and whether the
6690 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006691 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006692 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006693 Value *V = ICA;
6694 if (ShouldNotVal)
6695 V = InsertNewInstBefore(BinaryOperator::create(
6696 Instruction::Xor, V, ICA->getOperand(1)), SI);
6697 return ReplaceInstUsesWith(SI, V);
6698 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006699 }
Chris Lattner533bc492004-03-30 19:37:13 +00006700 }
Chris Lattner623fba12004-04-10 22:21:27 +00006701
6702 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006703 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6704 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006705 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006706 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006707 return ReplaceInstUsesWith(SI, FalseVal);
6708 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006709 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006710 return ReplaceInstUsesWith(SI, TrueVal);
6711 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6712
Reid Spencer266e42b2006-12-23 06:05:41 +00006713 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006714 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006715 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006716 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006717 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006718 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6719 return ReplaceInstUsesWith(SI, TrueVal);
6720 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6721 }
6722 }
6723
6724 // See if we are selecting two values based on a comparison of the two values.
6725 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6726 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6727 // Transform (X == Y) ? X : Y -> Y
6728 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6729 return ReplaceInstUsesWith(SI, FalseVal);
6730 // Transform (X != Y) ? X : Y -> X
6731 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6732 return ReplaceInstUsesWith(SI, TrueVal);
6733 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6734
6735 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6736 // Transform (X == Y) ? Y : X -> X
6737 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6738 return ReplaceInstUsesWith(SI, FalseVal);
6739 // Transform (X != Y) ? Y : X -> Y
6740 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006741 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006742 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6743 }
6744 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006745
Chris Lattnera04c9042005-01-13 22:52:24 +00006746 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6747 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6748 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006749 Instruction *AddOp = 0, *SubOp = 0;
6750
Chris Lattner411336f2005-01-19 21:50:18 +00006751 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6752 if (TI->getOpcode() == FI->getOpcode())
6753 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6754 return IV;
6755
6756 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6757 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006758 if (TI->getOpcode() == Instruction::Sub &&
6759 FI->getOpcode() == Instruction::Add) {
6760 AddOp = FI; SubOp = TI;
6761 } else if (FI->getOpcode() == Instruction::Sub &&
6762 TI->getOpcode() == Instruction::Add) {
6763 AddOp = TI; SubOp = FI;
6764 }
6765
6766 if (AddOp) {
6767 Value *OtherAddOp = 0;
6768 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6769 OtherAddOp = AddOp->getOperand(1);
6770 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6771 OtherAddOp = AddOp->getOperand(0);
6772 }
6773
6774 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006775 // So at this point we know we have (Y -> OtherAddOp):
6776 // select C, (add X, Y), (sub X, Z)
6777 Value *NegVal; // Compute -Z
6778 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6779 NegVal = ConstantExpr::getNeg(C);
6780 } else {
6781 NegVal = InsertNewInstBefore(
6782 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006783 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006784
6785 Value *NewTrueOp = OtherAddOp;
6786 Value *NewFalseOp = NegVal;
6787 if (AddOp != TI)
6788 std::swap(NewTrueOp, NewFalseOp);
6789 Instruction *NewSel =
6790 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6791
6792 NewSel = InsertNewInstBefore(NewSel, SI);
6793 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006794 }
6795 }
6796 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006797
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006798 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006799 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006800 // See the comment above GetSelectFoldableOperands for a description of the
6801 // transformation we are doing here.
6802 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6803 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6804 !isa<Constant>(FalseVal))
6805 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6806 unsigned OpToFold = 0;
6807 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6808 OpToFold = 1;
6809 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6810 OpToFold = 2;
6811 }
6812
6813 if (OpToFold) {
6814 Constant *C = GetSelectFoldableConstant(TVI);
6815 std::string Name = TVI->getName(); TVI->setName("");
6816 Instruction *NewSel =
6817 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6818 Name);
6819 InsertNewInstBefore(NewSel, SI);
6820 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6821 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6822 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6823 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6824 else {
6825 assert(0 && "Unknown instruction!!");
6826 }
6827 }
6828 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006829
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006830 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6831 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6832 !isa<Constant>(TrueVal))
6833 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6834 unsigned OpToFold = 0;
6835 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6836 OpToFold = 1;
6837 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6838 OpToFold = 2;
6839 }
6840
6841 if (OpToFold) {
6842 Constant *C = GetSelectFoldableConstant(FVI);
6843 std::string Name = FVI->getName(); FVI->setName("");
6844 Instruction *NewSel =
6845 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6846 Name);
6847 InsertNewInstBefore(NewSel, SI);
6848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6849 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6850 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6851 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6852 else {
6853 assert(0 && "Unknown instruction!!");
6854 }
6855 }
6856 }
6857 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006858
6859 if (BinaryOperator::isNot(CondVal)) {
6860 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6861 SI.setOperand(1, FalseVal);
6862 SI.setOperand(2, TrueVal);
6863 return &SI;
6864 }
6865
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006866 return 0;
6867}
6868
Chris Lattner82f2ef22006-03-06 20:18:44 +00006869/// GetKnownAlignment - If the specified pointer has an alignment that we can
6870/// determine, return it, otherwise return 0.
6871static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6872 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6873 unsigned Align = GV->getAlignment();
6874 if (Align == 0 && TD)
6875 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6876 return Align;
6877 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6878 unsigned Align = AI->getAlignment();
6879 if (Align == 0 && TD) {
6880 if (isa<AllocaInst>(AI))
6881 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6882 else if (isa<MallocInst>(AI)) {
6883 // Malloc returns maximally aligned memory.
6884 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6885 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc635f472006-12-31 05:48:39 +00006886 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006887 }
6888 }
6889 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006890 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006891 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006892 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006893 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006894 if (isa<PointerType>(CI->getOperand(0)->getType()))
6895 return GetKnownAlignment(CI->getOperand(0), TD);
6896 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006897 } else if (isa<GetElementPtrInst>(V) ||
6898 (isa<ConstantExpr>(V) &&
6899 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6900 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006901 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6902 if (BaseAlignment == 0) return 0;
6903
6904 // If all indexes are zero, it is just the alignment of the base pointer.
6905 bool AllZeroOperands = true;
6906 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6907 if (!isa<Constant>(GEPI->getOperand(i)) ||
6908 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6909 AllZeroOperands = false;
6910 break;
6911 }
6912 if (AllZeroOperands)
6913 return BaseAlignment;
6914
6915 // Otherwise, if the base alignment is >= the alignment we expect for the
6916 // base pointer type, then we know that the resultant pointer is aligned at
6917 // least as much as its type requires.
6918 if (!TD) return 0;
6919
6920 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6921 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006922 <= BaseAlignment) {
6923 const Type *GEPTy = GEPI->getType();
6924 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6925 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006926 return 0;
6927 }
6928 return 0;
6929}
6930
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006931
Chris Lattnerc66b2232006-01-13 20:11:04 +00006932/// visitCallInst - CallInst simplification. This mostly only handles folding
6933/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6934/// the heavy lifting.
6935///
Chris Lattner970c33a2003-06-19 17:00:31 +00006936Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006937 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6938 if (!II) return visitCallSite(&CI);
6939
Chris Lattner51ea1272004-02-28 05:22:00 +00006940 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6941 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006942 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006943 bool Changed = false;
6944
6945 // memmove/cpy/set of zero bytes is a noop.
6946 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6947 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6948
Chris Lattner00648e12004-10-12 04:52:52 +00006949 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006950 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006951 // Replace the instruction with just byte operations. We would
6952 // transform other cases to loads/stores, but we don't know if
6953 // alignment is sufficient.
6954 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006955 }
6956
Chris Lattner00648e12004-10-12 04:52:52 +00006957 // If we have a memmove and the source operation is a constant global,
6958 // then the source and dest pointers can't alias, so we can change this
6959 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006960 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006961 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6962 if (GVSrc->isConstant()) {
6963 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006964 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006965 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006966 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006967 Name = "llvm.memcpy.i32";
6968 else
6969 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00006970 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006971 CI.getCalledFunction()->getFunctionType());
6972 CI.setOperand(0, MemCpy);
6973 Changed = true;
6974 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006975 }
Chris Lattner00648e12004-10-12 04:52:52 +00006976
Chris Lattner82f2ef22006-03-06 20:18:44 +00006977 // If we can determine a pointer alignment that is bigger than currently
6978 // set, update the alignment.
6979 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6980 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6981 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6982 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006983 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006984 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006985 Changed = true;
6986 }
6987 } else if (isa<MemSetInst>(MI)) {
6988 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006989 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00006990 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006991 Changed = true;
6992 }
6993 }
6994
Chris Lattnerc66b2232006-01-13 20:11:04 +00006995 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006996 } else {
6997 switch (II->getIntrinsicID()) {
6998 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006999 case Intrinsic::ppc_altivec_lvx:
7000 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007001 case Intrinsic::x86_sse_loadu_ps:
7002 case Intrinsic::x86_sse2_loadu_pd:
7003 case Intrinsic::x86_sse2_loadu_dq:
7004 // Turn PPC lvx -> load if the pointer is known aligned.
7005 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007006 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007007 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007008 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007009 return new LoadInst(Ptr);
7010 }
7011 break;
7012 case Intrinsic::ppc_altivec_stvx:
7013 case Intrinsic::ppc_altivec_stvxl:
7014 // Turn stvx -> store if the pointer is known aligned.
7015 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007016 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007017 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7018 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007019 return new StoreInst(II->getOperand(1), Ptr);
7020 }
7021 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007022 case Intrinsic::x86_sse_storeu_ps:
7023 case Intrinsic::x86_sse2_storeu_pd:
7024 case Intrinsic::x86_sse2_storeu_dq:
7025 case Intrinsic::x86_sse2_storel_dq:
7026 // Turn X86 storeu -> store if the pointer is known aligned.
7027 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7028 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007029 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7030 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007031 return new StoreInst(II->getOperand(2), Ptr);
7032 }
7033 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007034
7035 case Intrinsic::x86_sse_cvttss2si: {
7036 // These intrinsics only demands the 0th element of its input vector. If
7037 // we can simplify the input based on that, do so now.
7038 uint64_t UndefElts;
7039 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7040 UndefElts)) {
7041 II->setOperand(1, V);
7042 return II;
7043 }
7044 break;
7045 }
7046
Chris Lattnere79d2492006-04-06 19:19:17 +00007047 case Intrinsic::ppc_altivec_vperm:
7048 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7049 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7050 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7051
7052 // Check that all of the elements are integer constants or undefs.
7053 bool AllEltsOk = true;
7054 for (unsigned i = 0; i != 16; ++i) {
7055 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7056 !isa<UndefValue>(Mask->getOperand(i))) {
7057 AllEltsOk = false;
7058 break;
7059 }
7060 }
7061
7062 if (AllEltsOk) {
7063 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007064 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7065 II->getOperand(1), Mask->getType(), CI);
7066 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7067 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007068 Value *Result = UndefValue::get(Op0->getType());
7069
7070 // Only extract each element once.
7071 Value *ExtractedElts[32];
7072 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7073
7074 for (unsigned i = 0; i != 16; ++i) {
7075 if (isa<UndefValue>(Mask->getOperand(i)))
7076 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007077 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007078 Idx &= 31; // Match the hardware behavior.
7079
7080 if (ExtractedElts[Idx] == 0) {
7081 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007082 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007083 InsertNewInstBefore(Elt, CI);
7084 ExtractedElts[Idx] = Elt;
7085 }
7086
7087 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007088 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007089 InsertNewInstBefore(cast<Instruction>(Result), CI);
7090 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007091 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007092 }
7093 }
7094 break;
7095
Chris Lattner503221f2006-01-13 21:28:09 +00007096 case Intrinsic::stackrestore: {
7097 // If the save is right next to the restore, remove the restore. This can
7098 // happen when variable allocas are DCE'd.
7099 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7100 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7101 BasicBlock::iterator BI = SS;
7102 if (&*++BI == II)
7103 return EraseInstFromFunction(CI);
7104 }
7105 }
7106
7107 // If the stack restore is in a return/unwind block and if there are no
7108 // allocas or calls between the restore and the return, nuke the restore.
7109 TerminatorInst *TI = II->getParent()->getTerminator();
7110 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7111 BasicBlock::iterator BI = II;
7112 bool CannotRemove = false;
7113 for (++BI; &*BI != TI; ++BI) {
7114 if (isa<AllocaInst>(BI) ||
7115 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7116 CannotRemove = true;
7117 break;
7118 }
7119 }
7120 if (!CannotRemove)
7121 return EraseInstFromFunction(CI);
7122 }
7123 break;
7124 }
7125 }
Chris Lattner00648e12004-10-12 04:52:52 +00007126 }
7127
Chris Lattnerc66b2232006-01-13 20:11:04 +00007128 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007129}
7130
7131// InvokeInst simplification
7132//
7133Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007134 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007135}
7136
Chris Lattneraec3d942003-10-07 22:32:43 +00007137// visitCallSite - Improvements for call and invoke instructions.
7138//
7139Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007140 bool Changed = false;
7141
7142 // If the callee is a constexpr cast of a function, attempt to move the cast
7143 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007144 if (transformConstExprCastCall(CS)) return 0;
7145
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007146 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007147
Chris Lattner61d9d812005-05-13 07:09:09 +00007148 if (Function *CalleeF = dyn_cast<Function>(Callee))
7149 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7150 Instruction *OldCall = CS.getInstruction();
7151 // If the call and callee calling conventions don't match, this call must
7152 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007153 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007154 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007155 if (!OldCall->use_empty())
7156 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7157 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7158 return EraseInstFromFunction(*OldCall);
7159 return 0;
7160 }
7161
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007162 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7163 // This instruction is not reachable, just remove it. We insert a store to
7164 // undef so that we know that this code is not reachable, despite the fact
7165 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007166 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007167 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007168 CS.getInstruction());
7169
7170 if (!CS.getInstruction()->use_empty())
7171 CS.getInstruction()->
7172 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7173
7174 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7175 // Don't break the CFG, insert a dummy cond branch.
7176 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007177 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007178 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007179 return EraseInstFromFunction(*CS.getInstruction());
7180 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007181
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007182 const PointerType *PTy = cast<PointerType>(Callee->getType());
7183 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7184 if (FTy->isVarArg()) {
7185 // See if we can optimize any arguments passed through the varargs area of
7186 // the call.
7187 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7188 E = CS.arg_end(); I != E; ++I)
7189 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7190 // If this cast does not effect the value passed through the varargs
7191 // area, we can eliminate the use of the cast.
7192 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007193 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007194 *I = Op;
7195 Changed = true;
7196 }
7197 }
7198 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007199
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007200 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007201}
7202
Chris Lattner970c33a2003-06-19 17:00:31 +00007203// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7204// attempt to move the cast to the arguments of the call/invoke.
7205//
7206bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7207 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7208 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007209 if (CE->getOpcode() != Instruction::BitCast ||
7210 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007211 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007212 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007213 Instruction *Caller = CS.getInstruction();
7214
7215 // Okay, this is a cast from a function to a different type. Unless doing so
7216 // would cause a type conversion of one of our arguments, change this call to
7217 // be a direct call with arguments casted to the appropriate types.
7218 //
7219 const FunctionType *FT = Callee->getFunctionType();
7220 const Type *OldRetTy = Caller->getType();
7221
Chris Lattner1f7942f2004-01-14 06:06:08 +00007222 // Check to see if we are changing the return type...
7223 if (OldRetTy != FT->getReturnType()) {
Chris Lattner400f9592007-01-06 02:09:32 +00007224 if (Callee->isExternal() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007225 OldRetTy != FT->getReturnType() &&
7226 // Conversion is ok if changing from pointer to int of same size.
7227 !(isa<PointerType>(FT->getReturnType()) &&
7228 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007229 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007230
7231 // If the callsite is an invoke instruction, and the return value is used by
7232 // a PHI node in a successor, we cannot change the return type of the call
7233 // because there is no place to put the cast instruction (without breaking
7234 // the critical edge). Bail out in this case.
7235 if (!Caller->use_empty())
7236 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7237 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7238 UI != E; ++UI)
7239 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7240 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007241 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007242 return false;
7243 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007244
7245 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7246 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007247
Chris Lattner970c33a2003-06-19 17:00:31 +00007248 CallSite::arg_iterator AI = CS.arg_begin();
7249 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7250 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007251 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007252 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007253 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007254 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007255 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007256 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007257 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7258 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7259 && c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007260 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007261 }
7262
7263 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7264 Callee->isExternal())
7265 return false; // Do not delete arguments unless we have a function body...
7266
7267 // Okay, we decided that this is a safe thing to do: go ahead and start
7268 // inserting cast instructions as necessary...
7269 std::vector<Value*> Args;
7270 Args.reserve(NumActualArgs);
7271
7272 AI = CS.arg_begin();
7273 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7274 const Type *ParamTy = FT->getParamType(i);
7275 if ((*AI)->getType() == ParamTy) {
7276 Args.push_back(*AI);
7277 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007278 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007279 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007280 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007281 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007282 }
7283 }
7284
7285 // If the function takes more arguments than the call was taking, add them
7286 // now...
7287 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7288 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7289
7290 // If we are removing arguments to the function, emit an obnoxious warning...
7291 if (FT->getNumParams() < NumActualArgs)
7292 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007293 cerr << "WARNING: While resolving call to function '"
7294 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007295 } else {
7296 // Add all of the arguments in their promoted form to the arg list...
7297 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7298 const Type *PTy = getPromotedType((*AI)->getType());
7299 if (PTy != (*AI)->getType()) {
7300 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007301 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7302 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007303 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007304 InsertNewInstBefore(Cast, *Caller);
7305 Args.push_back(Cast);
7306 } else {
7307 Args.push_back(*AI);
7308 }
7309 }
7310 }
7311
7312 if (FT->getReturnType() == Type::VoidTy)
7313 Caller->setName(""); // Void type should not have a name...
7314
7315 Instruction *NC;
7316 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007317 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007318 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007319 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007320 } else {
7321 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007322 if (cast<CallInst>(Caller)->isTailCall())
7323 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007324 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007325 }
7326
7327 // Insert a cast of the return type as necessary...
7328 Value *NV = NC;
7329 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7330 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007331 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007332 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7333 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007334 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007335
7336 // If this is an invoke instruction, we should insert it after the first
7337 // non-phi, instruction in the normal successor block.
7338 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7339 BasicBlock::iterator I = II->getNormalDest()->begin();
7340 while (isa<PHINode>(I)) ++I;
7341 InsertNewInstBefore(NC, *I);
7342 } else {
7343 // Otherwise, it's a call, just insert cast right after the call instr
7344 InsertNewInstBefore(NC, *Caller);
7345 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007346 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007347 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007348 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007349 }
7350 }
7351
7352 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7353 Caller->replaceAllUsesWith(NV);
7354 Caller->getParent()->getInstList().erase(Caller);
7355 removeFromWorkList(Caller);
7356 return true;
7357}
7358
Chris Lattnercadac0c2006-11-01 04:51:18 +00007359/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7360/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7361/// and a single binop.
7362Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7363 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007364 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007365 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007366 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007367 Value *LHSVal = FirstInst->getOperand(0);
7368 Value *RHSVal = FirstInst->getOperand(1);
7369
7370 const Type *LHSType = LHSVal->getType();
7371 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007372
7373 // Scan to see if all operands are the same opcode, all have one use, and all
7374 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007375 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007376 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007377 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007378 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007379 // types or GEP's with different index types.
7380 I->getOperand(0)->getType() != LHSType ||
7381 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007382 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007383
7384 // If they are CmpInst instructions, check their predicates
7385 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7386 if (cast<CmpInst>(I)->getPredicate() !=
7387 cast<CmpInst>(FirstInst)->getPredicate())
7388 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007389
7390 // Keep track of which operand needs a phi node.
7391 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7392 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007393 }
7394
Chris Lattner4f218d52006-11-08 19:42:28 +00007395 // Otherwise, this is safe to transform, determine if it is profitable.
7396
7397 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7398 // Indexes are often folded into load/store instructions, so we don't want to
7399 // hide them behind a phi.
7400 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7401 return 0;
7402
Chris Lattnercadac0c2006-11-01 04:51:18 +00007403 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007404 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007405 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007406 if (LHSVal == 0) {
7407 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7408 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7409 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007410 InsertNewInstBefore(NewLHS, PN);
7411 LHSVal = NewLHS;
7412 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007413
7414 if (RHSVal == 0) {
7415 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7416 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7417 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007418 InsertNewInstBefore(NewRHS, PN);
7419 RHSVal = NewRHS;
7420 }
7421
Chris Lattnercd62f112006-11-08 19:29:23 +00007422 // Add all operands to the new PHIs.
7423 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7424 if (NewLHS) {
7425 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7426 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7427 }
7428 if (NewRHS) {
7429 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7430 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7431 }
7432 }
7433
Chris Lattnercadac0c2006-11-01 04:51:18 +00007434 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007435 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007436 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7437 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7438 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007439 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7440 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7441 else {
7442 assert(isa<GetElementPtrInst>(FirstInst));
7443 return new GetElementPtrInst(LHSVal, RHSVal);
7444 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007445}
7446
Chris Lattner14f82c72006-11-01 07:13:54 +00007447/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7448/// of the block that defines it. This means that it must be obvious the value
7449/// of the load is not changed from the point of the load to the end of the
7450/// block it is in.
7451static bool isSafeToSinkLoad(LoadInst *L) {
7452 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7453
7454 for (++BBI; BBI != E; ++BBI)
7455 if (BBI->mayWriteToMemory())
7456 return false;
7457 return true;
7458}
7459
Chris Lattner970c33a2003-06-19 17:00:31 +00007460
Chris Lattner7515cab2004-11-14 19:13:23 +00007461// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7462// operator and they all are only used by the PHI, PHI together their
7463// inputs, and do the operation once, to the result of the PHI.
7464Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7465 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7466
7467 // Scan the instruction, looking for input operations that can be folded away.
7468 // If all input operands to the phi are the same instruction (e.g. a cast from
7469 // the same type or "+42") we can pull the operation through the PHI, reducing
7470 // code size and simplifying code.
7471 Constant *ConstantOp = 0;
7472 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007473 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007474 if (isa<CastInst>(FirstInst)) {
7475 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007476 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7477 isa<CmpInst>(FirstInst)) {
7478 // Can fold binop, compare or shift here if the RHS is a constant,
7479 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007480 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007481 if (ConstantOp == 0)
7482 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007483 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7484 isVolatile = LI->isVolatile();
7485 // We can't sink the load if the loaded value could be modified between the
7486 // load and the PHI.
7487 if (LI->getParent() != PN.getIncomingBlock(0) ||
7488 !isSafeToSinkLoad(LI))
7489 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007490 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007491 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007492 return FoldPHIArgBinOpIntoPHI(PN);
7493 // Can't handle general GEPs yet.
7494 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007495 } else {
7496 return 0; // Cannot fold this operation.
7497 }
7498
7499 // Check to see if all arguments are the same operation.
7500 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7501 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7502 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007503 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007504 return 0;
7505 if (CastSrcTy) {
7506 if (I->getOperand(0)->getType() != CastSrcTy)
7507 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007508 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007509 // We can't sink the load if the loaded value could be modified between
7510 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007511 if (LI->isVolatile() != isVolatile ||
7512 LI->getParent() != PN.getIncomingBlock(i) ||
7513 !isSafeToSinkLoad(LI))
7514 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007515 } else if (I->getOperand(1) != ConstantOp) {
7516 return 0;
7517 }
7518 }
7519
7520 // Okay, they are all the same operation. Create a new PHI node of the
7521 // correct type, and PHI together all of the LHS's of the instructions.
7522 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7523 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007524 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007525
7526 Value *InVal = FirstInst->getOperand(0);
7527 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007528
7529 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007530 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7531 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7532 if (NewInVal != InVal)
7533 InVal = 0;
7534 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7535 }
7536
7537 Value *PhiVal;
7538 if (InVal) {
7539 // The new PHI unions all of the same values together. This is really
7540 // common, so we handle it intelligently here for compile-time speed.
7541 PhiVal = InVal;
7542 delete NewPN;
7543 } else {
7544 InsertNewInstBefore(NewPN, PN);
7545 PhiVal = NewPN;
7546 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007547
Chris Lattner7515cab2004-11-14 19:13:23 +00007548 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007549 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7550 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007551 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007552 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007553 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007554 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007555 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7556 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7557 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007558 else
7559 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007560 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007561}
Chris Lattner48a44f72002-05-02 17:06:02 +00007562
Chris Lattner71536432005-01-17 05:10:15 +00007563/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7564/// that is dead.
7565static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7566 if (PN->use_empty()) return true;
7567 if (!PN->hasOneUse()) return false;
7568
7569 // Remember this node, and if we find the cycle, return.
7570 if (!PotentiallyDeadPHIs.insert(PN).second)
7571 return true;
7572
7573 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7574 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007575
Chris Lattner71536432005-01-17 05:10:15 +00007576 return false;
7577}
7578
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007579// PHINode simplification
7580//
Chris Lattner113f4f42002-06-25 16:13:24 +00007581Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007582 // If LCSSA is around, don't mess with Phi nodes
7583 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007584
Owen Andersonae8aa642006-07-10 22:03:18 +00007585 if (Value *V = PN.hasConstantValue())
7586 return ReplaceInstUsesWith(PN, V);
7587
Owen Andersonae8aa642006-07-10 22:03:18 +00007588 // If all PHI operands are the same operation, pull them through the PHI,
7589 // reducing code size.
7590 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7591 PN.getIncomingValue(0)->hasOneUse())
7592 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7593 return Result;
7594
7595 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7596 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7597 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007598 if (PN.hasOneUse()) {
7599 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7600 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007601 std::set<PHINode*> PotentiallyDeadPHIs;
7602 PotentiallyDeadPHIs.insert(&PN);
7603 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7604 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7605 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007606
7607 // If this phi has a single use, and if that use just computes a value for
7608 // the next iteration of a loop, delete the phi. This occurs with unused
7609 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7610 // common case here is good because the only other things that catch this
7611 // are induction variable analysis (sometimes) and ADCE, which is only run
7612 // late.
7613 if (PHIUser->hasOneUse() &&
7614 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7615 PHIUser->use_back() == &PN) {
7616 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7617 }
7618 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007619
Chris Lattner91daeb52003-12-19 05:58:40 +00007620 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007621}
7622
Reid Spencer13bc5d72006-12-12 09:18:51 +00007623static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7624 Instruction *InsertPoint,
7625 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007626 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7627 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007628 // We must cast correctly to the pointer type. Ensure that we
7629 // sign extend the integer value if it is smaller as this is
7630 // used for address computation.
7631 Instruction::CastOps opcode =
7632 (VTySize < PtrSize ? Instruction::SExt :
7633 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7634 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007635}
7636
Chris Lattner48a44f72002-05-02 17:06:02 +00007637
Chris Lattner113f4f42002-06-25 16:13:24 +00007638Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007639 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007640 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007641 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007642 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007643 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007644
Chris Lattner81a7a232004-10-16 18:11:37 +00007645 if (isa<UndefValue>(GEP.getOperand(0)))
7646 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7647
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007648 bool HasZeroPointerIndex = false;
7649 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7650 HasZeroPointerIndex = C->isNullValue();
7651
7652 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007653 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007654
Chris Lattner69193f92004-04-05 01:30:19 +00007655 // Eliminate unneeded casts for indices.
7656 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007657 gep_type_iterator GTI = gep_type_begin(GEP);
7658 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7659 if (isa<SequentialType>(*GTI)) {
7660 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007661 if (CI->getOpcode() == Instruction::ZExt ||
7662 CI->getOpcode() == Instruction::SExt) {
7663 const Type *SrcTy = CI->getOperand(0)->getType();
7664 // We can eliminate a cast from i32 to i64 iff the target
7665 // is a 32-bit pointer target.
7666 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7667 MadeChange = true;
7668 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007669 }
7670 }
7671 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007672 // If we are using a wider index than needed for this platform, shrink it
7673 // to what we need. If the incoming value needs a cast instruction,
7674 // insert it. This explicit cast can make subsequent optimizations more
7675 // obvious.
7676 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007677 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007678 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007679 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007680 MadeChange = true;
7681 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007682 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7683 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007684 GEP.setOperand(i, Op);
7685 MadeChange = true;
7686 }
Chris Lattner69193f92004-04-05 01:30:19 +00007687 }
7688 if (MadeChange) return &GEP;
7689
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007690 // Combine Indices - If the source pointer to this getelementptr instruction
7691 // is a getelementptr instruction, combine the indices of the two
7692 // getelementptr instructions into a single instruction.
7693 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007694 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007695 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007696 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007697
7698 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007699 // Note that if our source is a gep chain itself that we wait for that
7700 // chain to be resolved before we perform this transformation. This
7701 // avoids us creating a TON of code in some cases.
7702 //
7703 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7704 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7705 return 0; // Wait until our source is folded to completion.
7706
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007707 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007708
7709 // Find out whether the last index in the source GEP is a sequential idx.
7710 bool EndsWithSequential = false;
7711 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7712 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007713 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007714
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007715 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007716 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007717 // Replace: gep (gep %P, long B), long A, ...
7718 // With: T = long A+B; gep %P, T, ...
7719 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007720 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007721 if (SO1 == Constant::getNullValue(SO1->getType())) {
7722 Sum = GO1;
7723 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7724 Sum = SO1;
7725 } else {
7726 // If they aren't the same type, convert both to an integer of the
7727 // target's pointer size.
7728 if (SO1->getType() != GO1->getType()) {
7729 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007730 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007731 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007732 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007733 } else {
7734 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007735 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007736 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007737 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007738
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007739 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007740 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007741 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007742 } else {
7743 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007744 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7745 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007746 }
7747 }
7748 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007749 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7750 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7751 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007752 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7753 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007754 }
Chris Lattner69193f92004-04-05 01:30:19 +00007755 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007756
7757 // Recycle the GEP we already have if possible.
7758 if (SrcGEPOperands.size() == 2) {
7759 GEP.setOperand(0, SrcGEPOperands[0]);
7760 GEP.setOperand(1, Sum);
7761 return &GEP;
7762 } else {
7763 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7764 SrcGEPOperands.end()-1);
7765 Indices.push_back(Sum);
7766 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7767 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007768 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007769 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007770 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007771 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007772 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7773 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007774 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7775 }
7776
7777 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007778 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007779
Chris Lattner5f667a62004-05-07 22:09:22 +00007780 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007781 // GEP of global variable. If all of the indices for this GEP are
7782 // constants, we can promote this to a constexpr instead of an instruction.
7783
7784 // Scan for nonconstants...
7785 std::vector<Constant*> Indices;
7786 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7787 for (; I != E && isa<Constant>(*I); ++I)
7788 Indices.push_back(cast<Constant>(*I));
7789
7790 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007791 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007792
7793 // Replace all uses of the GEP with the new constexpr...
7794 return ReplaceInstUsesWith(GEP, CE);
7795 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007796 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007797 if (!isa<PointerType>(X->getType())) {
7798 // Not interesting. Source pointer must be a cast from pointer.
7799 } else if (HasZeroPointerIndex) {
7800 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7801 // into : GEP [10 x ubyte]* X, long 0, ...
7802 //
7803 // This occurs when the program declares an array extern like "int X[];"
7804 //
7805 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7806 const PointerType *XTy = cast<PointerType>(X->getType());
7807 if (const ArrayType *XATy =
7808 dyn_cast<ArrayType>(XTy->getElementType()))
7809 if (const ArrayType *CATy =
7810 dyn_cast<ArrayType>(CPTy->getElementType()))
7811 if (CATy->getElementType() == XATy->getElementType()) {
7812 // At this point, we know that the cast source type is a pointer
7813 // to an array of the same type as the destination pointer
7814 // array. Because the array type is never stepped over (there
7815 // is a leading zero) we can fold the cast into this GEP.
7816 GEP.setOperand(0, X);
7817 return &GEP;
7818 }
7819 } else if (GEP.getNumOperands() == 2) {
7820 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007821 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7822 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007823 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7824 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7825 if (isa<ArrayType>(SrcElTy) &&
7826 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7827 TD->getTypeSize(ResElTy)) {
7828 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007829 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007830 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007831 // V and GEP are both pointer types --> BitCast
7832 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007833 }
Chris Lattner2a893292005-09-13 18:36:04 +00007834
7835 // Transform things like:
7836 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7837 // (where tmp = 8*tmp2) into:
7838 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7839
7840 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007841 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007842 uint64_t ArrayEltSize =
7843 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7844
7845 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7846 // allow either a mul, shift, or constant here.
7847 Value *NewIdx = 0;
7848 ConstantInt *Scale = 0;
7849 if (ArrayEltSize == 1) {
7850 NewIdx = GEP.getOperand(1);
7851 Scale = ConstantInt::get(NewIdx->getType(), 1);
7852 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007853 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007854 Scale = CI;
7855 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7856 if (Inst->getOpcode() == Instruction::Shl &&
7857 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007858 unsigned ShAmt =
7859 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007860 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007861 NewIdx = Inst->getOperand(0);
7862 } else if (Inst->getOpcode() == Instruction::Mul &&
7863 isa<ConstantInt>(Inst->getOperand(1))) {
7864 Scale = cast<ConstantInt>(Inst->getOperand(1));
7865 NewIdx = Inst->getOperand(0);
7866 }
7867 }
7868
7869 // If the index will be to exactly the right offset with the scale taken
7870 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007871 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007872 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007873 Scale = ConstantInt::get(Scale->getType(),
7874 Scale->getZExtValue() / ArrayEltSize);
7875 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007876 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7877 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007878 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7879 NewIdx = InsertNewInstBefore(Sc, GEP);
7880 }
7881
7882 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007883 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007884 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007885 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007886 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7887 // The NewGEP must be pointer typed, so must the old one -> BitCast
7888 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007889 }
7890 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007891 }
Chris Lattnerca081252001-12-14 16:52:21 +00007892 }
7893
Chris Lattnerca081252001-12-14 16:52:21 +00007894 return 0;
7895}
7896
Chris Lattner1085bdf2002-11-04 16:18:53 +00007897Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7898 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7899 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007900 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7901 const Type *NewTy =
7902 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007903 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007904
7905 // Create and insert the replacement instruction...
7906 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007907 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007908 else {
7909 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007910 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007911 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007912
7913 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007914
Chris Lattner1085bdf2002-11-04 16:18:53 +00007915 // Scan to the end of the allocation instructions, to skip over a block of
7916 // allocas if possible...
7917 //
7918 BasicBlock::iterator It = New;
7919 while (isa<AllocationInst>(*It)) ++It;
7920
7921 // Now that I is pointing to the first non-allocation-inst in the block,
7922 // insert our getelementptr instruction...
7923 //
Reid Spencerc635f472006-12-31 05:48:39 +00007924 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007925 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7926 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007927
7928 // Now make everything use the getelementptr instead of the original
7929 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007930 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007931 } else if (isa<UndefValue>(AI.getArraySize())) {
7932 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007933 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007934
7935 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7936 // Note that we only do this for alloca's, because malloc should allocate and
7937 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007938 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007939 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007940 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7941
Chris Lattner1085bdf2002-11-04 16:18:53 +00007942 return 0;
7943}
7944
Chris Lattner8427bff2003-12-07 01:24:23 +00007945Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7946 Value *Op = FI.getOperand(0);
7947
7948 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7949 if (CastInst *CI = dyn_cast<CastInst>(Op))
7950 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7951 FI.setOperand(0, CI->getOperand(0));
7952 return &FI;
7953 }
7954
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007955 // free undef -> unreachable.
7956 if (isa<UndefValue>(Op)) {
7957 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007958 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007959 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007960 return EraseInstFromFunction(FI);
7961 }
7962
Chris Lattnerf3a36602004-02-28 04:57:37 +00007963 // If we have 'free null' delete the instruction. This can happen in stl code
7964 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007965 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007966 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007967
Chris Lattner8427bff2003-12-07 01:24:23 +00007968 return 0;
7969}
7970
7971
Chris Lattner72684fe2005-01-31 05:51:45 +00007972/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007973static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7974 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007975 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007976
7977 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007978 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007979 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007980
Chris Lattner479a9fc2007-01-15 17:55:20 +00007981 if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
7982 isa<PointerType>(DestPTy) || isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007983 // If the source is an array, the code below will not succeed. Check to
7984 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7985 // constants.
7986 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7987 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7988 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00007989 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007990 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7991 SrcTy = cast<PointerType>(CastOp->getType());
7992 SrcPTy = SrcTy->getElementType();
7993 }
7994
Chris Lattner479a9fc2007-01-15 17:55:20 +00007995 if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
7996 isa<PointerType>(SrcPTy) || isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007997 // Do not allow turning this into a load of an integer, which is then
7998 // casted to a pointer, this pessimizes pointer analysis a lot.
7999 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008000 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008001 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008002
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008003 // Okay, we are casting from one integer or pointer type to another of
8004 // the same size. Instead of casting the pointer before the load, cast
8005 // the result of the loaded value.
8006 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8007 CI->getName(),
8008 LI.isVolatile()),LI);
8009 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008010 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008011 }
Chris Lattner35e24772004-07-13 01:49:43 +00008012 }
8013 }
8014 return 0;
8015}
8016
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008017/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008018/// from this value cannot trap. If it is not obviously safe to load from the
8019/// specified pointer, we do a quick local scan of the basic block containing
8020/// ScanFrom, to determine if the address is already accessed.
8021static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8022 // If it is an alloca or global variable, it is always safe to load from.
8023 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8024
8025 // Otherwise, be a little bit agressive by scanning the local block where we
8026 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008027 // from/to. If so, the previous load or store would have already trapped,
8028 // so there is no harm doing an extra load (also, CSE will later eliminate
8029 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008030 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8031
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008032 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008033 --BBI;
8034
8035 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8036 if (LI->getOperand(0) == V) return true;
8037 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8038 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008039
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008040 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008041 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008042}
8043
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008044Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8045 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008046
Chris Lattnera9d84e32005-05-01 04:24:53 +00008047 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008048 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008049 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8050 return Res;
8051
8052 // None of the following transforms are legal for volatile loads.
8053 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008054
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008055 if (&LI.getParent()->front() != &LI) {
8056 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008057 // If the instruction immediately before this is a store to the same
8058 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008059 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8060 if (SI->getOperand(1) == LI.getOperand(0))
8061 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008062 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8063 if (LIB->getOperand(0) == LI.getOperand(0))
8064 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008065 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008066
8067 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8068 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8069 isa<UndefValue>(GEPI->getOperand(0))) {
8070 // Insert a new store to null instruction before the load to indicate
8071 // that this code is not reachable. We do this instead of inserting
8072 // an unreachable instruction directly because we cannot modify the
8073 // CFG.
8074 new StoreInst(UndefValue::get(LI.getType()),
8075 Constant::getNullValue(Op->getType()), &LI);
8076 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8077 }
8078
Chris Lattner81a7a232004-10-16 18:11:37 +00008079 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008080 // load null/undef -> undef
8081 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008082 // Insert a new store to null instruction before the load to indicate that
8083 // this code is not reachable. We do this instead of inserting an
8084 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008085 new StoreInst(UndefValue::get(LI.getType()),
8086 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008087 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008088 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008089
Chris Lattner81a7a232004-10-16 18:11:37 +00008090 // Instcombine load (constant global) into the value loaded.
8091 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8092 if (GV->isConstant() && !GV->isExternal())
8093 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008094
Chris Lattner81a7a232004-10-16 18:11:37 +00008095 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8096 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8097 if (CE->getOpcode() == Instruction::GetElementPtr) {
8098 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8099 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008100 if (Constant *V =
8101 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008102 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008103 if (CE->getOperand(0)->isNullValue()) {
8104 // Insert a new store to null instruction before the load to indicate
8105 // that this code is not reachable. We do this instead of inserting
8106 // an unreachable instruction directly because we cannot modify the
8107 // CFG.
8108 new StoreInst(UndefValue::get(LI.getType()),
8109 Constant::getNullValue(Op->getType()), &LI);
8110 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8111 }
8112
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008113 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008114 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8115 return Res;
8116 }
8117 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008118
Chris Lattnera9d84e32005-05-01 04:24:53 +00008119 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008120 // Change select and PHI nodes to select values instead of addresses: this
8121 // helps alias analysis out a lot, allows many others simplifications, and
8122 // exposes redundancy in the code.
8123 //
8124 // Note that we cannot do the transformation unless we know that the
8125 // introduced loads cannot trap! Something like this is valid as long as
8126 // the condition is always false: load (select bool %C, int* null, int* %G),
8127 // but it would not be valid if we transformed it to load from null
8128 // unconditionally.
8129 //
8130 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8131 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008132 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8133 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008134 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008135 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008136 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008137 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008138 return new SelectInst(SI->getCondition(), V1, V2);
8139 }
8140
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008141 // load (select (cond, null, P)) -> load P
8142 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8143 if (C->isNullValue()) {
8144 LI.setOperand(0, SI->getOperand(2));
8145 return &LI;
8146 }
8147
8148 // load (select (cond, P, null)) -> load P
8149 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8150 if (C->isNullValue()) {
8151 LI.setOperand(0, SI->getOperand(1));
8152 return &LI;
8153 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008154 }
8155 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008156 return 0;
8157}
8158
Chris Lattner72684fe2005-01-31 05:51:45 +00008159/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8160/// when possible.
8161static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8162 User *CI = cast<User>(SI.getOperand(1));
8163 Value *CastOp = CI->getOperand(0);
8164
8165 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8166 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8167 const Type *SrcPTy = SrcTy->getElementType();
8168
Chris Lattner479a9fc2007-01-15 17:55:20 +00008169 if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
8170 isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008171 // If the source is an array, the code below will not succeed. Check to
8172 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8173 // constants.
8174 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8175 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8176 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008177 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008178 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8179 SrcTy = cast<PointerType>(CastOp->getType());
8180 SrcPTy = SrcTy->getElementType();
8181 }
8182
Chris Lattner479a9fc2007-01-15 17:55:20 +00008183 if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
8184 isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008185 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008186 IC.getTargetData().getTypeSize(DestPTy)) {
8187
8188 // Okay, we are casting from one integer or pointer type to another of
8189 // the same size. Instead of casting the pointer before the store, cast
8190 // the value to be stored.
8191 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008192 Instruction::CastOps opcode = Instruction::BitCast;
8193 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008194 if (isa<PointerType>(SrcPTy)) {
Chris Lattner03c49532007-01-15 02:27:26 +00008195 if (SIOp0->getType()->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008196 opcode = Instruction::IntToPtr;
Chris Lattner03c49532007-01-15 02:27:26 +00008197 } else if (SrcPTy->isInteger()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008198 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008199 opcode = Instruction::PtrToInt;
8200 }
8201 if (Constant *C = dyn_cast<Constant>(SIOp0))
8202 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008203 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008204 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008205 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008206 return new StoreInst(NewCast, CastOp);
8207 }
8208 }
8209 }
8210 return 0;
8211}
8212
Chris Lattner31f486c2005-01-31 05:36:43 +00008213Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8214 Value *Val = SI.getOperand(0);
8215 Value *Ptr = SI.getOperand(1);
8216
8217 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008218 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008219 ++NumCombined;
8220 return 0;
8221 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008222
8223 // If the RHS is an alloca with a single use, zapify the store, making the
8224 // alloca dead.
8225 if (Ptr->hasOneUse()) {
8226 if (isa<AllocaInst>(Ptr)) {
8227 EraseInstFromFunction(SI);
8228 ++NumCombined;
8229 return 0;
8230 }
8231
8232 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8233 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8234 GEP->getOperand(0)->hasOneUse()) {
8235 EraseInstFromFunction(SI);
8236 ++NumCombined;
8237 return 0;
8238 }
8239 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008240
Chris Lattner5997cf92006-02-08 03:25:32 +00008241 // Do really simple DSE, to catch cases where there are several consequtive
8242 // stores to the same location, separated by a few arithmetic operations. This
8243 // situation often occurs with bitfield accesses.
8244 BasicBlock::iterator BBI = &SI;
8245 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8246 --ScanInsts) {
8247 --BBI;
8248
8249 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8250 // Prev store isn't volatile, and stores to the same location?
8251 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8252 ++NumDeadStore;
8253 ++BBI;
8254 EraseInstFromFunction(*PrevSI);
8255 continue;
8256 }
8257 break;
8258 }
8259
Chris Lattnerdab43b22006-05-26 19:19:20 +00008260 // If this is a load, we have to stop. However, if the loaded value is from
8261 // the pointer we're loading and is producing the pointer we're storing,
8262 // then *this* store is dead (X = load P; store X -> P).
8263 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8264 if (LI == Val && LI->getOperand(0) == Ptr) {
8265 EraseInstFromFunction(SI);
8266 ++NumCombined;
8267 return 0;
8268 }
8269 // Otherwise, this is a load from some other location. Stores before it
8270 // may not be dead.
8271 break;
8272 }
8273
Chris Lattner5997cf92006-02-08 03:25:32 +00008274 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008275 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008276 break;
8277 }
8278
8279
8280 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008281
8282 // store X, null -> turns into 'unreachable' in SimplifyCFG
8283 if (isa<ConstantPointerNull>(Ptr)) {
8284 if (!isa<UndefValue>(Val)) {
8285 SI.setOperand(0, UndefValue::get(Val->getType()));
8286 if (Instruction *U = dyn_cast<Instruction>(Val))
8287 WorkList.push_back(U); // Dropped a use.
8288 ++NumCombined;
8289 }
8290 return 0; // Do not modify these!
8291 }
8292
8293 // store undef, Ptr -> noop
8294 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008295 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008296 ++NumCombined;
8297 return 0;
8298 }
8299
Chris Lattner72684fe2005-01-31 05:51:45 +00008300 // If the pointer destination is a cast, see if we can fold the cast into the
8301 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008302 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008303 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8304 return Res;
8305 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008306 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008307 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8308 return Res;
8309
Chris Lattner219175c2005-09-12 23:23:25 +00008310
8311 // If this store is the last instruction in the basic block, and if the block
8312 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008313 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008314 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8315 if (BI->isUnconditional()) {
8316 // Check to see if the successor block has exactly two incoming edges. If
8317 // so, see if the other predecessor contains a store to the same location.
8318 // if so, insert a PHI node (if needed) and move the stores down.
8319 BasicBlock *Dest = BI->getSuccessor(0);
8320
8321 pred_iterator PI = pred_begin(Dest);
8322 BasicBlock *Other = 0;
8323 if (*PI != BI->getParent())
8324 Other = *PI;
8325 ++PI;
8326 if (PI != pred_end(Dest)) {
8327 if (*PI != BI->getParent())
8328 if (Other)
8329 Other = 0;
8330 else
8331 Other = *PI;
8332 if (++PI != pred_end(Dest))
8333 Other = 0;
8334 }
8335 if (Other) { // If only one other pred...
8336 BBI = Other->getTerminator();
8337 // Make sure this other block ends in an unconditional branch and that
8338 // there is an instruction before the branch.
8339 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8340 BBI != Other->begin()) {
8341 --BBI;
8342 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8343
8344 // If this instruction is a store to the same location.
8345 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8346 // Okay, we know we can perform this transformation. Insert a PHI
8347 // node now if we need it.
8348 Value *MergedVal = OtherStore->getOperand(0);
8349 if (MergedVal != SI.getOperand(0)) {
8350 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8351 PN->reserveOperandSpace(2);
8352 PN->addIncoming(SI.getOperand(0), SI.getParent());
8353 PN->addIncoming(OtherStore->getOperand(0), Other);
8354 MergedVal = InsertNewInstBefore(PN, Dest->front());
8355 }
8356
8357 // Advance to a place where it is safe to insert the new store and
8358 // insert it.
8359 BBI = Dest->begin();
8360 while (isa<PHINode>(BBI)) ++BBI;
8361 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8362 OtherStore->isVolatile()), *BBI);
8363
8364 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008365 EraseInstFromFunction(SI);
8366 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008367 ++NumCombined;
8368 return 0;
8369 }
8370 }
8371 }
8372 }
8373
Chris Lattner31f486c2005-01-31 05:36:43 +00008374 return 0;
8375}
8376
8377
Chris Lattner9eef8a72003-06-04 04:46:00 +00008378Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8379 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008380 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008381 BasicBlock *TrueDest;
8382 BasicBlock *FalseDest;
8383 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8384 !isa<Constant>(X)) {
8385 // Swap Destinations and condition...
8386 BI.setCondition(X);
8387 BI.setSuccessor(0, FalseDest);
8388 BI.setSuccessor(1, TrueDest);
8389 return &BI;
8390 }
8391
Reid Spencer266e42b2006-12-23 06:05:41 +00008392 // Cannonicalize fcmp_one -> fcmp_oeq
8393 FCmpInst::Predicate FPred; Value *Y;
8394 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8395 TrueDest, FalseDest)))
8396 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8397 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8398 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008399 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008400 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8401 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8402 // Swap Destinations and condition...
8403 BI.setCondition(NewSCC);
8404 BI.setSuccessor(0, FalseDest);
8405 BI.setSuccessor(1, TrueDest);
8406 removeFromWorkList(I);
8407 I->getParent()->getInstList().erase(I);
8408 WorkList.push_back(cast<Instruction>(NewSCC));
8409 return &BI;
8410 }
8411
8412 // Cannonicalize icmp_ne -> icmp_eq
8413 ICmpInst::Predicate IPred;
8414 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8415 TrueDest, FalseDest)))
8416 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8417 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8418 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8419 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8420 std::string Name = I->getName(); I->setName("");
8421 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8422 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008423 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008424 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008425 BI.setSuccessor(0, FalseDest);
8426 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008427 removeFromWorkList(I);
8428 I->getParent()->getInstList().erase(I);
8429 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008430 return &BI;
8431 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008432
Chris Lattner9eef8a72003-06-04 04:46:00 +00008433 return 0;
8434}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008435
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008436Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8437 Value *Cond = SI.getCondition();
8438 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8439 if (I->getOpcode() == Instruction::Add)
8440 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8441 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8442 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008443 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008444 AddRHS));
8445 SI.setOperand(0, I->getOperand(0));
8446 WorkList.push_back(I);
8447 return &SI;
8448 }
8449 }
8450 return 0;
8451}
8452
Chris Lattner6bc98652006-03-05 00:22:33 +00008453/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8454/// is to leave as a vector operation.
8455static bool CheapToScalarize(Value *V, bool isConstant) {
8456 if (isa<ConstantAggregateZero>(V))
8457 return true;
8458 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8459 if (isConstant) return true;
8460 // If all elts are the same, we can extract.
8461 Constant *Op0 = C->getOperand(0);
8462 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8463 if (C->getOperand(i) != Op0)
8464 return false;
8465 return true;
8466 }
8467 Instruction *I = dyn_cast<Instruction>(V);
8468 if (!I) return false;
8469
8470 // Insert element gets simplified to the inserted element or is deleted if
8471 // this is constant idx extract element and its a constant idx insertelt.
8472 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8473 isa<ConstantInt>(I->getOperand(2)))
8474 return true;
8475 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8476 return true;
8477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8478 if (BO->hasOneUse() &&
8479 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8480 CheapToScalarize(BO->getOperand(1), isConstant)))
8481 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008482 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8483 if (CI->hasOneUse() &&
8484 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8485 CheapToScalarize(CI->getOperand(1), isConstant)))
8486 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008487
8488 return false;
8489}
8490
Chris Lattner12249be2006-05-25 23:48:38 +00008491/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8492/// elements into values that are larger than the #elts in the input.
8493static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8494 unsigned NElts = SVI->getType()->getNumElements();
8495 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8496 return std::vector<unsigned>(NElts, 0);
8497 if (isa<UndefValue>(SVI->getOperand(2)))
8498 return std::vector<unsigned>(NElts, 2*NElts);
8499
8500 std::vector<unsigned> Result;
8501 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8502 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8503 if (isa<UndefValue>(CP->getOperand(i)))
8504 Result.push_back(NElts*2); // undef -> 8
8505 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008506 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008507 return Result;
8508}
8509
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008510/// FindScalarElement - Given a vector and an element number, see if the scalar
8511/// value is already around as a register, for example if it were inserted then
8512/// extracted from the vector.
8513static Value *FindScalarElement(Value *V, unsigned EltNo) {
8514 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8515 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008516 unsigned Width = PTy->getNumElements();
8517 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008518 return UndefValue::get(PTy->getElementType());
8519
8520 if (isa<UndefValue>(V))
8521 return UndefValue::get(PTy->getElementType());
8522 else if (isa<ConstantAggregateZero>(V))
8523 return Constant::getNullValue(PTy->getElementType());
8524 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8525 return CP->getOperand(EltNo);
8526 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8527 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008528 if (!isa<ConstantInt>(III->getOperand(2)))
8529 return 0;
8530 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008531
8532 // If this is an insert to the element we are looking for, return the
8533 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008534 if (EltNo == IIElt)
8535 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008536
8537 // Otherwise, the insertelement doesn't modify the value, recurse on its
8538 // vector input.
8539 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008540 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008541 unsigned InEl = getShuffleMask(SVI)[EltNo];
8542 if (InEl < Width)
8543 return FindScalarElement(SVI->getOperand(0), InEl);
8544 else if (InEl < Width*2)
8545 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8546 else
8547 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008548 }
8549
8550 // Otherwise, we don't know.
8551 return 0;
8552}
8553
Robert Bocchinoa8352962006-01-13 22:48:06 +00008554Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008555
Chris Lattner92346c32006-03-31 18:25:14 +00008556 // If packed val is undef, replace extract with scalar undef.
8557 if (isa<UndefValue>(EI.getOperand(0)))
8558 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8559
8560 // If packed val is constant 0, replace extract with scalar 0.
8561 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8562 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8563
Robert Bocchinoa8352962006-01-13 22:48:06 +00008564 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8565 // If packed val is constant with uniform operands, replace EI
8566 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008567 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008568 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008569 if (C->getOperand(i) != op0) {
8570 op0 = 0;
8571 break;
8572 }
8573 if (op0)
8574 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008575 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008576
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008577 // If extracting a specified index from the vector, see if we can recursively
8578 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008579 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008580 // This instruction only demands the single element from the input vector.
8581 // If the input vector has a single use, simplify it based on this use
8582 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008583 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008584 if (EI.getOperand(0)->hasOneUse()) {
8585 uint64_t UndefElts;
8586 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008587 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008588 UndefElts)) {
8589 EI.setOperand(0, V);
8590 return &EI;
8591 }
8592 }
8593
Reid Spencere0fc4df2006-10-20 07:07:24 +00008594 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008595 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008596 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008597
Chris Lattner83f65782006-05-25 22:53:38 +00008598 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008599 if (I->hasOneUse()) {
8600 // Push extractelement into predecessor operation if legal and
8601 // profitable to do so
8602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008603 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8604 if (CheapToScalarize(BO, isConstantElt)) {
8605 ExtractElementInst *newEI0 =
8606 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8607 EI.getName()+".lhs");
8608 ExtractElementInst *newEI1 =
8609 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8610 EI.getName()+".rhs");
8611 InsertNewInstBefore(newEI0, EI);
8612 InsertNewInstBefore(newEI1, EI);
8613 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8614 }
Reid Spencerde46e482006-11-02 20:25:50 +00008615 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008616 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008617 PointerType::get(EI.getType()), EI);
8618 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008619 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008620 InsertNewInstBefore(GEP, EI);
8621 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008622 }
8623 }
8624 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8625 // Extracting the inserted element?
8626 if (IE->getOperand(2) == EI.getOperand(1))
8627 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8628 // If the inserted and extracted elements are constants, they must not
8629 // be the same value, extract from the pre-inserted value instead.
8630 if (isa<Constant>(IE->getOperand(2)) &&
8631 isa<Constant>(EI.getOperand(1))) {
8632 AddUsesToWorkList(EI);
8633 EI.setOperand(0, IE->getOperand(0));
8634 return &EI;
8635 }
8636 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8637 // If this is extracting an element from a shufflevector, figure out where
8638 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008639 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8640 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008641 Value *Src;
8642 if (SrcIdx < SVI->getType()->getNumElements())
8643 Src = SVI->getOperand(0);
8644 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8645 SrcIdx -= SVI->getType()->getNumElements();
8646 Src = SVI->getOperand(1);
8647 } else {
8648 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008649 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008650 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008651 }
8652 }
Chris Lattner83f65782006-05-25 22:53:38 +00008653 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008654 return 0;
8655}
8656
Chris Lattner90951862006-04-16 00:51:47 +00008657/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8658/// elements from either LHS or RHS, return the shuffle mask and true.
8659/// Otherwise, return false.
8660static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8661 std::vector<Constant*> &Mask) {
8662 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8663 "Invalid CollectSingleShuffleElements");
8664 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8665
8666 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008667 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008668 return true;
8669 } else if (V == LHS) {
8670 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008671 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008672 return true;
8673 } else if (V == RHS) {
8674 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008675 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008676 return true;
8677 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8678 // If this is an insert of an extract from some other vector, include it.
8679 Value *VecOp = IEI->getOperand(0);
8680 Value *ScalarOp = IEI->getOperand(1);
8681 Value *IdxOp = IEI->getOperand(2);
8682
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008683 if (!isa<ConstantInt>(IdxOp))
8684 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008685 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008686
8687 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8688 // Okay, we can handle this if the vector we are insertinting into is
8689 // transitively ok.
8690 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8691 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008692 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008693 return true;
8694 }
8695 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8696 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008697 EI->getOperand(0)->getType() == V->getType()) {
8698 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008699 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008700
8701 // This must be extracting from either LHS or RHS.
8702 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8703 // Okay, we can handle this if the vector we are insertinting into is
8704 // transitively ok.
8705 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8706 // If so, update the mask to reflect the inserted value.
8707 if (EI->getOperand(0) == LHS) {
8708 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008709 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008710 } else {
8711 assert(EI->getOperand(0) == RHS);
8712 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008713 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008714
8715 }
8716 return true;
8717 }
8718 }
8719 }
8720 }
8721 }
8722 // TODO: Handle shufflevector here!
8723
8724 return false;
8725}
8726
8727/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8728/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8729/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008730static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008731 Value *&RHS) {
8732 assert(isa<PackedType>(V->getType()) &&
8733 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008734 "Invalid shuffle!");
8735 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8736
8737 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008738 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008739 return V;
8740 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008741 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008742 return V;
8743 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8744 // If this is an insert of an extract from some other vector, include it.
8745 Value *VecOp = IEI->getOperand(0);
8746 Value *ScalarOp = IEI->getOperand(1);
8747 Value *IdxOp = IEI->getOperand(2);
8748
8749 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8750 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8751 EI->getOperand(0)->getType() == V->getType()) {
8752 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008753 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8754 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008755
8756 // Either the extracted from or inserted into vector must be RHSVec,
8757 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008758 if (EI->getOperand(0) == RHS || RHS == 0) {
8759 RHS = EI->getOperand(0);
8760 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008761 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008762 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008763 return V;
8764 }
8765
Chris Lattner90951862006-04-16 00:51:47 +00008766 if (VecOp == RHS) {
8767 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008768 // Everything but the extracted element is replaced with the RHS.
8769 for (unsigned i = 0; i != NumElts; ++i) {
8770 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008771 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008772 }
8773 return V;
8774 }
Chris Lattner90951862006-04-16 00:51:47 +00008775
8776 // If this insertelement is a chain that comes from exactly these two
8777 // vectors, return the vector and the effective shuffle.
8778 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8779 return EI->getOperand(0);
8780
Chris Lattner39fac442006-04-15 01:39:45 +00008781 }
8782 }
8783 }
Chris Lattner90951862006-04-16 00:51:47 +00008784 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008785
8786 // Otherwise, can't do anything fancy. Return an identity vector.
8787 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008788 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008789 return V;
8790}
8791
8792Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8793 Value *VecOp = IE.getOperand(0);
8794 Value *ScalarOp = IE.getOperand(1);
8795 Value *IdxOp = IE.getOperand(2);
8796
8797 // If the inserted element was extracted from some other vector, and if the
8798 // indexes are constant, try to turn this into a shufflevector operation.
8799 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8800 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8801 EI->getOperand(0)->getType() == IE.getType()) {
8802 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008803 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8804 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008805
8806 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8807 return ReplaceInstUsesWith(IE, VecOp);
8808
8809 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8810 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8811
8812 // If we are extracting a value from a vector, then inserting it right
8813 // back into the same place, just use the input vector.
8814 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8815 return ReplaceInstUsesWith(IE, VecOp);
8816
8817 // We could theoretically do this for ANY input. However, doing so could
8818 // turn chains of insertelement instructions into a chain of shufflevector
8819 // instructions, and right now we do not merge shufflevectors. As such,
8820 // only do this in a situation where it is clear that there is benefit.
8821 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8822 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8823 // the values of VecOp, except then one read from EIOp0.
8824 // Build a new shuffle mask.
8825 std::vector<Constant*> Mask;
8826 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008827 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008828 else {
8829 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008830 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008831 NumVectorElts));
8832 }
Reid Spencerc635f472006-12-31 05:48:39 +00008833 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008834 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8835 ConstantPacked::get(Mask));
8836 }
8837
8838 // If this insertelement isn't used by some other insertelement, turn it
8839 // (and any insertelements it points to), into one big shuffle.
8840 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8841 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008842 Value *RHS = 0;
8843 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8844 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8845 // We now have a shuffle of LHS, RHS, Mask.
8846 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008847 }
8848 }
8849 }
8850
8851 return 0;
8852}
8853
8854
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008855Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8856 Value *LHS = SVI.getOperand(0);
8857 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008858 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008859
8860 bool MadeChange = false;
8861
Chris Lattner2deeaea2006-10-05 06:55:50 +00008862 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008863 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008864 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8865
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008866 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008867 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008868 if (isa<UndefValue>(SVI.getOperand(1))) {
8869 // Scan to see if there are any references to the RHS. If so, replace them
8870 // with undef element refs and set MadeChange to true.
8871 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8872 if (Mask[i] >= e && Mask[i] != 2*e) {
8873 Mask[i] = 2*e;
8874 MadeChange = true;
8875 }
8876 }
8877
8878 if (MadeChange) {
8879 // Remap any references to RHS to use LHS.
8880 std::vector<Constant*> Elts;
8881 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8882 if (Mask[i] == 2*e)
8883 Elts.push_back(UndefValue::get(Type::Int32Ty));
8884 else
8885 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8886 }
8887 SVI.setOperand(2, ConstantPacked::get(Elts));
8888 }
8889 }
Chris Lattner39fac442006-04-15 01:39:45 +00008890
Chris Lattner12249be2006-05-25 23:48:38 +00008891 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8892 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8893 if (LHS == RHS || isa<UndefValue>(LHS)) {
8894 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008895 // shuffle(undef,undef,mask) -> undef.
8896 return ReplaceInstUsesWith(SVI, LHS);
8897 }
8898
Chris Lattner12249be2006-05-25 23:48:38 +00008899 // Remap any references to RHS to use LHS.
8900 std::vector<Constant*> Elts;
8901 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008902 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008903 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008904 else {
8905 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8906 (Mask[i] < e && isa<UndefValue>(LHS)))
8907 Mask[i] = 2*e; // Turn into undef.
8908 else
8909 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008910 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008911 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008912 }
Chris Lattner12249be2006-05-25 23:48:38 +00008913 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008914 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008915 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008916 LHS = SVI.getOperand(0);
8917 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008918 MadeChange = true;
8919 }
8920
Chris Lattner0e477162006-05-26 00:29:06 +00008921 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008922 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008923
Chris Lattner12249be2006-05-25 23:48:38 +00008924 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8925 if (Mask[i] >= e*2) continue; // Ignore undef values.
8926 // Is this an identity shuffle of the LHS value?
8927 isLHSID &= (Mask[i] == i);
8928
8929 // Is this an identity shuffle of the RHS value?
8930 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008931 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008932
Chris Lattner12249be2006-05-25 23:48:38 +00008933 // Eliminate identity shuffles.
8934 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8935 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008936
Chris Lattner0e477162006-05-26 00:29:06 +00008937 // If the LHS is a shufflevector itself, see if we can combine it with this
8938 // one without producing an unusual shuffle. Here we are really conservative:
8939 // we are absolutely afraid of producing a shuffle mask not in the input
8940 // program, because the code gen may not be smart enough to turn a merged
8941 // shuffle into two specific shuffles: it may produce worse code. As such,
8942 // we only merge two shuffles if the result is one of the two input shuffle
8943 // masks. In this case, merging the shuffles just removes one instruction,
8944 // which we know is safe. This is good for things like turning:
8945 // (splat(splat)) -> splat.
8946 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8947 if (isa<UndefValue>(RHS)) {
8948 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8949
8950 std::vector<unsigned> NewMask;
8951 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8952 if (Mask[i] >= 2*e)
8953 NewMask.push_back(2*e);
8954 else
8955 NewMask.push_back(LHSMask[Mask[i]]);
8956
8957 // If the result mask is equal to the src shuffle or this shuffle mask, do
8958 // the replacement.
8959 if (NewMask == LHSMask || NewMask == Mask) {
8960 std::vector<Constant*> Elts;
8961 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8962 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008963 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008964 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008965 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008966 }
8967 }
8968 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8969 LHSSVI->getOperand(1),
8970 ConstantPacked::get(Elts));
8971 }
8972 }
8973 }
8974
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008975 return MadeChange ? &SVI : 0;
8976}
8977
8978
Robert Bocchinoa8352962006-01-13 22:48:06 +00008979
Chris Lattner99f48c62002-09-02 04:59:56 +00008980void InstCombiner::removeFromWorkList(Instruction *I) {
8981 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8982 WorkList.end());
8983}
8984
Chris Lattner39c98bb2004-12-08 23:43:58 +00008985
8986/// TryToSinkInstruction - Try to move the specified instruction from its
8987/// current block into the beginning of DestBlock, which can only happen if it's
8988/// safe to move the instruction past all of the instructions between it and the
8989/// end of its block.
8990static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8991 assert(I->hasOneUse() && "Invariants didn't hold!");
8992
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008993 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8994 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008995
Chris Lattner39c98bb2004-12-08 23:43:58 +00008996 // Do not sink alloca instructions out of the entry block.
8997 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8998 return false;
8999
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009000 // We can only sink load instructions if there is nothing between the load and
9001 // the end of block that could change the value.
9002 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009003 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9004 Scan != E; ++Scan)
9005 if (Scan->mayWriteToMemory())
9006 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009007 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009008
9009 BasicBlock::iterator InsertPos = DestBlock->begin();
9010 while (isa<PHINode>(InsertPos)) ++InsertPos;
9011
Chris Lattner9f269e42005-08-08 19:11:57 +00009012 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009013 ++NumSunkInst;
9014 return true;
9015}
9016
Chris Lattner1443bc52006-05-11 17:11:52 +00009017/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00009018/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00009019/// if possible.
9020static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9021 if (!TD) return CE;
9022
9023 Constant *Ptr = CE->getOperand(0);
9024 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9025 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9026 // If this is a constant expr gep that is effectively computing an
9027 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9028 bool isFoldableGEP = true;
9029 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9030 if (!isa<ConstantInt>(CE->getOperand(i)))
9031 isFoldableGEP = false;
9032 if (isFoldableGEP) {
9033 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9034 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00009035 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009036 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009037 }
9038 }
9039
9040 return CE;
9041}
9042
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009043
9044/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9045/// all reachable code to the worklist.
9046///
9047/// This has a couple of tricks to make the code faster and more powerful. In
9048/// particular, we constant fold and DCE instructions as we go, to avoid adding
9049/// them to the worklist (this significantly speeds up instcombine on code where
9050/// many instructions are dead or constant). Additionally, if we find a branch
9051/// whose condition is a known constant, we only visit the reachable successors.
9052///
9053static void AddReachableCodeToWorklist(BasicBlock *BB,
9054 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009055 std::vector<Instruction*> &WorkList,
9056 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009057 // We have now visited this block! If we've already been here, bail out.
9058 if (!Visited.insert(BB).second) return;
9059
9060 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9061 Instruction *Inst = BBI++;
9062
9063 // DCE instruction if trivially dead.
9064 if (isInstructionTriviallyDead(Inst)) {
9065 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009066 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009067 Inst->eraseFromParent();
9068 continue;
9069 }
9070
9071 // ConstantProp instruction if trivially constant.
9072 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009073 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9074 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009075 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009076 Inst->replaceAllUsesWith(C);
9077 ++NumConstProp;
9078 Inst->eraseFromParent();
9079 continue;
9080 }
9081
9082 WorkList.push_back(Inst);
9083 }
9084
9085 // Recursively visit successors. If this is a branch or switch on a constant,
9086 // only visit the reachable successor.
9087 TerminatorInst *TI = BB->getTerminator();
9088 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009089 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009090 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009091 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9092 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009093 return;
9094 }
9095 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9096 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9097 // See if this is an explicit destination.
9098 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9099 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009100 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009101 return;
9102 }
9103
9104 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009105 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009106 return;
9107 }
9108 }
9109
9110 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009111 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009112}
9113
Chris Lattner113f4f42002-06-25 16:13:24 +00009114bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009115 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009116 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009117
Chris Lattner4ed40f72005-07-07 20:40:38 +00009118 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009119 // Do a depth-first traversal of the function, populate the worklist with
9120 // the reachable instructions. Ignore blocks that are not reachable. Keep
9121 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009122 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009123 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009124
Chris Lattner4ed40f72005-07-07 20:40:38 +00009125 // Do a quick scan over the function. If we find any blocks that are
9126 // unreachable, remove any instructions inside of them. This prevents
9127 // the instcombine code from having to deal with some bad special cases.
9128 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9129 if (!Visited.count(BB)) {
9130 Instruction *Term = BB->getTerminator();
9131 while (Term != BB->begin()) { // Remove instrs bottom-up
9132 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009133
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009134 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009135 ++NumDeadInst;
9136
9137 if (!I->use_empty())
9138 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9139 I->eraseFromParent();
9140 }
9141 }
9142 }
Chris Lattnerca081252001-12-14 16:52:21 +00009143
9144 while (!WorkList.empty()) {
9145 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9146 WorkList.pop_back();
9147
Chris Lattner1443bc52006-05-11 17:11:52 +00009148 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009149 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009150 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009151 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009152 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009153 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009154
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009155 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009156
9157 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009158 removeFromWorkList(I);
9159 continue;
9160 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009161
Chris Lattner1443bc52006-05-11 17:11:52 +00009162 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009163 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9165 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009166 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009167
Chris Lattner1443bc52006-05-11 17:11:52 +00009168 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009169 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009170 ReplaceInstUsesWith(*I, C);
9171
Chris Lattner99f48c62002-09-02 04:59:56 +00009172 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009173 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009174 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009175 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009176 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009177
Chris Lattner39c98bb2004-12-08 23:43:58 +00009178 // See if we can trivially sink this instruction to a successor basic block.
9179 if (I->hasOneUse()) {
9180 BasicBlock *BB = I->getParent();
9181 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9182 if (UserParent != BB) {
9183 bool UserIsSuccessor = false;
9184 // See if the user is one of our successors.
9185 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9186 if (*SI == UserParent) {
9187 UserIsSuccessor = true;
9188 break;
9189 }
9190
9191 // If the user is one of our immediate successors, and if that successor
9192 // only has us as a predecessors (we'd have to split the critical edge
9193 // otherwise), we can keep going.
9194 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9195 next(pred_begin(UserParent)) == pred_end(UserParent))
9196 // Okay, the CFG is simple enough, try to sink this instruction.
9197 Changed |= TryToSinkInstruction(I, UserParent);
9198 }
9199 }
9200
Chris Lattnerca081252001-12-14 16:52:21 +00009201 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009202 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009203 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009204 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009205 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009206 DOUT << "IC: Old = " << *I
9207 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009208
Chris Lattner396dbfe2004-06-09 05:08:07 +00009209 // Everything uses the new instruction now.
9210 I->replaceAllUsesWith(Result);
9211
9212 // Push the new instruction and any users onto the worklist.
9213 WorkList.push_back(Result);
9214 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009215
9216 // Move the name to the new instruction first...
9217 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009218 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009219
9220 // Insert the new instruction into the basic block...
9221 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009222 BasicBlock::iterator InsertPos = I;
9223
9224 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9225 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9226 ++InsertPos;
9227
9228 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009229
Chris Lattner63d75af2004-05-01 23:27:23 +00009230 // Make sure that we reprocess all operands now that we reduced their
9231 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009232 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9233 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9234 WorkList.push_back(OpI);
9235
Chris Lattner396dbfe2004-06-09 05:08:07 +00009236 // Instructions can end up on the worklist more than once. Make sure
9237 // we do not process an instruction that has been deleted.
9238 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009239
9240 // Erase the old instruction.
9241 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009242 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009243 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009244
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009245 // If the instruction was modified, it's possible that it is now dead.
9246 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009247 if (isInstructionTriviallyDead(I)) {
9248 // Make sure we process all operands now that we are reducing their
9249 // use counts.
9250 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9251 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9252 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009253
Chris Lattner63d75af2004-05-01 23:27:23 +00009254 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009255 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009256 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009257 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009258 } else {
9259 WorkList.push_back(Result);
9260 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009261 }
Chris Lattner053c0932002-05-14 15:24:07 +00009262 }
Chris Lattner260ab202002-04-18 17:39:14 +00009263 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009264 }
9265 }
9266
Chris Lattner260ab202002-04-18 17:39:14 +00009267 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009268}
9269
Brian Gaeke38b79e82004-07-27 17:43:21 +00009270FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009271 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009272}
Brian Gaeke960707c2003-11-11 22:41:34 +00009273