blob: 743502240d47d7672aaac456659df8591e607ec6 [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 Lattnerf95d9b92003-10-15 16:48:29 +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 Lattnerfb296922006-05-04 17:33:35 +0000561 Mask &= V->getType()->getIntegralTypeMask();
562
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();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000627 if (SrcTy->isIntegral()) {
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 Lattner0157e7f2006-02-11 09:31:47 +0000636 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
637 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000638
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000639 Mask &= SrcTy->getIntegralTypeMask();
640 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();
649 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
651
652 Mask &= SrcTy->getIntegralTypeMask();
653 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) {
769 uint64_t TypeBits = Ty->getIntegralTypeMask();
770 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) {
799 uint64_t TypeBits = Ty->getIntegralTypeMask();
800 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.
834 DemandedMask = V->getType()->getIntegralTypeMask();
835 } 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 Lattnerfb296922006-05-04 17:33:35 +0000846 DemandedMask &= V->getType()->getIntegralTypeMask();
847
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:
1004 if (!I->getOperand(0)->getType()->isIntegral())
1005 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 Lattner0157e7f2006-02-11 09:31:47 +00001015 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1016 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1017
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001018 DemandedMask &= SrcTy->getIntegralTypeMask();
1019 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();
1030 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1031 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1032
1033 // Get the sign bit for the source type
1034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
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;
1177 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1178 // 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 Lattner68e74752006-02-13 06:09:08 +00001210 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
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
1460/// @returns true if the specified compare instruction is
1461/// true when both operands are equal...
1462/// @brief Determine if the FCmpInst returns true if both operands are equal
1463static bool isTrueWhenEqual(FCmpInst &FCI) {
1464 FCmpInst::Predicate pred = FCI.getPredicate();
1465 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1466 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1467 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001468}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001469
1470/// AssociativeOpt - Perform an optimization on an associative operator. This
1471/// function is designed to check a chain of associative operators for a
1472/// potential to apply a certain optimization. Since the optimization may be
1473/// applicable if the expression was reassociated, this checks the chain, then
1474/// reassociates the expression as necessary to expose the optimization
1475/// opportunity. This makes use of a special Functor, which must define
1476/// 'shouldApply' and 'apply' methods.
1477///
1478template<typename Functor>
1479Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1480 unsigned Opcode = Root.getOpcode();
1481 Value *LHS = Root.getOperand(0);
1482
1483 // Quick check, see if the immediate LHS matches...
1484 if (F.shouldApply(LHS))
1485 return F.apply(Root);
1486
1487 // Otherwise, if the LHS is not of the same opcode as the root, return.
1488 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001489 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001490 // Should we apply this transform to the RHS?
1491 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1492
1493 // If not to the RHS, check to see if we should apply to the LHS...
1494 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1495 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1496 ShouldApply = true;
1497 }
1498
1499 // If the functor wants to apply the optimization to the RHS of LHSI,
1500 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1501 if (ShouldApply) {
1502 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001503
Chris Lattnerb8b97502003-08-13 19:01:45 +00001504 // Now all of the instructions are in the current basic block, go ahead
1505 // and perform the reassociation.
1506 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1507
1508 // First move the selected RHS to the LHS of the root...
1509 Root.setOperand(0, LHSI->getOperand(1));
1510
1511 // Make what used to be the LHS of the root be the user of the root...
1512 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001513 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001514 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1515 return 0;
1516 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001517 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001518 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001519 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1520 BasicBlock::iterator ARI = &Root; ++ARI;
1521 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1522 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001523
1524 // Now propagate the ExtraOperand down the chain of instructions until we
1525 // get to LHSI.
1526 while (TmpLHSI != LHSI) {
1527 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001528 // Move the instruction to immediately before the chain we are
1529 // constructing to avoid breaking dominance properties.
1530 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1531 BB->getInstList().insert(ARI, NextLHSI);
1532 ARI = NextLHSI;
1533
Chris Lattnerb8b97502003-08-13 19:01:45 +00001534 Value *NextOp = NextLHSI->getOperand(1);
1535 NextLHSI->setOperand(1, ExtraOperand);
1536 TmpLHSI = NextLHSI;
1537 ExtraOperand = NextOp;
1538 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001539
Chris Lattnerb8b97502003-08-13 19:01:45 +00001540 // Now that the instructions are reassociated, have the functor perform
1541 // the transformation...
1542 return F.apply(Root);
1543 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001544
Chris Lattnerb8b97502003-08-13 19:01:45 +00001545 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1546 }
1547 return 0;
1548}
1549
1550
1551// AddRHS - Implements: X + X --> X << 1
1552struct AddRHS {
1553 Value *RHS;
1554 AddRHS(Value *rhs) : RHS(rhs) {}
1555 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1556 Instruction *apply(BinaryOperator &Add) const {
1557 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001558 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001559 }
1560};
1561
1562// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1563// iff C1&C2 == 0
1564struct AddMaskingAnd {
1565 Constant *C2;
1566 AddMaskingAnd(Constant *c) : C2(c) {}
1567 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001568 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001569 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001570 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001571 }
1572 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001573 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001574 }
1575};
1576
Chris Lattner86102b82005-01-01 16:22:27 +00001577static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001578 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001579 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001580 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001581 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001583 return IC->InsertNewInstBefore(CastInst::create(
1584 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001585 }
1586
Chris Lattner183b3362004-04-09 19:05:30 +00001587 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001588 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1589 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001590
Chris Lattner183b3362004-04-09 19:05:30 +00001591 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1592 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001593 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1594 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001595 }
1596
1597 Value *Op0 = SO, *Op1 = ConstOperand;
1598 if (!ConstIsRHS)
1599 std::swap(Op0, Op1);
1600 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001601 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1602 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001603 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1604 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1605 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001606 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1607 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001608 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001609 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001610 abort();
1611 }
Chris Lattner86102b82005-01-01 16:22:27 +00001612 return IC->InsertNewInstBefore(New, I);
1613}
1614
1615// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1616// constant as the other operand, try to fold the binary operator into the
1617// select arguments. This also works for Cast instructions, which obviously do
1618// not have a second operand.
1619static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1620 InstCombiner *IC) {
1621 // Don't modify shared select instructions
1622 if (!SI->hasOneUse()) return 0;
1623 Value *TV = SI->getOperand(1);
1624 Value *FV = SI->getOperand(2);
1625
1626 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001627 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001628 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001629
Chris Lattner86102b82005-01-01 16:22:27 +00001630 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1631 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1632
1633 return new SelectInst(SI->getCondition(), SelectTrueVal,
1634 SelectFalseVal);
1635 }
1636 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001637}
1638
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001639
1640/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1641/// node as operand #0, see if we can fold the instruction into the PHI (which
1642/// is only possible if all operands to the PHI are constants).
1643Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1644 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001645 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001646 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001647
Chris Lattner04689872006-09-09 22:02:56 +00001648 // Check to see if all of the operands of the PHI are constants. If there is
1649 // one non-constant value, remember the BB it is. If there is more than one
1650 // bail out.
1651 BasicBlock *NonConstBB = 0;
1652 for (unsigned i = 0; i != NumPHIValues; ++i)
1653 if (!isa<Constant>(PN->getIncomingValue(i))) {
1654 if (NonConstBB) return 0; // More than one non-const value.
1655 NonConstBB = PN->getIncomingBlock(i);
1656
1657 // If the incoming non-constant value is in I's block, we have an infinite
1658 // loop.
1659 if (NonConstBB == I.getParent())
1660 return 0;
1661 }
1662
1663 // If there is exactly one non-constant value, we can insert a copy of the
1664 // operation in that block. However, if this is a critical edge, we would be
1665 // inserting the computation one some other paths (e.g. inside a loop). Only
1666 // do this if the pred block is unconditionally branching into the phi block.
1667 if (NonConstBB) {
1668 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1669 if (!BI || !BI->isUnconditional()) return 0;
1670 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001671
1672 // Okay, we can do the transformation: create the new PHI node.
1673 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1674 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001675 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001676 InsertNewInstBefore(NewPN, *PN);
1677
1678 // Next, add all of the operands to the PHI.
1679 if (I.getNumOperands() == 2) {
1680 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001681 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001682 Value *InV;
1683 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001684 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1686 else
1687 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001688 } else {
1689 assert(PN->getIncomingBlock(i) == NonConstBB);
1690 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1691 InV = BinaryOperator::create(BO->getOpcode(),
1692 PN->getIncomingValue(i), C, "phitmp",
1693 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001694 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1695 InV = CmpInst::create(CI->getOpcode(),
1696 CI->getPredicate(),
1697 PN->getIncomingValue(i), C, "phitmp",
1698 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001699 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1700 InV = new ShiftInst(SI->getOpcode(),
1701 PN->getIncomingValue(i), C, "phitmp",
1702 NonConstBB->getTerminator());
1703 else
1704 assert(0 && "Unknown binop!");
1705
1706 WorkList.push_back(cast<Instruction>(InV));
1707 }
1708 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001709 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001710 } else {
1711 CastInst *CI = cast<CastInst>(&I);
1712 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001713 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001714 Value *InV;
1715 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001716 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001717 } else {
1718 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001719 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1720 I.getType(), "phitmp",
1721 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001722 WorkList.push_back(cast<Instruction>(InV));
1723 }
1724 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001725 }
1726 }
1727 return ReplaceInstUsesWith(I, NewPN);
1728}
1729
Chris Lattner113f4f42002-06-25 16:13:24 +00001730Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001731 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001732 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001733
Chris Lattnercf4a9962004-04-10 22:01:55 +00001734 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001735 // X + undef -> undef
1736 if (isa<UndefValue>(RHS))
1737 return ReplaceInstUsesWith(I, RHS);
1738
Chris Lattnercf4a9962004-04-10 22:01:55 +00001739 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001740 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001741 if (RHSC->isNullValue())
1742 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001743 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1744 if (CFP->isExactlyValue(-0.0))
1745 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001746 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001747
Chris Lattnercf4a9962004-04-10 22:01:55 +00001748 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001749 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001750 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001751 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001752 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001753
1754 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1755 // (X & 254)+1 -> (X&254)|1
1756 uint64_t KnownZero, KnownOne;
1757 if (!isa<PackedType>(I.getType()) &&
1758 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1759 KnownZero, KnownOne))
1760 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001761 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001762
1763 if (isa<PHINode>(LHS))
1764 if (Instruction *NV = FoldOpIntoPhi(I))
1765 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001766
Chris Lattner330628a2006-01-06 17:59:59 +00001767 ConstantInt *XorRHS = 0;
1768 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001769 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1770 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1771 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1772 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1773
1774 uint64_t C0080Val = 1ULL << 31;
1775 int64_t CFF80Val = -C0080Val;
1776 unsigned Size = 32;
1777 do {
1778 if (TySizeBits > Size) {
1779 bool Found = false;
1780 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1781 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1782 if (RHSSExt == CFF80Val) {
1783 if (XorRHS->getZExtValue() == C0080Val)
1784 Found = true;
1785 } else if (RHSZExt == C0080Val) {
1786 if (XorRHS->getSExtValue() == CFF80Val)
1787 Found = true;
1788 }
1789 if (Found) {
1790 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001791 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001792 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001793 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001794 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001795 Size = 0; // Not a sign ext, but can't be any others either.
1796 goto FoundSExt;
1797 }
1798 }
1799 Size >>= 1;
1800 C0080Val >>= Size;
1801 CFF80Val >>= Size;
1802 } while (Size >= 8);
1803
1804FoundSExt:
1805 const Type *MiddleType = 0;
1806 switch (Size) {
1807 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001808 case 32: MiddleType = Type::Int32Ty; break;
1809 case 16: MiddleType = Type::Int16Ty; break;
1810 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001811 }
1812 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001813 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001814 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001815 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001816 }
1817 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001818 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001819
Chris Lattnerb8b97502003-08-13 19:01:45 +00001820 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001821 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001822 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001823
1824 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1825 if (RHSI->getOpcode() == Instruction::Sub)
1826 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1827 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1828 }
1829 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1830 if (LHSI->getOpcode() == Instruction::Sub)
1831 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1832 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1833 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001834 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001835
Chris Lattner147e9752002-05-08 22:46:53 +00001836 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001837 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001838 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001839
1840 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001841 if (!isa<Constant>(RHS))
1842 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001843 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001844
Misha Brukmanb1c93172005-04-21 23:48:37 +00001845
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001846 ConstantInt *C2;
1847 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1848 if (X == RHS) // X*C + X --> X * (C+1)
1849 return BinaryOperator::createMul(RHS, AddOne(C2));
1850
1851 // X*C1 + X*C2 --> X * (C1+C2)
1852 ConstantInt *C1;
1853 if (X == dyn_castFoldableMul(RHS, C1))
1854 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001855 }
1856
1857 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001858 if (dyn_castFoldableMul(RHS, C2) == LHS)
1859 return BinaryOperator::createMul(LHS, AddOne(C2));
1860
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001861 // X + ~X --> -1 since ~X = -X-1
1862 if (dyn_castNotVal(LHS) == RHS ||
1863 dyn_castNotVal(RHS) == LHS)
1864 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1865
Chris Lattner57c8d992003-02-18 19:57:07 +00001866
Chris Lattnerb8b97502003-08-13 19:01:45 +00001867 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001868 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001869 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1870 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001871
Chris Lattnerb9cde762003-10-02 15:11:26 +00001872 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001873 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001874 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1875 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1876 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001877 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001878
Chris Lattnerbff91d92004-10-08 05:07:56 +00001879 // (X & FF00) + xx00 -> (X+xx00) & FF00
1880 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1881 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1882 if (Anded == CRHS) {
1883 // See if all bits from the first bit set in the Add RHS up are included
1884 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001885 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001886
1887 // Form a mask of all bits from the lowest bit added through the top.
1888 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001889 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001890
1891 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001892 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001893
Chris Lattnerbff91d92004-10-08 05:07:56 +00001894 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1895 // Okay, the xform is safe. Insert the new add pronto.
1896 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1897 LHS->getName()), I);
1898 return BinaryOperator::createAnd(NewAdd, C2);
1899 }
1900 }
1901 }
1902
Chris Lattnerd4252a72004-07-30 07:50:03 +00001903 // Try to fold constant add into select arguments.
1904 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001905 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001906 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001907 }
1908
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001909 // add (cast *A to intptrtype) B ->
1910 // cast (GEP (cast *A to sbyte*) B) ->
1911 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001912 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001913 CastInst *CI = dyn_cast<CastInst>(LHS);
1914 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001915 if (!CI) {
1916 CI = dyn_cast<CastInst>(RHS);
1917 Other = LHS;
1918 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001919 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001920 (CI->getType()->getPrimitiveSizeInBits() ==
1921 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001922 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001923 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001924 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001925 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001926 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001927 }
1928 }
1929
Chris Lattner113f4f42002-06-25 16:13:24 +00001930 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001931}
1932
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001933// isSignBit - Return true if the value represented by the constant only has the
1934// highest order bit set.
1935static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001936 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001937 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001938}
1939
Chris Lattner022167f2004-03-13 00:11:49 +00001940/// RemoveNoopCast - Strip off nonconverting casts from the value.
1941///
1942static Value *RemoveNoopCast(Value *V) {
1943 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1944 const Type *CTy = CI->getType();
1945 const Type *OpTy = CI->getOperand(0)->getType();
1946 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001947 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001948 return RemoveNoopCast(CI->getOperand(0));
1949 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1950 return RemoveNoopCast(CI->getOperand(0));
1951 }
1952 return V;
1953}
1954
Chris Lattner113f4f42002-06-25 16:13:24 +00001955Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001956 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001957
Chris Lattnere6794492002-08-12 21:17:25 +00001958 if (Op0 == Op1) // sub X, X -> 0
1959 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001960
Chris Lattnere6794492002-08-12 21:17:25 +00001961 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001962 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001963 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001964
Chris Lattner81a7a232004-10-16 18:11:37 +00001965 if (isa<UndefValue>(Op0))
1966 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1967 if (isa<UndefValue>(Op1))
1968 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1969
Chris Lattner8f2f5982003-11-05 01:06:05 +00001970 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1971 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001972 if (C->isAllOnesValue())
1973 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001974
Chris Lattner8f2f5982003-11-05 01:06:05 +00001975 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001976 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001977 if (match(Op1, m_Not(m_Value(X))))
1978 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001979 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001980 // -((uint)X >> 31) -> ((int)X >> 31)
1981 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001982 if (C->isNullValue()) {
1983 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1984 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001985 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001986 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001987 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001988 if (CU->getZExtValue() ==
1989 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001990 // Ok, the transformation is safe. Insert AShr.
Reid Spencer193df252006-12-24 00:40:59 +00001991 // FIXME: Once integer types are signless, this cast should be
1992 // removed.
1993 Value *ShiftOp = SI->getOperand(0);
Reid Spencer193df252006-12-24 00:40:59 +00001994 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
1995 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001996 }
1997 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001998 }
1999 else if (SI->getOpcode() == Instruction::AShr) {
2000 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2001 // Check to see if we are shifting out everything but the sign bit.
2002 if (CU->getZExtValue() ==
2003 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002004
2005 // Ok, the transformation is safe. Insert LShr.
2006 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2007 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002008 }
2009 }
2010 }
Chris Lattner022167f2004-03-13 00:11:49 +00002011 }
Chris Lattner183b3362004-04-09 19:05:30 +00002012
2013 // Try to fold constant sub into select arguments.
2014 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002016 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002017
2018 if (isa<PHINode>(Op0))
2019 if (Instruction *NV = FoldOpIntoPhi(I))
2020 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002021 }
2022
Chris Lattnera9be4492005-04-07 16:15:25 +00002023 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2024 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002025 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002026 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002027 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002028 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002029 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002030 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2031 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2032 // C1-(X+C2) --> (C1-C2)-X
2033 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2034 Op1I->getOperand(0));
2035 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002036 }
2037
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002038 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002039 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2040 // is not used by anyone else...
2041 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002042 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002043 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002044 // Swap the two operands of the subexpr...
2045 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2046 Op1I->setOperand(0, IIOp1);
2047 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002048
Chris Lattner3082c5a2003-02-18 19:28:33 +00002049 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002050 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051 }
2052
2053 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2054 //
2055 if (Op1I->getOpcode() == Instruction::And &&
2056 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2057 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2058
Chris Lattner396dbfe2004-06-09 05:08:07 +00002059 Value *NewNot =
2060 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002061 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002062 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002063
Reid Spencer3c514952006-10-16 23:08:08 +00002064 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002065 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002066 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002067 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002068 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002069 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002070 ConstantExpr::getNeg(DivRHS));
2071
Chris Lattner57c8d992003-02-18 19:57:07 +00002072 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002073 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002074 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002075 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002076 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002077 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002078 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002079 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002080 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002081
Chris Lattner7a002fe2006-12-02 00:13:08 +00002082 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002085 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2086 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2087 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2088 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002089 } else if (Op0I->getOpcode() == Instruction::Sub) {
2090 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2091 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002092 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002093
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002094 ConstantInt *C1;
2095 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2096 if (X == Op1) { // X*C - X --> X * (C-1)
2097 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2098 return BinaryOperator::createMul(Op1, CP1);
2099 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002100
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002101 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2102 if (X == dyn_castFoldableMul(Op1, C2))
2103 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2104 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002105 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002106}
2107
Reid Spencer266e42b2006-12-23 06:05:41 +00002108/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002109/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002110static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2111 switch (pred) {
2112 case ICmpInst::ICMP_SLT:
2113 // True if LHS s< RHS and RHS == 0
2114 return RHS->isNullValue();
2115 case ICmpInst::ICMP_SLE:
2116 // True if LHS s<= RHS and RHS == -1
2117 return RHS->isAllOnesValue();
2118 case ICmpInst::ICMP_UGE:
2119 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2120 return RHS->getZExtValue() == (1ULL <<
2121 (RHS->getType()->getPrimitiveSizeInBits()-1));
2122 case ICmpInst::ICMP_UGT:
2123 // True if LHS u> RHS and RHS == high-bit-mask - 1
2124 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002125 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002126 default:
2127 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002128 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002129}
2130
Chris Lattner113f4f42002-06-25 16:13:24 +00002131Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002132 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002134
Chris Lattner81a7a232004-10-16 18:11:37 +00002135 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2136 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2137
Chris Lattnere6794492002-08-12 21:17:25 +00002138 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002139 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2140 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002141
2142 // ((X << C1)*C2) == (X * (C2 << C1))
2143 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2144 if (SI->getOpcode() == Instruction::Shl)
2145 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002146 return BinaryOperator::createMul(SI->getOperand(0),
2147 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002148
Chris Lattnercce81be2003-09-11 22:24:54 +00002149 if (CI->isNullValue())
2150 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2151 if (CI->equalsInt(1)) // X * 1 == X
2152 return ReplaceInstUsesWith(I, Op0);
2153 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002154 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002155
Reid Spencere0fc4df2006-10-20 07:07:24 +00002156 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002157 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2158 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002159 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002160 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002161 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002162 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002163 if (Op1F->isNullValue())
2164 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002165
Chris Lattner3082c5a2003-02-18 19:28:33 +00002166 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2167 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2168 if (Op1F->getValue() == 1.0)
2169 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2170 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002171
2172 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2173 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2174 isa<ConstantInt>(Op0I->getOperand(1))) {
2175 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2176 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2177 Op1, "tmp");
2178 InsertNewInstBefore(Add, I);
2179 Value *C1C2 = ConstantExpr::getMul(Op1,
2180 cast<Constant>(Op0I->getOperand(1)));
2181 return BinaryOperator::createAdd(Add, C1C2);
2182
2183 }
Chris Lattner183b3362004-04-09 19:05:30 +00002184
2185 // Try to fold constant mul into select arguments.
2186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002187 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002188 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002189
2190 if (isa<PHINode>(Op0))
2191 if (Instruction *NV = FoldOpIntoPhi(I))
2192 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002193 }
2194
Chris Lattner934a64cf2003-03-10 23:23:04 +00002195 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2196 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002197 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002198
Chris Lattner2635b522004-02-23 05:39:21 +00002199 // If one of the operands of the multiply is a cast from a boolean value, then
2200 // we know the bool is either zero or one, so this is a 'masking' multiply.
2201 // See if we can simplify things based on how the boolean was originally
2202 // formed.
2203 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002204 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002205 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002206 BoolCast = CI;
2207 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002208 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002209 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002210 BoolCast = CI;
2211 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002212 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002213 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2214 const Type *SCOpTy = SCIOp0->getType();
2215
Reid Spencer266e42b2006-12-23 06:05:41 +00002216 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002217 // multiply into a shift/and combination.
2218 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002219 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002220 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002221 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002222 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002223 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002224 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002225 BoolCast->getOperand(0)->getName()+
2226 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002227
2228 // If the multiply type is not the same as the source type, sign extend
2229 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002230 if (I.getType() != V->getType()) {
2231 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2232 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2233 Instruction::CastOps opcode =
2234 (SrcBits == DstBits ? Instruction::BitCast :
2235 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2236 V = InsertCastBefore(opcode, V, I.getType(), I);
2237 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002238
Chris Lattner2635b522004-02-23 05:39:21 +00002239 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002240 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002241 }
2242 }
2243 }
2244
Chris Lattner113f4f42002-06-25 16:13:24 +00002245 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002246}
2247
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002248/// This function implements the transforms on div instructions that work
2249/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2250/// used by the visitors to those instructions.
2251/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002252Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002254
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002255 // undef / X -> 0
2256 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002257 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002258
2259 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002260 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002261 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002262
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002263 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002264 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2265 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266 // same basic block, then we replace the select with Y, and the condition
2267 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002268 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002269 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002270 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2271 if (ST->isNullValue()) {
2272 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2273 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002274 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002275 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2276 I.setOperand(1, SI->getOperand(2));
2277 else
2278 UpdateValueUsesWith(SI, SI->getOperand(2));
2279 return &I;
2280 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002281
Chris Lattnerd79dc792006-09-09 20:26:32 +00002282 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2283 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2284 if (ST->isNullValue()) {
2285 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2286 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002287 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002288 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2289 I.setOperand(1, SI->getOperand(1));
2290 else
2291 UpdateValueUsesWith(SI, SI->getOperand(1));
2292 return &I;
2293 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002294 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002295
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002296 return 0;
2297}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002298
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002299/// This function implements the transforms common to both integer division
2300/// instructions (udiv and sdiv). It is called by the visitors to those integer
2301/// division instructions.
2302/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002303Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002304 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2305
2306 if (Instruction *Common = commonDivTransforms(I))
2307 return Common;
2308
2309 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2310 // div X, 1 == X
2311 if (RHS->equalsInt(1))
2312 return ReplaceInstUsesWith(I, Op0);
2313
2314 // (X / C1) / C2 -> X / (C1*C2)
2315 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2316 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2317 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2318 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2319 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002320 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002321
2322 if (!RHS->isNullValue()) { // avoid X udiv 0
2323 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2324 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2325 return R;
2326 if (isa<PHINode>(Op0))
2327 if (Instruction *NV = FoldOpIntoPhi(I))
2328 return NV;
2329 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002330 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002331
Chris Lattner3082c5a2003-02-18 19:28:33 +00002332 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002333 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002334 if (LHS->equalsInt(0))
2335 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2336
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002337 return 0;
2338}
2339
2340Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2342
2343 // Handle the integer div common cases
2344 if (Instruction *Common = commonIDivTransforms(I))
2345 return Common;
2346
2347 // X udiv C^2 -> X >> C
2348 // Check to see if this is an unsigned division with an exact power of 2,
2349 // if so, convert to a right shift.
2350 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2351 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2352 if (isPowerOf2_64(Val)) {
2353 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002354 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002355 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002356 }
2357 }
2358
2359 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2360 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2361 if (RHSI->getOpcode() == Instruction::Shl &&
2362 isa<ConstantInt>(RHSI->getOperand(0))) {
2363 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2364 if (isPowerOf2_64(C1)) {
2365 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002366 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002367 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002368 Constant *C2V = ConstantInt::get(NTy, C2);
2369 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002370 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002371 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002372 }
2373 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002374 }
2375
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002376 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2377 // where C1&C2 are powers of two.
2378 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2379 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2380 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2381 if (!STO->isNullValue() && !STO->isNullValue()) {
2382 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2383 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2384 // Compute the shift amounts
2385 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002387 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002388 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002389 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002390 TSI = InsertNewInstBefore(TSI, I);
2391
2392 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002393 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002394 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002395 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002396 FSI = InsertNewInstBefore(FSI, I);
2397
2398 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002399 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002400 }
2401 }
2402 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002403 return 0;
2404}
2405
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002406Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2407 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2408
2409 // Handle the integer div common cases
2410 if (Instruction *Common = commonIDivTransforms(I))
2411 return Common;
2412
2413 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2414 // sdiv X, -1 == -X
2415 if (RHS->isAllOnesValue())
2416 return BinaryOperator::createNeg(Op0);
2417
2418 // -X/C -> X/-C
2419 if (Value *LHSNeg = dyn_castNegVal(Op0))
2420 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2421 }
2422
2423 // If the sign bits of both operands are zero (i.e. we can prove they are
2424 // unsigned inputs), turn this into a udiv.
2425 if (I.getType()->isInteger()) {
2426 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2427 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2428 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2429 }
2430 }
2431
2432 return 0;
2433}
2434
2435Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2436 return commonDivTransforms(I);
2437}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002438
Chris Lattner85dda9a2006-03-02 06:50:58 +00002439/// GetFactor - If we can prove that the specified value is at least a multiple
2440/// of some factor, return that factor.
2441static Constant *GetFactor(Value *V) {
2442 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2443 return CI;
2444
2445 // Unless we can be tricky, we know this is a multiple of 1.
2446 Constant *Result = ConstantInt::get(V->getType(), 1);
2447
2448 Instruction *I = dyn_cast<Instruction>(V);
2449 if (!I) return Result;
2450
2451 if (I->getOpcode() == Instruction::Mul) {
2452 // Handle multiplies by a constant, etc.
2453 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2454 GetFactor(I->getOperand(1)));
2455 } else if (I->getOpcode() == Instruction::Shl) {
2456 // (X<<C) -> X * (1 << C)
2457 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2458 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2459 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2460 }
2461 } else if (I->getOpcode() == Instruction::And) {
2462 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2463 // X & 0xFFF0 is known to be a multiple of 16.
2464 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2465 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2466 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002467 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002468 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002469 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002470 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002471 if (!CI->isIntegerCast())
2472 return Result;
2473 Value *Op = CI->getOperand(0);
2474 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002475 }
2476 return Result;
2477}
2478
Reid Spencer7eb55b32006-11-02 01:53:59 +00002479/// This function implements the transforms on rem instructions that work
2480/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2481/// is used by the visitors to those instructions.
2482/// @brief Transforms common to all three rem instructions
2483Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002484 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002485
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002486 // 0 % X == 0, we don't need to preserve faults!
2487 if (Constant *LHS = dyn_cast<Constant>(Op0))
2488 if (LHS->isNullValue())
2489 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2490
2491 if (isa<UndefValue>(Op0)) // undef % X -> 0
2492 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2493 if (isa<UndefValue>(Op1))
2494 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002495
2496 // Handle cases involving: rem X, (select Cond, Y, Z)
2497 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2498 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2499 // the same basic block, then we replace the select with Y, and the
2500 // condition of the select with false (if the cond value is in the same
2501 // BB). If the select has uses other than the div, this allows them to be
2502 // simplified also.
2503 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2504 if (ST->isNullValue()) {
2505 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2506 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002507 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002508 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2509 I.setOperand(1, SI->getOperand(2));
2510 else
2511 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002512 return &I;
2513 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002514 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2515 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2516 if (ST->isNullValue()) {
2517 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2518 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002519 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002520 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2521 I.setOperand(1, SI->getOperand(1));
2522 else
2523 UpdateValueUsesWith(SI, SI->getOperand(1));
2524 return &I;
2525 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002526 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002527
Reid Spencer7eb55b32006-11-02 01:53:59 +00002528 return 0;
2529}
2530
2531/// This function implements the transforms common to both integer remainder
2532/// instructions (urem and srem). It is called by the visitors to those integer
2533/// remainder instructions.
2534/// @brief Common integer remainder transforms
2535Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2536 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2537
2538 if (Instruction *common = commonRemTransforms(I))
2539 return common;
2540
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002541 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002542 // X % 0 == undef, we don't need to preserve faults!
2543 if (RHS->equalsInt(0))
2544 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2545
Chris Lattner3082c5a2003-02-18 19:28:33 +00002546 if (RHS->equalsInt(1)) // X % 1 == 0
2547 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2548
Chris Lattnerb70f1412006-02-28 05:49:21 +00002549 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2550 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2551 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2552 return R;
2553 } else if (isa<PHINode>(Op0I)) {
2554 if (Instruction *NV = FoldOpIntoPhi(I))
2555 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002556 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002557 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2558 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002559 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002560 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002561 }
2562
Reid Spencer7eb55b32006-11-02 01:53:59 +00002563 return 0;
2564}
2565
2566Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569 if (Instruction *common = commonIRemTransforms(I))
2570 return common;
2571
2572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2573 // X urem C^2 -> X and C
2574 // Check to see if this is an unsigned remainder with an exact power of 2,
2575 // if so, convert to a bitwise and.
2576 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2577 if (isPowerOf2_64(C->getZExtValue()))
2578 return BinaryOperator::createAnd(Op0, SubOne(C));
2579 }
2580
Chris Lattner2e90b732006-02-05 07:54:04 +00002581 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002582 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2583 if (RHSI->getOpcode() == Instruction::Shl &&
2584 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002585 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002586 if (isPowerOf2_64(C1)) {
2587 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2588 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2589 "tmp"), I);
2590 return BinaryOperator::createAnd(Op0, Add);
2591 }
2592 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002593 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002594
Reid Spencer7eb55b32006-11-02 01:53:59 +00002595 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2596 // where C1&C2 are powers of two.
2597 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2598 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2599 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2600 // STO == 0 and SFO == 0 handled above.
2601 if (isPowerOf2_64(STO->getZExtValue()) &&
2602 isPowerOf2_64(SFO->getZExtValue())) {
2603 Value *TrueAnd = InsertNewInstBefore(
2604 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2605 Value *FalseAnd = InsertNewInstBefore(
2606 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2607 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2608 }
2609 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002610 }
2611
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002612 return 0;
2613}
2614
Reid Spencer7eb55b32006-11-02 01:53:59 +00002615Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2616 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2617
2618 if (Instruction *common = commonIRemTransforms(I))
2619 return common;
2620
2621 if (Value *RHSNeg = dyn_castNegVal(Op1))
2622 if (!isa<ConstantInt>(RHSNeg) ||
2623 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2624 // X % -Y -> X % Y
2625 AddUsesToWorkList(I);
2626 I.setOperand(1, RHSNeg);
2627 return &I;
2628 }
2629
2630 // If the top bits of both operands are zero (i.e. we can prove they are
2631 // unsigned inputs), turn this into a urem.
2632 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2633 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2634 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2635 return BinaryOperator::createURem(Op0, Op1, I.getName());
2636 }
2637
2638 return 0;
2639}
2640
2641Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002642 return commonRemTransforms(I);
2643}
2644
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002645// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002646static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2647 if (isSigned) {
2648 // Calculate 0111111111..11111
2649 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2650 int64_t Val = INT64_MAX; // All ones
2651 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2652 return C->getSExtValue() == Val-1;
2653 }
2654 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002655}
2656
2657// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002658static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2659 if (isSigned) {
2660 // Calculate 1111111111000000000000
2661 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2662 int64_t Val = -1; // All ones
2663 Val <<= TypeBits-1; // Shift over to the right spot
2664 return C->getSExtValue() == Val+1;
2665 }
2666 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002667}
2668
Chris Lattner35167c32004-06-09 07:59:58 +00002669// isOneBitSet - Return true if there is exactly one bit set in the specified
2670// constant.
2671static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002672 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002673 return V && (V & (V-1)) == 0;
2674}
2675
Chris Lattner8fc5af42004-09-23 21:46:38 +00002676#if 0 // Currently unused
2677// isLowOnes - Return true if the constant is of the form 0+1+.
2678static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002679 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002680
2681 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002682 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002683
2684 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2685 return U && V && (U & V) == 0;
2686}
2687#endif
2688
2689// isHighOnes - Return true if the constant is of the form 1+0+.
2690// This is the same as lowones(~X).
2691static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002692 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002693 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002694
2695 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002696 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002697
2698 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2699 return U && V && (U & V) == 0;
2700}
2701
Reid Spencer266e42b2006-12-23 06:05:41 +00002702/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002703/// are carefully arranged to allow folding of expressions such as:
2704///
2705/// (A < B) | (A > B) --> (A != B)
2706///
Reid Spencer266e42b2006-12-23 06:05:41 +00002707/// Note that this is only valid if the first and second predicates have the
2708/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002709///
Reid Spencer266e42b2006-12-23 06:05:41 +00002710/// Three bits are used to represent the condition, as follows:
2711/// 0 A > B
2712/// 1 A == B
2713/// 2 A < B
2714///
2715/// <=> Value Definition
2716/// 000 0 Always false
2717/// 001 1 A > B
2718/// 010 2 A == B
2719/// 011 3 A >= B
2720/// 100 4 A < B
2721/// 101 5 A != B
2722/// 110 6 A <= B
2723/// 111 7 Always true
2724///
2725static unsigned getICmpCode(const ICmpInst *ICI) {
2726 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002727 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002728 case ICmpInst::ICMP_UGT: return 1; // 001
2729 case ICmpInst::ICMP_SGT: return 1; // 001
2730 case ICmpInst::ICMP_EQ: return 2; // 010
2731 case ICmpInst::ICMP_UGE: return 3; // 011
2732 case ICmpInst::ICMP_SGE: return 3; // 011
2733 case ICmpInst::ICMP_ULT: return 4; // 100
2734 case ICmpInst::ICMP_SLT: return 4; // 100
2735 case ICmpInst::ICMP_NE: return 5; // 101
2736 case ICmpInst::ICMP_ULE: return 6; // 110
2737 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002738 // True -> 7
2739 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002740 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002741 return 0;
2742 }
2743}
2744
Reid Spencer266e42b2006-12-23 06:05:41 +00002745/// getICmpValue - This is the complement of getICmpCode, which turns an
2746/// opcode and two operands into either a constant true or false, or a brand
2747/// new /// ICmp instruction. The sign is passed in to determine which kind
2748/// of predicate to use in new icmp instructions.
2749static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2750 switch (code) {
2751 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002752 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002753 case 1:
2754 if (sign)
2755 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2756 else
2757 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2758 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2759 case 3:
2760 if (sign)
2761 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2762 else
2763 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2764 case 4:
2765 if (sign)
2766 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2767 else
2768 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2769 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2770 case 6:
2771 if (sign)
2772 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2773 else
2774 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002775 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002776 }
2777}
2778
Reid Spencer266e42b2006-12-23 06:05:41 +00002779static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2780 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2781 (ICmpInst::isSignedPredicate(p1) &&
2782 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2783 (ICmpInst::isSignedPredicate(p2) &&
2784 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2785}
2786
2787namespace {
2788// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2789struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002790 InstCombiner &IC;
2791 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002792 ICmpInst::Predicate pred;
2793 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2794 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2795 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002796 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002797 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2798 if (PredicatesFoldable(pred, ICI->getPredicate()))
2799 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2800 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002801 return false;
2802 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002803 Instruction *apply(Instruction &Log) const {
2804 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2805 if (ICI->getOperand(0) != LHS) {
2806 assert(ICI->getOperand(1) == LHS);
2807 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002808 }
2809
Reid Spencer266e42b2006-12-23 06:05:41 +00002810 unsigned LHSCode = getICmpCode(ICI);
2811 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002812 unsigned Code;
2813 switch (Log.getOpcode()) {
2814 case Instruction::And: Code = LHSCode & RHSCode; break;
2815 case Instruction::Or: Code = LHSCode | RHSCode; break;
2816 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002817 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002818 }
2819
Reid Spencer266e42b2006-12-23 06:05:41 +00002820 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002821 if (Instruction *I = dyn_cast<Instruction>(RV))
2822 return I;
2823 // Otherwise, it's a constant boolean value...
2824 return IC.ReplaceInstUsesWith(Log, RV);
2825 }
2826};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002827} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002828
Chris Lattnerba1cb382003-09-19 17:17:26 +00002829// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2830// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2831// guaranteed to be either a shift instruction or a binary operator.
2832Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002833 ConstantInt *OpRHS,
2834 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002835 BinaryOperator &TheAnd) {
2836 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002837 Constant *Together = 0;
2838 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002839 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002840
Chris Lattnerba1cb382003-09-19 17:17:26 +00002841 switch (Op->getOpcode()) {
2842 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002843 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002844 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2845 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002846 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002847 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002848 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002849 }
2850 break;
2851 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002852 if (Together == AndRHS) // (X | C) & C --> C
2853 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002854
Chris Lattner86102b82005-01-01 16:22:27 +00002855 if (Op->hasOneUse() && Together != OpRHS) {
2856 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2857 std::string Op0Name = Op->getName(); Op->setName("");
2858 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2859 InsertNewInstBefore(Or, TheAnd);
2860 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002861 }
2862 break;
2863 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002864 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002865 // Adding a one to a single bit bit-field should be turned into an XOR
2866 // of the bit. First thing to check is to see if this AND is with a
2867 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002868 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002869
2870 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002871 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002872
2873 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002874 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002875 // Ok, at this point, we know that we are masking the result of the
2876 // ADD down to exactly one bit. If the constant we are adding has
2877 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002878 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002879
Chris Lattnerba1cb382003-09-19 17:17:26 +00002880 // Check to see if any bits below the one bit set in AndRHSV are set.
2881 if ((AddRHS & (AndRHSV-1)) == 0) {
2882 // If not, the only thing that can effect the output of the AND is
2883 // the bit specified by AndRHSV. If that bit is set, the effect of
2884 // the XOR is to toggle the bit. If it is clear, then the ADD has
2885 // no effect.
2886 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2887 TheAnd.setOperand(0, X);
2888 return &TheAnd;
2889 } else {
2890 std::string Name = Op->getName(); Op->setName("");
2891 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002892 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002893 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002894 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002895 }
2896 }
2897 }
2898 }
2899 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002900
2901 case Instruction::Shl: {
2902 // We know that the AND will not produce any of the bits shifted in, so if
2903 // the anded constant includes them, clear them now!
2904 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002905 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002906 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2907 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002908
Chris Lattner7e794272004-09-24 15:21:34 +00002909 if (CI == ShlMask) { // Masking out bits that the shift already masks
2910 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2911 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002912 TheAnd.setOperand(1, CI);
2913 return &TheAnd;
2914 }
2915 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002916 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002917 case Instruction::LShr:
2918 {
Chris Lattner2da29172003-09-19 19:05:02 +00002919 // We know that the AND will not produce any of the bits shifted in, so if
2920 // the anded constant includes them, clear them now! This only applies to
2921 // unsigned shifts, because a signed shr may bring in set bits!
2922 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002923 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002924 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2925 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002926
Reid Spencerfdff9382006-11-08 06:47:33 +00002927 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2928 return ReplaceInstUsesWith(TheAnd, Op);
2929 } else if (CI != AndRHS) {
2930 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2931 return &TheAnd;
2932 }
2933 break;
2934 }
2935 case Instruction::AShr:
2936 // Signed shr.
2937 // See if this is shifting in some sign extension, then masking it out
2938 // with an and.
2939 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002940 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002941 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002942 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2943 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002944 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002945 // Make the argument unsigned.
2946 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002947 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2948 OpRHS, Op->getName()), TheAnd);
2949 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002950 }
Chris Lattner2da29172003-09-19 19:05:02 +00002951 }
2952 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002953 }
2954 return 0;
2955}
2956
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002957
Chris Lattner6862fbd2004-09-29 17:40:11 +00002958/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2959/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002960/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2961/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002962/// insert new instructions.
2963Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002964 bool isSigned, bool Inside,
2965 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002966 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002967 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002968 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002969
Chris Lattner6862fbd2004-09-29 17:40:11 +00002970 if (Inside) {
2971 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002972 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002973
Reid Spencer266e42b2006-12-23 06:05:41 +00002974 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002975 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002976 ICmpInst::Predicate pred = (isSigned ?
2977 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2978 return new ICmpInst(pred, V, Hi);
2979 }
2980
2981 // Emit V-Lo <u Hi-Lo
2982 Constant *NegLo = ConstantExpr::getNeg(Lo);
2983 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002984 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002985 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2986 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002987 }
2988
2989 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002990 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002991
Reid Spencer266e42b2006-12-23 06:05:41 +00002992 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002993 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002994 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002995 ICmpInst::Predicate pred = (isSigned ?
2996 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2997 return new ICmpInst(pred, V, Hi);
2998 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00002999
Reid Spencer266e42b2006-12-23 06:05:41 +00003000 // Emit V-Lo > Hi-1-Lo
3001 Constant *NegLo = ConstantExpr::getNeg(Lo);
3002 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003003 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003004 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3005 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003006}
3007
Chris Lattnerb4b25302005-09-18 07:22:02 +00003008// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3009// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3010// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3011// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003012static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003013 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003014 if (!isShiftedMask_64(V)) return false;
3015
3016 // look for the first zero bit after the run of ones
3017 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3018 // look for the first non-zero bit
3019 ME = 64-CountLeadingZeros_64(V);
3020 return true;
3021}
3022
3023
3024
3025/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3026/// where isSub determines whether the operator is a sub. If we can fold one of
3027/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003028///
3029/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3030/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3031/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3032///
3033/// return (A +/- B).
3034///
3035Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003036 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003037 Instruction &I) {
3038 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3039 if (!LHSI || LHSI->getNumOperands() != 2 ||
3040 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3041
3042 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3043
3044 switch (LHSI->getOpcode()) {
3045 default: return 0;
3046 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003047 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3048 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003049 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003050 break;
3051
3052 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3053 // part, we don't need any explicit masks to take them out of A. If that
3054 // is all N is, ignore it.
3055 unsigned MB, ME;
3056 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003057 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3058 Mask >>= 64-MB+1;
3059 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003060 break;
3061 }
3062 }
Chris Lattneraf517572005-09-18 04:24:45 +00003063 return 0;
3064 case Instruction::Or:
3065 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003066 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003067 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003068 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003069 break;
3070 return 0;
3071 }
3072
3073 Instruction *New;
3074 if (isSub)
3075 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3076 else
3077 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3078 return InsertNewInstBefore(New, I);
3079}
3080
Chris Lattner113f4f42002-06-25 16:13:24 +00003081Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003082 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003083 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003084
Chris Lattner81a7a232004-10-16 18:11:37 +00003085 if (isa<UndefValue>(Op1)) // X & undef -> 0
3086 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3087
Chris Lattner86102b82005-01-01 16:22:27 +00003088 // and X, X = X
3089 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003090 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003091
Chris Lattner5b2edb12006-02-12 08:02:11 +00003092 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003093 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003094 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003095 if (!isa<PackedType>(I.getType()) &&
3096 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003097 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003098 return &I;
3099
Zhou Sheng75b871f2007-01-11 12:24:14 +00003100 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003101 uint64_t AndRHSMask = AndRHS->getZExtValue();
3102 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003103 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003104
Chris Lattnerba1cb382003-09-19 17:17:26 +00003105 // Optimize a variety of ((val OP C1) & C2) combinations...
3106 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3107 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003108 Value *Op0LHS = Op0I->getOperand(0);
3109 Value *Op0RHS = Op0I->getOperand(1);
3110 switch (Op0I->getOpcode()) {
3111 case Instruction::Xor:
3112 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003113 // If the mask is only needed on one incoming arm, push it up.
3114 if (Op0I->hasOneUse()) {
3115 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3116 // Not masking anything out for the LHS, move to RHS.
3117 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3118 Op0RHS->getName()+".masked");
3119 InsertNewInstBefore(NewRHS, I);
3120 return BinaryOperator::create(
3121 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003122 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003123 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003124 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3125 // Not masking anything out for the RHS, move to LHS.
3126 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3127 Op0LHS->getName()+".masked");
3128 InsertNewInstBefore(NewLHS, I);
3129 return BinaryOperator::create(
3130 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3131 }
3132 }
3133
Chris Lattner86102b82005-01-01 16:22:27 +00003134 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003135 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003136 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3137 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3138 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3139 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3140 return BinaryOperator::createAnd(V, AndRHS);
3141 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3142 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003143 break;
3144
3145 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003146 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3147 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3148 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3149 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3150 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003151 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003152 }
3153
Chris Lattner16464b32003-07-23 19:25:52 +00003154 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003155 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003156 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003157 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003158 // If this is an integer truncation or change from signed-to-unsigned, and
3159 // if the source is an and/or with immediate, transform it. This
3160 // frequently occurs for bitfield accesses.
3161 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003162 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003163 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003164 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003165 if (CastOp->getOpcode() == Instruction::And) {
3166 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003167 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3168 // This will fold the two constants together, which may allow
3169 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003170 Instruction *NewCast = CastInst::createTruncOrBitCast(
3171 CastOp->getOperand(0), I.getType(),
3172 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003173 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003174 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003175 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003176 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003177 return BinaryOperator::createAnd(NewCast, C3);
3178 } else if (CastOp->getOpcode() == Instruction::Or) {
3179 // Change: and (cast (or X, C1) to T), C2
3180 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003181 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003182 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3183 return ReplaceInstUsesWith(I, AndRHS);
3184 }
3185 }
Chris Lattner33217db2003-07-23 19:36:21 +00003186 }
Chris Lattner183b3362004-04-09 19:05:30 +00003187
3188 // Try to fold constant and into select arguments.
3189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003191 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003192 if (isa<PHINode>(Op0))
3193 if (Instruction *NV = FoldOpIntoPhi(I))
3194 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003195 }
3196
Chris Lattnerbb74e222003-03-10 23:06:50 +00003197 Value *Op0NotVal = dyn_castNotVal(Op0);
3198 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003199
Chris Lattner023a4832004-06-18 06:07:51 +00003200 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3201 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3202
Misha Brukman9c003d82004-07-30 12:50:08 +00003203 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003204 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003205 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3206 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003207 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003208 return BinaryOperator::createNot(Or);
3209 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003210
3211 {
3212 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003213 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3214 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3215 return ReplaceInstUsesWith(I, Op1);
3216 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3217 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3218 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003219
3220 if (Op0->hasOneUse() &&
3221 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3222 if (A == Op1) { // (A^B)&A -> A&(A^B)
3223 I.swapOperands(); // Simplify below
3224 std::swap(Op0, Op1);
3225 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3226 cast<BinaryOperator>(Op0)->swapOperands();
3227 I.swapOperands(); // Simplify below
3228 std::swap(Op0, Op1);
3229 }
3230 }
3231 if (Op1->hasOneUse() &&
3232 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3233 if (B == Op0) { // B&(A^B) -> B&(B^A)
3234 cast<BinaryOperator>(Op1)->swapOperands();
3235 std::swap(A, B);
3236 }
3237 if (A == Op0) { // A&(A^B) -> A & ~B
3238 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3239 InsertNewInstBefore(NotB, I);
3240 return BinaryOperator::createAnd(A, NotB);
3241 }
3242 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003243 }
3244
Reid Spencer266e42b2006-12-23 06:05:41 +00003245 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3246 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3247 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003248 return R;
3249
Chris Lattner623826c2004-09-28 21:48:02 +00003250 Value *LHSVal, *RHSVal;
3251 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003252 ICmpInst::Predicate LHSCC, RHSCC;
3253 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3254 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3255 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3256 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3257 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3258 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3259 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3260 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003261 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003262 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3263 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3264 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3265 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003266 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003267 std::swap(LHS, RHS);
3268 std::swap(LHSCst, RHSCst);
3269 std::swap(LHSCC, RHSCC);
3270 }
3271
Reid Spencer266e42b2006-12-23 06:05:41 +00003272 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003273 // comparing a value against two constants and and'ing the result
3274 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003275 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3276 // (from the FoldICmpLogical check above), that the two constants
3277 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003278 assert(LHSCst != RHSCst && "Compares not folded above?");
3279
3280 switch (LHSCC) {
3281 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003282 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003283 switch (RHSCC) {
3284 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003285 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3286 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3287 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003288 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003289 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3290 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3291 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003292 return ReplaceInstUsesWith(I, LHS);
3293 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003294 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003295 switch (RHSCC) {
3296 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003297 case ICmpInst::ICMP_ULT:
3298 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3299 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3300 break; // (X != 13 & X u< 15) -> no change
3301 case ICmpInst::ICMP_SLT:
3302 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3303 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3304 break; // (X != 13 & X s< 15) -> no change
3305 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3306 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3307 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003308 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003309 case ICmpInst::ICMP_NE:
3310 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003311 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3312 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3313 LHSVal->getName()+".off");
3314 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003315 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003316 }
3317 break; // (X != 13 & X != 15) -> no change
3318 }
3319 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003320 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003321 switch (RHSCC) {
3322 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003323 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3324 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003325 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003326 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3327 break;
3328 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3329 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003330 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003331 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3332 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003333 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003334 break;
3335 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003336 switch (RHSCC) {
3337 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003338 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3339 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003340 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003341 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3342 break;
3343 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3344 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003345 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003346 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3347 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003348 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003349 break;
3350 case ICmpInst::ICMP_UGT:
3351 switch (RHSCC) {
3352 default: assert(0 && "Unknown integer condition code!");
3353 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3354 return ReplaceInstUsesWith(I, LHS);
3355 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3356 return ReplaceInstUsesWith(I, RHS);
3357 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3358 break;
3359 case ICmpInst::ICMP_NE:
3360 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3361 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3362 break; // (X u> 13 & X != 15) -> no change
3363 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3364 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3365 true, I);
3366 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3367 break;
3368 }
3369 break;
3370 case ICmpInst::ICMP_SGT:
3371 switch (RHSCC) {
3372 default: assert(0 && "Unknown integer condition code!");
3373 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3374 return ReplaceInstUsesWith(I, LHS);
3375 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3376 return ReplaceInstUsesWith(I, RHS);
3377 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3378 break;
3379 case ICmpInst::ICMP_NE:
3380 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3381 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3382 break; // (X s> 13 & X != 15) -> no change
3383 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3384 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3385 true, I);
3386 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3387 break;
3388 }
3389 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003390 }
3391 }
3392 }
3393
Chris Lattner3af10532006-05-05 06:39:07 +00003394 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003395 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3396 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3397 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3398 const Type *SrcTy = Op0C->getOperand(0)->getType();
3399 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3400 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003401 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3402 I.getType(), TD) &&
3403 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3404 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003405 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3406 Op1C->getOperand(0),
3407 I.getName());
3408 InsertNewInstBefore(NewOp, I);
3409 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3410 }
Chris Lattner3af10532006-05-05 06:39:07 +00003411 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003412
3413 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3414 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3415 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3416 if (SI0->getOpcode() == SI1->getOpcode() &&
3417 SI0->getOperand(1) == SI1->getOperand(1) &&
3418 (SI0->hasOneUse() || SI1->hasOneUse())) {
3419 Instruction *NewOp =
3420 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3421 SI1->getOperand(0),
3422 SI0->getName()), I);
3423 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3424 }
Chris Lattner3af10532006-05-05 06:39:07 +00003425 }
3426
Chris Lattner113f4f42002-06-25 16:13:24 +00003427 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003428}
3429
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003430/// CollectBSwapParts - Look to see if the specified value defines a single byte
3431/// in the result. If it does, and if the specified byte hasn't been filled in
3432/// yet, fill it in and return false.
3433static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3434 Instruction *I = dyn_cast<Instruction>(V);
3435 if (I == 0) return true;
3436
3437 // If this is an or instruction, it is an inner node of the bswap.
3438 if (I->getOpcode() == Instruction::Or)
3439 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3440 CollectBSwapParts(I->getOperand(1), ByteValues);
3441
3442 // If this is a shift by a constant int, and it is "24", then its operand
3443 // defines a byte. We only handle unsigned types here.
3444 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3445 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003446 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003447 8*(ByteValues.size()-1))
3448 return true;
3449
3450 unsigned DestNo;
3451 if (I->getOpcode() == Instruction::Shl) {
3452 // X << 24 defines the top byte with the lowest of the input bytes.
3453 DestNo = ByteValues.size()-1;
3454 } else {
3455 // X >>u 24 defines the low byte with the highest of the input bytes.
3456 DestNo = 0;
3457 }
3458
3459 // If the destination byte value is already defined, the values are or'd
3460 // together, which isn't a bswap (unless it's an or of the same bits).
3461 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3462 return true;
3463 ByteValues[DestNo] = I->getOperand(0);
3464 return false;
3465 }
3466
3467 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3468 // don't have this.
3469 Value *Shift = 0, *ShiftLHS = 0;
3470 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3471 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3472 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3473 return true;
3474 Instruction *SI = cast<Instruction>(Shift);
3475
3476 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003477 if (ShiftAmt->getZExtValue() & 7 ||
3478 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003479 return true;
3480
3481 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3482 unsigned DestByte;
3483 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003484 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003485 break;
3486 // Unknown mask for bswap.
3487 if (DestByte == ByteValues.size()) return true;
3488
Reid Spencere0fc4df2006-10-20 07:07:24 +00003489 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003490 unsigned SrcByte;
3491 if (SI->getOpcode() == Instruction::Shl)
3492 SrcByte = DestByte - ShiftBytes;
3493 else
3494 SrcByte = DestByte + ShiftBytes;
3495
3496 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3497 if (SrcByte != ByteValues.size()-DestByte-1)
3498 return true;
3499
3500 // If the destination byte value is already defined, the values are or'd
3501 // together, which isn't a bswap (unless it's an or of the same bits).
3502 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3503 return true;
3504 ByteValues[DestByte] = SI->getOperand(0);
3505 return false;
3506}
3507
3508/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3509/// If so, insert the new bswap intrinsic and return it.
3510Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3511 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003512 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003513 return 0;
3514
3515 /// ByteValues - For each byte of the result, we keep track of which value
3516 /// defines each byte.
3517 std::vector<Value*> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003518 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003519
3520 // Try to find all the pieces corresponding to the bswap.
3521 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3522 CollectBSwapParts(I.getOperand(1), ByteValues))
3523 return 0;
3524
3525 // Check to see if all of the bytes come from the same value.
3526 Value *V = ByteValues[0];
3527 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3528
3529 // Check to make sure that all of the bytes come from the same value.
3530 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3531 if (ByteValues[i] != V)
3532 return 0;
3533
3534 // If they do then *success* we can turn this into a bswap. Figure out what
3535 // bswap to make it into.
3536 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003537 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003538 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003539 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003540 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003541 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003542 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003543 FnName = "llvm.bswap.i64";
3544 else
3545 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003546 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003547 return new CallInst(F, V);
3548}
3549
3550
Chris Lattner113f4f42002-06-25 16:13:24 +00003551Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003552 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003554
Chris Lattner81a7a232004-10-16 18:11:37 +00003555 if (isa<UndefValue>(Op1))
3556 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003557 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003558
Chris Lattner5b2edb12006-02-12 08:02:11 +00003559 // or X, X = X
3560 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003561 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003562
Chris Lattner5b2edb12006-02-12 08:02:11 +00003563 // See if we can simplify any instructions used by the instruction whose sole
3564 // purpose is to compute bits we don't care about.
3565 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003566 if (!isa<PackedType>(I.getType()) &&
3567 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003568 KnownZero, KnownOne))
3569 return &I;
3570
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003571 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003573 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003574 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3575 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003576 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3577 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003578 InsertNewInstBefore(Or, I);
3579 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3580 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003581
Chris Lattnerd4252a72004-07-30 07:50:03 +00003582 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3583 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3584 std::string Op0Name = Op0->getName(); Op0->setName("");
3585 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3586 InsertNewInstBefore(Or, I);
3587 return BinaryOperator::createXor(Or,
3588 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003589 }
Chris Lattner183b3362004-04-09 19:05:30 +00003590
3591 // Try to fold constant and into select arguments.
3592 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003593 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003594 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003595 if (isa<PHINode>(Op0))
3596 if (Instruction *NV = FoldOpIntoPhi(I))
3597 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003598 }
3599
Chris Lattner330628a2006-01-06 17:59:59 +00003600 Value *A = 0, *B = 0;
3601 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003602
3603 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3604 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3605 return ReplaceInstUsesWith(I, Op1);
3606 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3607 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3608 return ReplaceInstUsesWith(I, Op0);
3609
Chris Lattnerb7845d62006-07-10 20:25:24 +00003610 // (A | B) | C and A | (B | C) -> bswap if possible.
3611 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003612 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003613 match(Op1, m_Or(m_Value(), m_Value())) ||
3614 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3615 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003616 if (Instruction *BSwap = MatchBSwap(I))
3617 return BSwap;
3618 }
3619
Chris Lattnerb62f5082005-05-09 04:58:36 +00003620 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3621 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003622 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003623 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3624 Op0->setName("");
3625 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3626 }
3627
3628 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3629 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003630 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003631 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3632 Op0->setName("");
3633 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3634 }
3635
Chris Lattner15212982005-09-18 03:42:07 +00003636 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003637 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003638 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3639
3640 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3641 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3642
3643
Chris Lattner01f56c62005-09-18 06:02:59 +00003644 // If we have: ((V + N) & C1) | (V & C2)
3645 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3646 // replace with V+N.
3647 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003648 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003649 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003650 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3651 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003652 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003653 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003654 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003655 return ReplaceInstUsesWith(I, A);
3656 }
3657 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003658 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003659 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3660 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003661 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003662 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003663 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003664 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003665 }
3666 }
3667 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003668
3669 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3670 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3671 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3672 if (SI0->getOpcode() == SI1->getOpcode() &&
3673 SI0->getOperand(1) == SI1->getOperand(1) &&
3674 (SI0->hasOneUse() || SI1->hasOneUse())) {
3675 Instruction *NewOp =
3676 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3677 SI1->getOperand(0),
3678 SI0->getName()), I);
3679 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3680 }
3681 }
Chris Lattner812aab72003-08-12 19:11:07 +00003682
Chris Lattnerd4252a72004-07-30 07:50:03 +00003683 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3684 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003685 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003686 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003687 } else {
3688 A = 0;
3689 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003690 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003691 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3692 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003693 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003694 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003695
Misha Brukman9c003d82004-07-30 12:50:08 +00003696 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003697 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3698 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3699 I.getName()+".demorgan"), I);
3700 return BinaryOperator::createNot(And);
3701 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003702 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003703
Reid Spencer266e42b2006-12-23 06:05:41 +00003704 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3705 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3706 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003707 return R;
3708
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003709 Value *LHSVal, *RHSVal;
3710 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003711 ICmpInst::Predicate LHSCC, RHSCC;
3712 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3713 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3714 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3715 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3716 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3717 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3718 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3719 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003720 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003721 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3722 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3723 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3724 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003725 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003726 std::swap(LHS, RHS);
3727 std::swap(LHSCst, RHSCst);
3728 std::swap(LHSCC, RHSCC);
3729 }
3730
Reid Spencer266e42b2006-12-23 06:05:41 +00003731 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003732 // comparing a value against two constants and or'ing the result
3733 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003734 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3735 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003736 // equal.
3737 assert(LHSCst != RHSCst && "Compares not folded above?");
3738
3739 switch (LHSCC) {
3740 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003741 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003742 switch (RHSCC) {
3743 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003744 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003745 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3746 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3747 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3748 LHSVal->getName()+".off");
3749 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003750 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003751 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003752 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003753 break; // (X == 13 | X == 15) -> no change
3754 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3755 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003756 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003757 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3758 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3759 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003760 return ReplaceInstUsesWith(I, RHS);
3761 }
3762 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003763 case ICmpInst::ICMP_NE:
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 != 13 | X == 15) -> X != 13
3767 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3768 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003769 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003770 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3771 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3772 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003773 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003774 }
3775 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003776 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003777 switch (RHSCC) {
3778 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003779 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003780 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003781 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3782 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3783 false, I);
3784 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3785 break;
3786 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3787 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003788 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003789 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3790 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003791 }
3792 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003793 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003794 switch (RHSCC) {
3795 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003796 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3797 break;
3798 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3799 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3800 false, I);
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) -> X != 15
3804 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3805 return ReplaceInstUsesWith(I, RHS);
3806 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3807 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003808 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003809 break;
3810 case ICmpInst::ICMP_UGT:
3811 switch (RHSCC) {
3812 default: assert(0 && "Unknown integer condition code!");
3813 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3814 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3815 return ReplaceInstUsesWith(I, LHS);
3816 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3817 break;
3818 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3819 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003820 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003821 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3822 break;
3823 }
3824 break;
3825 case ICmpInst::ICMP_SGT:
3826 switch (RHSCC) {
3827 default: assert(0 && "Unknown integer condition code!");
3828 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3829 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3830 return ReplaceInstUsesWith(I, LHS);
3831 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3832 break;
3833 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3834 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003835 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003836 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3837 break;
3838 }
3839 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003840 }
3841 }
3842 }
Chris Lattner3af10532006-05-05 06:39:07 +00003843
3844 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003845 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003846 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003847 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3848 const Type *SrcTy = Op0C->getOperand(0)->getType();
3849 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3850 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003851 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3852 I.getType(), TD) &&
3853 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3854 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003855 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3856 Op1C->getOperand(0),
3857 I.getName());
3858 InsertNewInstBefore(NewOp, I);
3859 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3860 }
Chris Lattner3af10532006-05-05 06:39:07 +00003861 }
Chris Lattner3af10532006-05-05 06:39:07 +00003862
Chris Lattner15212982005-09-18 03:42:07 +00003863
Chris Lattner113f4f42002-06-25 16:13:24 +00003864 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003865}
3866
Chris Lattnerc2076352004-02-16 01:20:27 +00003867// XorSelf - Implements: X ^ X --> 0
3868struct XorSelf {
3869 Value *RHS;
3870 XorSelf(Value *rhs) : RHS(rhs) {}
3871 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3872 Instruction *apply(BinaryOperator &Xor) const {
3873 return &Xor;
3874 }
3875};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003876
3877
Chris Lattner113f4f42002-06-25 16:13:24 +00003878Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003879 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003881
Chris Lattner81a7a232004-10-16 18:11:37 +00003882 if (isa<UndefValue>(Op1))
3883 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3884
Chris Lattnerc2076352004-02-16 01:20:27 +00003885 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3886 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3887 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003888 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003889 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003890
3891 // See if we can simplify any instructions used by the instruction whose sole
3892 // purpose is to compute bits we don't care about.
3893 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003894 if (!isa<PackedType>(I.getType()) &&
3895 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003896 KnownZero, KnownOne))
3897 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003898
Zhou Sheng75b871f2007-01-11 12:24:14 +00003899 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003900 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3901 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003902 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003903 return new ICmpInst(ICI->getInversePredicate(),
3904 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003905
Reid Spencer266e42b2006-12-23 06:05:41 +00003906 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003907 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003908 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3909 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003910 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3911 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003912 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003913 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003914 }
Chris Lattner023a4832004-06-18 06:07:51 +00003915
3916 // ~(~X & Y) --> (X | ~Y)
3917 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3918 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3919 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3920 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003921 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003922 Op0I->getOperand(1)->getName()+".not");
3923 InsertNewInstBefore(NotY, I);
3924 return BinaryOperator::createOr(Op0NotVal, NotY);
3925 }
3926 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003927
Chris Lattner97638592003-07-23 21:37:07 +00003928 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003929 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003930 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003931 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003932 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3933 return BinaryOperator::createSub(
3934 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003935 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003936 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003937 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003938 } else if (Op0I->getOpcode() == Instruction::Or) {
3939 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3940 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3941 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3942 // Anything in both C1 and C2 is known to be zero, remove it from
3943 // NewRHS.
3944 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3945 NewRHS = ConstantExpr::getAnd(NewRHS,
3946 ConstantExpr::getNot(CommonBits));
3947 WorkList.push_back(Op0I);
3948 I.setOperand(0, Op0I->getOperand(0));
3949 I.setOperand(1, NewRHS);
3950 return &I;
3951 }
Chris Lattner97638592003-07-23 21:37:07 +00003952 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003953 }
Chris Lattner183b3362004-04-09 19:05:30 +00003954
3955 // Try to fold constant and into select arguments.
3956 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003957 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003958 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003959 if (isa<PHINode>(Op0))
3960 if (Instruction *NV = FoldOpIntoPhi(I))
3961 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003962 }
3963
Chris Lattnerbb74e222003-03-10 23:06:50 +00003964 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003965 if (X == Op1)
3966 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003967 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003968
Chris Lattnerbb74e222003-03-10 23:06:50 +00003969 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003970 if (X == Op0)
3971 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003972 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003973
Chris Lattnerdcd07922006-04-01 08:03:55 +00003974 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003975 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003976 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003977 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003978 I.swapOperands();
3979 std::swap(Op0, Op1);
3980 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003981 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003982 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003983 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003984 } else if (Op1I->getOpcode() == Instruction::Xor) {
3985 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3986 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3987 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3988 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003989 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3990 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3991 Op1I->swapOperands();
3992 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3993 I.swapOperands(); // Simplified below.
3994 std::swap(Op0, Op1);
3995 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003996 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003997
Chris Lattnerdcd07922006-04-01 08:03:55 +00003998 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003999 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004000 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004001 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004002 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004003 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4004 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004005 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004006 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004007 } else if (Op0I->getOpcode() == Instruction::Xor) {
4008 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4009 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4010 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4011 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004012 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4013 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4014 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004015 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4016 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004017 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4018 InsertNewInstBefore(N, I);
4019 return BinaryOperator::createAnd(N, Op1);
4020 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004021 }
4022
Reid Spencer266e42b2006-12-23 06:05:41 +00004023 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4024 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4025 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004026 return R;
4027
Chris Lattner3af10532006-05-05 06:39:07 +00004028 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004029 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004030 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004031 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4032 const Type *SrcTy = Op0C->getOperand(0)->getType();
4033 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4034 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004035 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4036 I.getType(), TD) &&
4037 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4038 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004039 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4040 Op1C->getOperand(0),
4041 I.getName());
4042 InsertNewInstBefore(NewOp, I);
4043 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4044 }
Chris Lattner3af10532006-05-05 06:39:07 +00004045 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004046
4047 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4048 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4049 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4050 if (SI0->getOpcode() == SI1->getOpcode() &&
4051 SI0->getOperand(1) == SI1->getOperand(1) &&
4052 (SI0->hasOneUse() || SI1->hasOneUse())) {
4053 Instruction *NewOp =
4054 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4055 SI1->getOperand(0),
4056 SI0->getName()), I);
4057 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4058 }
4059 }
Chris Lattner3af10532006-05-05 06:39:07 +00004060
Chris Lattner113f4f42002-06-25 16:13:24 +00004061 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004062}
4063
Chris Lattner6862fbd2004-09-29 17:40:11 +00004064static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004065 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004066}
4067
4068/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4069/// overflowed for this type.
4070static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4071 ConstantInt *In2) {
4072 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4073
Reid Spencerc635f472006-12-31 05:48:39 +00004074 return cast<ConstantInt>(Result)->getZExtValue() <
4075 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004076}
4077
Chris Lattner0798af32005-01-13 20:14:25 +00004078/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4079/// code necessary to compute the offset from the base pointer (without adding
4080/// in the base pointer). Return the result as a signed integer of intptr size.
4081static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4082 TargetData &TD = IC.getTargetData();
4083 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004084 const Type *IntPtrTy = TD.getIntPtrType();
4085 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004086
4087 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004088 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004089
Chris Lattner0798af32005-01-13 20:14:25 +00004090 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4091 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004092 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004093 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004094 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4095 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004096 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004097 Scale = ConstantExpr::getMul(OpC, Scale);
4098 if (Constant *RC = dyn_cast<Constant>(Result))
4099 Result = ConstantExpr::getAdd(RC, Scale);
4100 else {
4101 // Emit an add instruction.
4102 Result = IC.InsertNewInstBefore(
4103 BinaryOperator::createAdd(Result, Scale,
4104 GEP->getName()+".offs"), I);
4105 }
4106 }
4107 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004108 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004109 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004110 Op->getName()+".c"), I);
4111 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004112 // We'll let instcombine(mul) convert this to a shl if possible.
4113 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4114 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004115
4116 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004117 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004118 GEP->getName()+".offs"), I);
4119 }
4120 }
4121 return Result;
4122}
4123
Reid Spencer266e42b2006-12-23 06:05:41 +00004124/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004125/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004126Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4127 ICmpInst::Predicate Cond,
4128 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004129 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004130
4131 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4132 if (isa<PointerType>(CI->getOperand(0)->getType()))
4133 RHS = CI->getOperand(0);
4134
Chris Lattner0798af32005-01-13 20:14:25 +00004135 Value *PtrBase = GEPLHS->getOperand(0);
4136 if (PtrBase == RHS) {
4137 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004138 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4139 // each index is zero or not.
4140 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004141 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004142 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4143 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004144 bool EmitIt = true;
4145 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4146 if (isa<UndefValue>(C)) // undef index -> undef.
4147 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4148 if (C->isNullValue())
4149 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004150 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4151 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004152 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004153 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004154 ConstantInt::get(Type::Int1Ty,
4155 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004156 }
4157
4158 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004159 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004160 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004161 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4162 if (InVal == 0)
4163 InVal = Comp;
4164 else {
4165 InVal = InsertNewInstBefore(InVal, I);
4166 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004167 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004168 InVal = BinaryOperator::createOr(InVal, Comp);
4169 else // True if all are equal
4170 InVal = BinaryOperator::createAnd(InVal, Comp);
4171 }
4172 }
4173 }
4174
4175 if (InVal)
4176 return InVal;
4177 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004178 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004179 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4180 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004181 }
Chris Lattner0798af32005-01-13 20:14:25 +00004182
Reid Spencer266e42b2006-12-23 06:05:41 +00004183 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004184 // the result to fold to a constant!
4185 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4186 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4187 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004188 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4189 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004190 }
4191 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004192 // If the base pointers are different, but the indices are the same, just
4193 // compare the base pointer.
4194 if (PtrBase != GEPRHS->getOperand(0)) {
4195 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004196 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004197 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004198 if (IndicesTheSame)
4199 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4200 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4201 IndicesTheSame = false;
4202 break;
4203 }
4204
4205 // If all indices are the same, just compare the base pointers.
4206 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004207 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4208 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004209
4210 // Otherwise, the base pointers are different and the indices are
4211 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004212 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004213 }
Chris Lattner0798af32005-01-13 20:14:25 +00004214
Chris Lattner81e84172005-01-13 22:25:21 +00004215 // If one of the GEPs has all zero indices, recurse.
4216 bool AllZeros = true;
4217 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4218 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4219 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4220 AllZeros = false;
4221 break;
4222 }
4223 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004224 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4225 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004226
4227 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004228 AllZeros = true;
4229 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4230 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4231 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4232 AllZeros = false;
4233 break;
4234 }
4235 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004236 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004237
Chris Lattner4fa89822005-01-14 00:20:05 +00004238 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4239 // If the GEPs only differ by one index, compare it.
4240 unsigned NumDifferences = 0; // Keep track of # differences.
4241 unsigned DiffOperand = 0; // The operand that differs.
4242 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4243 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004244 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4245 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004246 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004247 NumDifferences = 2;
4248 break;
4249 } else {
4250 if (NumDifferences++) break;
4251 DiffOperand = i;
4252 }
4253 }
4254
4255 if (NumDifferences == 0) // SAME GEP?
4256 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004257 ConstantInt::get(Type::Int1Ty,
4258 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004259 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004260 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4261 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004262 // Make sure we do a signed comparison here.
4263 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004264 }
4265 }
4266
Reid Spencer266e42b2006-12-23 06:05:41 +00004267 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004268 // the result to fold to a constant!
4269 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4270 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4271 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4272 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4273 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004274 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004275 }
4276 }
4277 return 0;
4278}
4279
Reid Spencer266e42b2006-12-23 06:05:41 +00004280Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4281 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004283
Reid Spencer266e42b2006-12-23 06:05:41 +00004284 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004285 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004286 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4287 isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004288
Reid Spencer266e42b2006-12-23 06:05:41 +00004289 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004290 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004291
Reid Spencer266e42b2006-12-23 06:05:41 +00004292 // Handle fcmp with constant RHS
4293 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4294 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4295 switch (LHSI->getOpcode()) {
4296 case Instruction::PHI:
4297 if (Instruction *NV = FoldOpIntoPhi(I))
4298 return NV;
4299 break;
4300 case Instruction::Select:
4301 // If either operand of the select is a constant, we can fold the
4302 // comparison into the select arms, which will cause one to be
4303 // constant folded and the select turned into a bitwise or.
4304 Value *Op1 = 0, *Op2 = 0;
4305 if (LHSI->hasOneUse()) {
4306 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4307 // Fold the known value into the constant operand.
4308 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4309 // Insert a new FCmp of the other select operand.
4310 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4311 LHSI->getOperand(2), RHSC,
4312 I.getName()), I);
4313 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4314 // Fold the known value into the constant operand.
4315 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4316 // Insert a new FCmp of the other select operand.
4317 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4318 LHSI->getOperand(1), RHSC,
4319 I.getName()), I);
4320 }
4321 }
4322
4323 if (Op1)
4324 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4325 break;
4326 }
4327 }
4328
4329 return Changed ? &I : 0;
4330}
4331
4332Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4333 bool Changed = SimplifyCompare(I);
4334 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4335 const Type *Ty = Op0->getType();
4336
4337 // icmp X, X
4338 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004339 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4340 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004341
4342 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004343 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004344
4345 // icmp of GlobalValues can never equal each other as long as they aren't
4346 // external weak linkage type.
4347 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4348 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4349 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004350 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4351 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004352
4353 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004354 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004355 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4356 isa<ConstantPointerNull>(Op0)) &&
4357 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004358 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004359 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4360 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004361
Reid Spencer266e42b2006-12-23 06:05:41 +00004362 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004363 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004364 switch (I.getPredicate()) {
4365 default: assert(0 && "Invalid icmp instruction!");
4366 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004367 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004368 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004369 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004370 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004371 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004372 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004373
Reid Spencer266e42b2006-12-23 06:05:41 +00004374 case ICmpInst::ICMP_UGT:
4375 case ICmpInst::ICMP_SGT:
4376 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004377 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004378 case ICmpInst::ICMP_ULT:
4379 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004380 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4381 InsertNewInstBefore(Not, I);
4382 return BinaryOperator::createAnd(Not, Op1);
4383 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004384 case ICmpInst::ICMP_UGE:
4385 case ICmpInst::ICMP_SGE:
4386 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004387 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004388 case ICmpInst::ICMP_ULE:
4389 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004390 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4391 InsertNewInstBefore(Not, I);
4392 return BinaryOperator::createOr(Not, Op1);
4393 }
4394 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004395 }
4396
Chris Lattner2dd01742004-06-09 04:24:29 +00004397 // See if we are doing a comparison between a constant and an instruction that
4398 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004399 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004400 switch (I.getPredicate()) {
4401 default: break;
4402 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4403 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004404 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004405 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4406 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4407 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4408 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4409 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004410
Reid Spencer266e42b2006-12-23 06:05:41 +00004411 case ICmpInst::ICMP_SLT:
4412 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004413 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004414 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4415 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4416 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4417 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4418 break;
4419
4420 case ICmpInst::ICMP_UGT:
4421 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004422 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004423 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4424 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4425 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4426 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4427 break;
4428
4429 case ICmpInst::ICMP_SGT:
4430 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004431 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004432 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4433 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4434 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4435 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4436 break;
4437
4438 case ICmpInst::ICMP_ULE:
4439 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004440 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004441 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4442 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4443 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4444 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4445 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004446
Reid Spencer266e42b2006-12-23 06:05:41 +00004447 case ICmpInst::ICMP_SLE:
4448 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004449 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004450 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4451 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4452 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4453 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4454 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004455
Reid Spencer266e42b2006-12-23 06:05:41 +00004456 case ICmpInst::ICMP_UGE:
4457 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004458 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004459 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4460 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4461 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4462 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4463 break;
4464
4465 case ICmpInst::ICMP_SGE:
4466 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004467 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004468 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4469 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4470 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4471 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4472 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004473 }
4474
Reid Spencer266e42b2006-12-23 06:05:41 +00004475 // If we still have a icmp le or icmp ge instruction, turn it into the
4476 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004477 // already been handled above, this requires little checking.
4478 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004479 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4480 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4481 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4482 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4483 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4484 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4485 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4486 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004487
4488 // See if we can fold the comparison based on bits known to be zero or one
4489 // in the input.
4490 uint64_t KnownZero, KnownOne;
4491 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4492 KnownZero, KnownOne, 0))
4493 return &I;
4494
4495 // Given the known and unknown bits, compute a range that the LHS could be
4496 // in.
4497 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004498 // Compute the Min, Max and RHS values based on the known bits. For the
4499 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004500 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4501 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004502 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4503 SRHSVal = CI->getSExtValue();
4504 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4505 SMax);
4506 } else {
4507 URHSVal = CI->getZExtValue();
4508 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4509 UMax);
4510 }
4511 switch (I.getPredicate()) { // LE/GE have been folded already.
4512 default: assert(0 && "Unknown icmp opcode!");
4513 case ICmpInst::ICMP_EQ:
4514 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004515 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004516 break;
4517 case ICmpInst::ICMP_NE:
4518 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004519 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004520 break;
4521 case ICmpInst::ICMP_ULT:
4522 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004523 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004524 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004525 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004526 break;
4527 case ICmpInst::ICMP_UGT:
4528 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004529 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004532 break;
4533 case ICmpInst::ICMP_SLT:
4534 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004535 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004536 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004537 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004538 break;
4539 case ICmpInst::ICMP_SGT:
4540 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004541 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004543 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004544 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004545 }
4546 }
4547
Reid Spencer266e42b2006-12-23 06:05:41 +00004548 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004549 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004551 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004552 switch (LHSI->getOpcode()) {
4553 case Instruction::And:
4554 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4555 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004556 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4557
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004559 // and/compare to be the input width without changing the value
4560 // produced, eliminating a cast.
4561 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4562 // We can do this transformation if either the AND constant does not
4563 // have its sign bit set or if it is an equality comparison.
4564 // Extending a relational comparison when we're checking the sign
4565 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004566 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004567 (I.isEquality() ||
4568 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4569 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4570 ConstantInt *NewCST;
4571 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004572 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4573 AndCST->getZExtValue());
4574 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4575 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004576 Instruction *NewAnd =
4577 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4578 LHSI->getName());
4579 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004580 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004581 }
4582 }
4583
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004584 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4585 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4586 // happens a LOT in code produced by the C front-end, for bitfield
4587 // access.
4588 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004589
4590 // Check to see if there is a noop-cast between the shift and the and.
4591 if (!Shift) {
4592 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004593 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004594 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4595 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004596
Reid Spencere0fc4df2006-10-20 07:07:24 +00004597 ConstantInt *ShAmt;
4598 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004599 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4600 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004601
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004602 // We can fold this as long as we can't shift unknown bits
4603 // into the mask. This can only happen with signed shift
4604 // rights, as they sign-extend.
4605 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004606 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004607 if (!CanFold) {
4608 // To test for the bad case of the signed shr, see if any
4609 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004610 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004611 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4612
Reid Spencerc635f472006-12-31 05:48:39 +00004613 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004614 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004615 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4616 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004617 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4618 CanFold = true;
4619 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004620
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004621 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004622 Constant *NewCst;
4623 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004624 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004625 else
4626 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004627
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004628 // Check to see if we are shifting out any of the bits being
4629 // compared.
4630 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4631 // If we shifted bits out, the fold is not going to work out.
4632 // As a special case, check to see if this means that the
4633 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004634 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004635 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004636 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004637 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004638 } else {
4639 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004640 Constant *NewAndCST;
4641 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004642 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004643 else
4644 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4645 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004646 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004647 WorkList.push_back(Shift); // Shift is dead.
4648 AddUsesToWorkList(I);
4649 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004650 }
4651 }
Chris Lattner35167c32004-06-09 07:59:58 +00004652 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004653
4654 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4655 // preferable because it allows the C<<Y expression to be hoisted out
4656 // of a loop if Y is invariant and X is not.
4657 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004658 I.isEquality() && !Shift->isArithmeticShift() &&
4659 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004660 // Compute C << Y.
4661 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004662 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004663 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4664 "tmp");
4665 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004666 // Insert a logical shift.
4667 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004668 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004669 }
4670 InsertNewInstBefore(cast<Instruction>(NS), I);
4671
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004672 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004673 Instruction *NewAnd = BinaryOperator::createAnd(
4674 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004675 InsertNewInstBefore(NewAnd, I);
4676
4677 I.setOperand(0, NewAnd);
4678 return &I;
4679 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004680 }
4681 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004682
Reid Spencer266e42b2006-12-23 06:05:41 +00004683 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004684 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004685 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004686 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4687
4688 // Check that the shift amount is in range. If not, don't perform
4689 // undefined shifts. When the shift is visited it will be
4690 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004691 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004692 break;
4693
Chris Lattner272d5ca2004-09-28 18:22:15 +00004694 // If we are comparing against bits always shifted out, the
4695 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004696 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004697 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004698 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004699 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004700 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004701 return ReplaceInstUsesWith(I, Cst);
4702 }
4703
4704 if (LHSI->hasOneUse()) {
4705 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004706 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004707 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004708 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004709
Chris Lattner272d5ca2004-09-28 18:22:15 +00004710 Instruction *AndI =
4711 BinaryOperator::createAnd(LHSI->getOperand(0),
4712 Mask, LHSI->getName()+".mask");
4713 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004714 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004715 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004716 }
4717 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004718 }
4719 break;
4720
Reid Spencer266e42b2006-12-23 06:05:41 +00004721 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004722 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004723 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004724 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004725 // Check that the shift amount is in range. If not, don't perform
4726 // undefined shifts. When the shift is visited it will be
4727 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004728 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004729 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004730 break;
4731
Chris Lattner1023b872004-09-27 16:18:50 +00004732 // If we are comparing against bits always shifted out, the
4733 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004734 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004735 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004736 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4737 ShAmt);
4738 else
4739 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4740 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004741
Chris Lattner1023b872004-09-27 16:18:50 +00004742 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004743 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004744 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004745 return ReplaceInstUsesWith(I, Cst);
4746 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004747
Chris Lattner1023b872004-09-27 16:18:50 +00004748 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004749 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004750
Chris Lattner1023b872004-09-27 16:18:50 +00004751 // Otherwise strength reduce the shift into an and.
4752 uint64_t Val = ~0ULL; // All ones.
4753 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004754 Val &= ~0ULL >> (64-TypeBits);
4755 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004756
Chris Lattner1023b872004-09-27 16:18:50 +00004757 Instruction *AndI =
4758 BinaryOperator::createAnd(LHSI->getOperand(0),
4759 Mask, LHSI->getName()+".mask");
4760 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004761 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004762 ConstantExpr::getShl(CI, ShAmt));
4763 }
Chris Lattner1023b872004-09-27 16:18:50 +00004764 }
4765 }
4766 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004767
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004768 case Instruction::SDiv:
4769 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004770 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004771 // Fold this div into the comparison, producing a range check.
4772 // Determine, based on the divide type, what the range is being
4773 // checked. If there is an overflow on the low or high side, remember
4774 // it, otherwise compute the range [low, hi) bounding the new value.
4775 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004776 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004777 // FIXME: If the operand types don't match the type of the divide
4778 // then don't attempt this transform. The code below doesn't have the
4779 // logic to deal with a signed divide and an unsigned compare (and
4780 // vice versa). This is because (x /s C1) <s C2 produces different
4781 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4782 // (x /u C1) <u C2. Simply casting the operands and result won't
4783 // work. :( The if statement below tests that condition and bails
4784 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004785 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4786 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004787 break;
4788
4789 // Initialize the variables that will indicate the nature of the
4790 // range check.
4791 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004792 ConstantInt *LoBound = 0, *HiBound = 0;
4793
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004794 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4795 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4796 // C2 (CI). By solving for X we can turn this into a range check
4797 // instead of computing a divide.
4798 ConstantInt *Prod =
4799 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004800
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004801 // Determine if the product overflows by seeing if the product is
4802 // not equal to the divide. Make sure we do the same kind of divide
4803 // as in the LHS instruction that we're folding.
4804 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004805 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004806 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4807
Reid Spencer266e42b2006-12-23 06:05:41 +00004808 // Get the ICmp opcode
4809 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004810
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004811 if (DivRHS->isNullValue()) {
4812 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004813 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004814 LoBound = Prod;
4815 LoOverflow = ProdOV;
4816 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004817 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004818 if (CI->isNullValue()) { // (X / pos) op 0
4819 // Can't overflow.
4820 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4821 HiBound = DivRHS;
4822 } else if (isPositive(CI)) { // (X / pos) op pos
4823 LoBound = Prod;
4824 LoOverflow = ProdOV;
4825 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4826 } else { // (X / pos) op neg
4827 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4828 LoOverflow = AddWithOverflow(LoBound, Prod,
4829 cast<ConstantInt>(DivRHSH));
4830 HiBound = Prod;
4831 HiOverflow = ProdOV;
4832 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004833 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004834 if (CI->isNullValue()) { // (X / neg) op 0
4835 LoBound = AddOne(DivRHS);
4836 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004837 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004838 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004839 } else if (isPositive(CI)) { // (X / neg) op pos
4840 HiOverflow = LoOverflow = ProdOV;
4841 if (!LoOverflow)
4842 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4843 HiBound = AddOne(Prod);
4844 } else { // (X / neg) op neg
4845 LoBound = Prod;
4846 LoOverflow = HiOverflow = ProdOV;
4847 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4848 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004849
Chris Lattnera92af962004-10-11 19:40:04 +00004850 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004851 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004852 }
4853
4854 if (LoBound) {
4855 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004856 switch (predicate) {
4857 default: assert(0 && "Unhandled icmp opcode!");
4858 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004859 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004860 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004861 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004862 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4863 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004864 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004865 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4866 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004867 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004868 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4869 true, I);
4870 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004871 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004872 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004873 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004874 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4875 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004876 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004877 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4878 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004879 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004880 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4881 false, I);
4882 case ICmpInst::ICMP_ULT:
4883 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004884 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004885 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004886 return new ICmpInst(predicate, X, LoBound);
4887 case ICmpInst::ICMP_UGT:
4888 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004889 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004890 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004891 if (predicate == ICmpInst::ICMP_UGT)
4892 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4893 else
4894 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004895 }
4896 }
4897 }
4898 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004899 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004900
Reid Spencer266e42b2006-12-23 06:05:41 +00004901 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004902 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004903 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004904
Reid Spencere0fc4df2006-10-20 07:07:24 +00004905 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4906 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004907 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4908 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004909 case Instruction::SRem:
4910 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4911 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4912 BO->hasOneUse()) {
4913 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4914 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004915 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4916 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004917 return new ICmpInst(I.getPredicate(), NewRem,
4918 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004919 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004920 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004921 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004922 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004923 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4924 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004925 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004926 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4927 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004928 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004929 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4930 // efficiently invertible, or if the add has just this one use.
4931 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004932
Chris Lattnerc992add2003-08-13 05:33:12 +00004933 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004934 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004935 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004936 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004937 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004938 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4939 BO->setName("");
4940 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004941 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004942 }
4943 }
4944 break;
4945 case Instruction::Xor:
4946 // For the xor case, we can xor two constants together, eliminating
4947 // the explicit xor.
4948 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004949 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4950 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004951
4952 // FALLTHROUGH
4953 case Instruction::Sub:
4954 // Replace (([sub|xor] A, B) != 0) with (A != B)
4955 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004956 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4957 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004958 break;
4959
4960 case Instruction::Or:
4961 // If bits are being or'd in that are not present in the constant we
4962 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004963 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004964 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004965 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004966 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4967 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004968 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004969 break;
4970
4971 case Instruction::And:
4972 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004973 // If bits are being compared against that are and'd out, then the
4974 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004975 if (!ConstantExpr::getAnd(CI,
4976 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004977 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4978 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004979
Chris Lattner35167c32004-06-09 07:59:58 +00004980 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004981 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004982 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4983 ICmpInst::ICMP_NE, Op0,
4984 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004985
Reid Spencer266e42b2006-12-23 06:05:41 +00004986 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00004987 if (isSignBit(BOC)) {
4988 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004989 Constant *Zero = Constant::getNullValue(X->getType());
4990 ICmpInst::Predicate pred = isICMP_NE ?
4991 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4992 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00004993 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004994
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004995 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004996 if (CI->isNullValue() && isHighOnes(BOC)) {
4997 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004998 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00004999 ICmpInst::Predicate pred = isICMP_NE ?
5000 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5001 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005002 }
5003
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005004 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005005 default: break;
5006 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005007 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5008 // Handle set{eq|ne} <intrinsic>, intcst.
5009 switch (II->getIntrinsicID()) {
5010 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005011 case Intrinsic::bswap_i16:
5012 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005013 WorkList.push_back(II); // Dead?
5014 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005015 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005016 ByteSwap_16(CI->getZExtValue())));
5017 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005018 case Intrinsic::bswap_i32:
5019 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005020 WorkList.push_back(II); // Dead?
5021 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005022 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005023 ByteSwap_32(CI->getZExtValue())));
5024 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 case Intrinsic::bswap_i64:
5026 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005027 WorkList.push_back(II); // Dead?
5028 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005029 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005030 ByteSwap_64(CI->getZExtValue())));
5031 return &I;
5032 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005033 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005034 } else { // Not a ICMP_EQ/ICMP_NE
5035 // If the LHS is a cast from an integral value of the same size, then
5036 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005037 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5038 Value *CastOp = Cast->getOperand(0);
5039 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005040 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005041 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005042 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005043 // If this is an unsigned comparison, try to make the comparison use
5044 // smaller constant values.
5045 switch (I.getPredicate()) {
5046 default: break;
5047 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5048 ConstantInt *CUI = cast<ConstantInt>(CI);
5049 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5050 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5051 ConstantInt::get(SrcTy, -1));
5052 break;
5053 }
5054 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5055 ConstantInt *CUI = cast<ConstantInt>(CI);
5056 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5057 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5058 Constant::getNullValue(SrcTy));
5059 break;
5060 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005061 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005062
Chris Lattner2b55ea32004-02-23 07:16:20 +00005063 }
5064 }
Chris Lattnere967b342003-06-04 05:10:11 +00005065 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005066 }
5067
Reid Spencer266e42b2006-12-23 06:05:41 +00005068 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005069 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5070 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5071 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005072 case Instruction::GetElementPtr:
5073 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005074 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005075 bool isAllZeros = true;
5076 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5077 if (!isa<Constant>(LHSI->getOperand(i)) ||
5078 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5079 isAllZeros = false;
5080 break;
5081 }
5082 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005083 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005084 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5085 }
5086 break;
5087
Chris Lattner77c32c32005-04-23 15:31:55 +00005088 case Instruction::PHI:
5089 if (Instruction *NV = FoldOpIntoPhi(I))
5090 return NV;
5091 break;
5092 case Instruction::Select:
5093 // If either operand of the select is a constant, we can fold the
5094 // comparison into the select arms, which will cause one to be
5095 // constant folded and the select turned into a bitwise or.
5096 Value *Op1 = 0, *Op2 = 0;
5097 if (LHSI->hasOneUse()) {
5098 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5099 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005100 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5101 // Insert a new ICmp of the other select operand.
5102 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5103 LHSI->getOperand(2), RHSC,
5104 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005105 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5106 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005107 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5108 // Insert a new ICmp of the other select operand.
5109 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5110 LHSI->getOperand(1), RHSC,
5111 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005112 }
5113 }
Jeff Cohen82639852005-04-23 21:38:35 +00005114
Chris Lattner77c32c32005-04-23 15:31:55 +00005115 if (Op1)
5116 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5117 break;
5118 }
5119 }
5120
Reid Spencer266e42b2006-12-23 06:05:41 +00005121 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005122 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005123 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005124 return NI;
5125 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005126 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5127 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005128 return NI;
5129
Reid Spencer266e42b2006-12-23 06:05:41 +00005130 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005131 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5132 // now.
5133 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5134 if (isa<PointerType>(Op0->getType()) &&
5135 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005136 // We keep moving the cast from the left operand over to the right
5137 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005138 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005139
Chris Lattner64d87b02007-01-06 01:45:59 +00005140 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5141 // so eliminate it as well.
5142 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5143 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005144
Chris Lattner16930792003-11-03 04:25:02 +00005145 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005146 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005147 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005148 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005149 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005150 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005151 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005152 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005153 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005154 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005155 }
5156
5157 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005158 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005159 // This comes up when you have code like
5160 // int X = A < B;
5161 // if (X) ...
5162 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005163 // with a constant or another cast from the same type.
5164 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005165 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005166 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005167 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005168
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005169 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005170 Value *A, *B, *C, *D;
5171 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5172 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5173 Value *OtherVal = A == Op1 ? B : A;
5174 return new ICmpInst(I.getPredicate(), OtherVal,
5175 Constant::getNullValue(A->getType()));
5176 }
5177
5178 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5179 // A^c1 == C^c2 --> A == C^(c1^c2)
5180 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5181 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5182 if (Op1->hasOneUse()) {
5183 Constant *NC = ConstantExpr::getXor(C1, C2);
5184 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5185 return new ICmpInst(I.getPredicate(), A,
5186 InsertNewInstBefore(Xor, I));
5187 }
5188
5189 // A^B == A^D -> B == D
5190 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5191 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5192 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5193 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5194 }
5195 }
5196
5197 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5198 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005199 // A == (A^B) -> B == 0
5200 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005201 return new ICmpInst(I.getPredicate(), OtherVal,
5202 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005203 }
5204 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005205 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005206 return new ICmpInst(I.getPredicate(), B,
5207 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005208 }
5209 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005210 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005211 return new ICmpInst(I.getPredicate(), B,
5212 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005213 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005214
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005215 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5216 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5217 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5218 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5219 Value *X = 0, *Y = 0, *Z = 0;
5220
5221 if (A == C) {
5222 X = B; Y = D; Z = A;
5223 } else if (A == D) {
5224 X = B; Y = C; Z = A;
5225 } else if (B == C) {
5226 X = A; Y = D; Z = B;
5227 } else if (B == D) {
5228 X = A; Y = C; Z = B;
5229 }
5230
5231 if (X) { // Build (X^Y) & Z
5232 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5233 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5234 I.setOperand(0, Op1);
5235 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5236 return &I;
5237 }
5238 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005239 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005240 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005241}
5242
Reid Spencer266e42b2006-12-23 06:05:41 +00005243// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005244// We only handle extending casts so far.
5245//
Reid Spencer266e42b2006-12-23 06:05:41 +00005246Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5247 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005248 Value *LHSCIOp = LHSCI->getOperand(0);
5249 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005250 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005251 Value *RHSCIOp;
5252
Reid Spencer266e42b2006-12-23 06:05:41 +00005253 // We only handle extension cast instructions, so far. Enforce this.
5254 if (LHSCI->getOpcode() != Instruction::ZExt &&
5255 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005256 return 0;
5257
Reid Spencer266e42b2006-12-23 06:05:41 +00005258 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5259 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005260
Reid Spencer266e42b2006-12-23 06:05:41 +00005261 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005262 // Not an extension from the same type?
5263 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005264 if (RHSCIOp->getType() != LHSCIOp->getType())
5265 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005266
5267 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5268 // and the other is a zext), then we can't handle this.
5269 if (CI->getOpcode() != LHSCI->getOpcode())
5270 return 0;
5271
5272 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5273 // then we can't handle this.
5274 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5275 return 0;
5276
5277 // Okay, just insert a compare of the reduced operands now!
5278 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005279 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005280
Reid Spencer266e42b2006-12-23 06:05:41 +00005281 // If we aren't dealing with a constant on the RHS, exit early
5282 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5283 if (!CI)
5284 return 0;
5285
5286 // Compute the constant that would happen if we truncated to SrcTy then
5287 // reextended to DestTy.
5288 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5289 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5290
5291 // If the re-extended constant didn't change...
5292 if (Res2 == CI) {
5293 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5294 // For example, we might have:
5295 // %A = sext short %X to uint
5296 // %B = icmp ugt uint %A, 1330
5297 // It is incorrect to transform this into
5298 // %B = icmp ugt short %X, 1330
5299 // because %A may have negative value.
5300 //
5301 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5302 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005303 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005304 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5305 else
5306 return 0;
5307 }
5308
5309 // The re-extended constant changed so the constant cannot be represented
5310 // in the shorter type. Consequently, we cannot emit a simple comparison.
5311
5312 // First, handle some easy cases. We know the result cannot be equal at this
5313 // point so handle the ICI.isEquality() cases
5314 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005315 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005316 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005317 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005318
5319 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5320 // should have been folded away previously and not enter in here.
5321 Value *Result;
5322 if (isSignedCmp) {
5323 // We're performing a signed comparison.
5324 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005325 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005326 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005327 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005328 } else {
5329 // We're performing an unsigned comparison.
5330 if (isSignedExt) {
5331 // We're performing an unsigned comp with a sign extended value.
5332 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005333 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005334 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5335 NegOne, ICI.getName()), ICI);
5336 } else {
5337 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005338 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005339 }
5340 }
5341
5342 // Finally, return the value computed.
5343 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5344 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5345 return ReplaceInstUsesWith(ICI, Result);
5346 } else {
5347 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5348 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5349 "ICmp should be folded!");
5350 if (Constant *CI = dyn_cast<Constant>(Result))
5351 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5352 else
5353 return BinaryOperator::createNot(Result);
5354 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005355}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005356
Chris Lattnere8d6c602003-03-10 19:16:08 +00005357Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005358 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005360
5361 // shl X, 0 == X and shr X, 0 == X
5362 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005363 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005364 Op0 == Constant::getNullValue(Op0->getType()))
5365 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005366
Reid Spencer266e42b2006-12-23 06:05:41 +00005367 if (isa<UndefValue>(Op0)) {
5368 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005369 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005370 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005371 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5372 }
5373 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005374 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5375 return ReplaceInstUsesWith(I, Op0);
5376 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005377 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005378 }
5379
Chris Lattnerd4dee402006-11-10 23:38:52 +00005380 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5381 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005382 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005383 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005384 return ReplaceInstUsesWith(I, CSI);
5385
Chris Lattner183b3362004-04-09 19:05:30 +00005386 // Try to fold constant and into select arguments.
5387 if (isa<Constant>(Op0))
5388 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005390 return R;
5391
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005392 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005393 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005394 if (MaskedValueIsZero(Op0,
5395 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005396 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005397 }
5398 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005399
Reid Spencere0fc4df2006-10-20 07:07:24 +00005400 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005401 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5402 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005403 return 0;
5404}
5405
Reid Spencere0fc4df2006-10-20 07:07:24 +00005406Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005407 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005408 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5409 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005410 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005411
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005412 // See if we can simplify any instructions used by the instruction whose sole
5413 // purpose is to compute bits we don't care about.
5414 uint64_t KnownZero, KnownOne;
5415 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5416 KnownZero, KnownOne))
5417 return &I;
5418
Chris Lattner14553932006-01-06 07:12:35 +00005419 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5420 // of a signed value.
5421 //
5422 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005423 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005424 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005425 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5426 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005427 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005428 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005429 }
Chris Lattner14553932006-01-06 07:12:35 +00005430 }
5431
5432 // ((X*C1) << C2) == (X * (C1 << C2))
5433 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5434 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5435 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5436 return BinaryOperator::createMul(BO->getOperand(0),
5437 ConstantExpr::getShl(BOOp, Op1));
5438
5439 // Try to fold constant and into select arguments.
5440 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5441 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5442 return R;
5443 if (isa<PHINode>(Op0))
5444 if (Instruction *NV = FoldOpIntoPhi(I))
5445 return NV;
5446
5447 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005448 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5449 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5450 Value *V1, *V2;
5451 ConstantInt *CC;
5452 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005453 default: break;
5454 case Instruction::Add:
5455 case Instruction::And:
5456 case Instruction::Or:
5457 case Instruction::Xor:
5458 // These operators commute.
5459 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005460 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5461 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005462 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005463 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005464 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005465 Op0BO->getName());
5466 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005467 Instruction *X =
5468 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5469 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005470 InsertNewInstBefore(X, I); // (X + (Y << C))
5471 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005472 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005473 return BinaryOperator::createAnd(X, C2);
5474 }
Chris Lattner14553932006-01-06 07:12:35 +00005475
Chris Lattner797dee72005-09-18 06:30:59 +00005476 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5477 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5478 match(Op0BO->getOperand(1),
5479 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005480 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005481 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005482 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005483 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005484 Op0BO->getName());
5485 InsertNewInstBefore(YS, I); // (Y << C)
5486 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005487 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005488 V1->getName()+".mask");
5489 InsertNewInstBefore(XM, I); // X & (CC << C)
5490
5491 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5492 }
Chris Lattner14553932006-01-06 07:12:35 +00005493
Chris Lattner797dee72005-09-18 06:30:59 +00005494 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005495 case Instruction::Sub:
5496 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005497 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5498 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005499 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005500 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005501 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005502 Op0BO->getName());
5503 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005504 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005505 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005506 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005507 InsertNewInstBefore(X, I); // (X + (Y << C))
5508 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005509 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005510 return BinaryOperator::createAnd(X, C2);
5511 }
Chris Lattner14553932006-01-06 07:12:35 +00005512
Chris Lattner1df0e982006-05-31 21:14:00 +00005513 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005514 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5515 match(Op0BO->getOperand(0),
5516 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005517 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005518 cast<BinaryOperator>(Op0BO->getOperand(0))
5519 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005520 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005521 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005522 Op0BO->getName());
5523 InsertNewInstBefore(YS, I); // (Y << C)
5524 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005525 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005526 V1->getName()+".mask");
5527 InsertNewInstBefore(XM, I); // X & (CC << C)
5528
Chris Lattner1df0e982006-05-31 21:14:00 +00005529 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005530 }
Chris Lattner14553932006-01-06 07:12:35 +00005531
Chris Lattner27cb9db2005-09-18 05:12:10 +00005532 break;
Chris Lattner14553932006-01-06 07:12:35 +00005533 }
5534
5535
5536 // If the operand is an bitwise operator with a constant RHS, and the
5537 // shift is the only use, we can pull it out of the shift.
5538 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5539 bool isValid = true; // Valid only for And, Or, Xor
5540 bool highBitSet = false; // Transform if high bit of constant set?
5541
5542 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005543 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005544 case Instruction::Add:
5545 isValid = isLeftShift;
5546 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005547 case Instruction::Or:
5548 case Instruction::Xor:
5549 highBitSet = false;
5550 break;
5551 case Instruction::And:
5552 highBitSet = true;
5553 break;
Chris Lattner14553932006-01-06 07:12:35 +00005554 }
5555
5556 // If this is a signed shift right, and the high bit is modified
5557 // by the logical operation, do not perform the transformation.
5558 // The highBitSet boolean indicates the value of the high bit of
5559 // the constant which would cause it to be modified for this
5560 // operation.
5561 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005562 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005563 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005564 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5565 }
5566
5567 if (isValid) {
5568 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5569
5570 Instruction *NewShift =
5571 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5572 Op0BO->getName());
5573 Op0BO->setName("");
5574 InsertNewInstBefore(NewShift, I);
5575
5576 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5577 NewRHS);
5578 }
5579 }
5580 }
5581 }
5582
Chris Lattnereb372a02006-01-06 07:52:12 +00005583 // Find out if this is a shift of a shift by a constant.
5584 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005585 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005586 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005587 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5588 // If this is a noop-integer cast of a shift instruction, use the shift.
5589 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005590 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5591 }
5592 }
5593
Reid Spencere0fc4df2006-10-20 07:07:24 +00005594 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005595 // Find the operands and properties of the input shift. Note that the
5596 // signedness of the input shift may differ from the current shift if there
5597 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005598 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5599 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005600 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005601
Reid Spencere0fc4df2006-10-20 07:07:24 +00005602 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005603
Reid Spencere0fc4df2006-10-20 07:07:24 +00005604 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5605 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005606
5607 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5608 if (isLeftShift == isShiftOfLeftShift) {
5609 // Do not fold these shifts if the first one is signed and the second one
5610 // is unsigned and this is a right shift. Further, don't do any folding
5611 // on them.
5612 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5613 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005614
Chris Lattnereb372a02006-01-06 07:52:12 +00005615 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5616 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5617 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005618
Chris Lattnereb372a02006-01-06 07:52:12 +00005619 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005620 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005621 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005622 if (I.getType() == ShiftResult->getType())
5623 return ShiftResult;
5624 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005625 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005626 }
5627
5628 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5629 // signed types, we can only support the (A >> c1) << c2 configuration,
5630 // because it can not turn an arbitrary bit of A into a sign bit.
5631 if (isUnsignedShift || isLeftShift) {
5632 // Calculate bitmask for what gets shifted off the edge.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005633 Constant *C = ConstantInt::getAllOnesValue(I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005634 if (isLeftShift)
5635 C = ConstantExpr::getShl(C, ShiftAmt1C);
5636 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005637 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005638
5639 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005640
5641 Instruction *Mask =
5642 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5643 InsertNewInstBefore(Mask, I);
5644
5645 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005646 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005647 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005648 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005649 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005650 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005651 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5652 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005653 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005654 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005655 } else {
5656 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005657 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005658 }
5659 } else {
5660 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005661 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005662 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005663 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005664 InsertNewInstBefore(Shift, I);
5665
Zhou Sheng75b871f2007-01-11 12:24:14 +00005666 C = ConstantInt::getAllOnesValue(Shift->getType());
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005667 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005668 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005669 }
5670 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005671 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005672 // this case, C1 == C2 and C1 is 8, 16, or 32.
5673 if (ShiftAmt1 == ShiftAmt2) {
5674 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005675 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005676 case 8 : SExtType = Type::Int8Ty; break;
5677 case 16: SExtType = Type::Int16Ty; break;
5678 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005679 }
5680
5681 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005682 Instruction *NewTrunc =
5683 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005684 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005685 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005686 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005687 }
Chris Lattner86102b82005-01-01 16:22:27 +00005688 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005689 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005690 return 0;
5691}
5692
Chris Lattner48a44f72002-05-02 17:06:02 +00005693
Chris Lattner8f663e82005-10-29 04:36:15 +00005694/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5695/// expression. If so, decompose it, returning some value X, such that Val is
5696/// X*Scale+Offset.
5697///
5698static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5699 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005700 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005701 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005702 Offset = CI->getZExtValue();
5703 Scale = 1;
5704 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005705 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5706 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005707 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005708 if (I->getOpcode() == Instruction::Shl) {
5709 // This is a value scaled by '1 << the shift amt'.
5710 Scale = 1U << CUI->getZExtValue();
5711 Offset = 0;
5712 return I->getOperand(0);
5713 } else if (I->getOpcode() == Instruction::Mul) {
5714 // This value is scaled by 'CUI'.
5715 Scale = CUI->getZExtValue();
5716 Offset = 0;
5717 return I->getOperand(0);
5718 } else if (I->getOpcode() == Instruction::Add) {
5719 // We have X+C. Check to see if we really have (X*C2)+C1,
5720 // where C1 is divisible by C2.
5721 unsigned SubScale;
5722 Value *SubVal =
5723 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5724 Offset += CUI->getZExtValue();
5725 if (SubScale > 1 && (Offset % SubScale == 0)) {
5726 Scale = SubScale;
5727 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005728 }
5729 }
5730 }
5731 }
5732 }
5733
5734 // Otherwise, we can't look past this.
5735 Scale = 1;
5736 Offset = 0;
5737 return Val;
5738}
5739
5740
Chris Lattner216be912005-10-24 06:03:58 +00005741/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5742/// try to eliminate the cast by moving the type information into the alloc.
5743Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5744 AllocationInst &AI) {
5745 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005746 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005747
Chris Lattnerac87beb2005-10-24 06:22:12 +00005748 // Remove any uses of AI that are dead.
5749 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5750 std::vector<Instruction*> DeadUsers;
5751 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5752 Instruction *User = cast<Instruction>(*UI++);
5753 if (isInstructionTriviallyDead(User)) {
5754 while (UI != E && *UI == User)
5755 ++UI; // If this instruction uses AI more than once, don't break UI.
5756
5757 // Add operands to the worklist.
5758 AddUsesToWorkList(*User);
5759 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005760 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005761
5762 User->eraseFromParent();
5763 removeFromWorkList(User);
5764 }
5765 }
5766
Chris Lattner216be912005-10-24 06:03:58 +00005767 // Get the type really allocated and the type casted to.
5768 const Type *AllocElTy = AI.getAllocatedType();
5769 const Type *CastElTy = PTy->getElementType();
5770 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005771
Chris Lattner7d190672006-10-01 19:40:58 +00005772 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5773 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005774 if (CastElTyAlign < AllocElTyAlign) return 0;
5775
Chris Lattner46705b22005-10-24 06:35:18 +00005776 // If the allocation has multiple uses, only promote it if we are strictly
5777 // increasing the alignment of the resultant allocation. If we keep it the
5778 // same, we open the door to infinite loops of various kinds.
5779 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5780
Chris Lattner216be912005-10-24 06:03:58 +00005781 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5782 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005783 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005784
Chris Lattner8270c332005-10-29 03:19:53 +00005785 // See if we can satisfy the modulus by pulling a scale out of the array
5786 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005787 unsigned ArraySizeScale, ArrayOffset;
5788 Value *NumElements = // See if the array size is a decomposable linear expr.
5789 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5790
Chris Lattner8270c332005-10-29 03:19:53 +00005791 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5792 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005793 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5794 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005795
Chris Lattner8270c332005-10-29 03:19:53 +00005796 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5797 Value *Amt = 0;
5798 if (Scale == 1) {
5799 Amt = NumElements;
5800 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005801 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005802 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5803 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005804 Amt = ConstantExpr::getMul(
5805 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5806 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005807 else if (Scale != 1) {
5808 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5809 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005810 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005811 }
5812
Chris Lattner8f663e82005-10-29 04:36:15 +00005813 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005814 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005815 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5816 Amt = InsertNewInstBefore(Tmp, AI);
5817 }
5818
Chris Lattner216be912005-10-24 06:03:58 +00005819 std::string Name = AI.getName(); AI.setName("");
5820 AllocationInst *New;
5821 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005822 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005823 else
Nate Begeman848622f2005-11-05 09:21:28 +00005824 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005825 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005826
5827 // If the allocation has multiple uses, insert a cast and change all things
5828 // that used it to use the new cast. This will also hack on CI, but it will
5829 // die soon.
5830 if (!AI.hasOneUse()) {
5831 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005832 // New is the allocation instruction, pointer typed. AI is the original
5833 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5834 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005835 InsertNewInstBefore(NewCast, AI);
5836 AI.replaceAllUsesWith(NewCast);
5837 }
Chris Lattner216be912005-10-24 06:03:58 +00005838 return ReplaceInstUsesWith(CI, New);
5839}
5840
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005841/// CanEvaluateInDifferentType - Return true if we can take the specified value
5842/// and return it without inserting any new casts. This is used by code that
5843/// tries to decide whether promoting or shrinking integer operations to wider
5844/// or smaller types will allow us to eliminate a truncate or extend.
5845static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5846 int &NumCastsRemoved) {
5847 if (isa<Constant>(V)) return true;
5848
5849 Instruction *I = dyn_cast<Instruction>(V);
5850 if (!I || !I->hasOneUse()) return false;
5851
5852 switch (I->getOpcode()) {
5853 case Instruction::And:
5854 case Instruction::Or:
5855 case Instruction::Xor:
5856 // These operators can all arbitrarily be extended or truncated.
5857 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5858 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005859 case Instruction::AShr:
5860 case Instruction::LShr:
5861 case Instruction::Shl:
5862 // If this is just a bitcast changing the sign of the operation, we can
5863 // convert if the operand can be converted.
5864 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5865 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5866 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005867 case Instruction::Trunc:
5868 case Instruction::ZExt:
5869 case Instruction::SExt:
5870 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005871 // If this is a cast from the destination type, we can trivially eliminate
5872 // it, and this will remove a cast overall.
5873 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005874 // If the first operand is itself a cast, and is eliminable, do not count
5875 // this as an eliminable cast. We would prefer to eliminate those two
5876 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005877 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005878 return true;
5879
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005880 ++NumCastsRemoved;
5881 return true;
5882 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005883 break;
5884 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005885 // TODO: Can handle more cases here.
5886 break;
5887 }
5888
5889 return false;
5890}
5891
5892/// EvaluateInDifferentType - Given an expression that
5893/// CanEvaluateInDifferentType returns true for, actually insert the code to
5894/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005895Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5896 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005897 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005898 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005899
5900 // Otherwise, it must be an instruction.
5901 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005902 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005903 switch (I->getOpcode()) {
5904 case Instruction::And:
5905 case Instruction::Or:
5906 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005907 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5908 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005909 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5910 LHS, RHS, I->getName());
5911 break;
5912 }
Chris Lattner960acb02006-11-29 07:18:39 +00005913 case Instruction::AShr:
5914 case Instruction::LShr:
5915 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005916 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005917 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5918 I->getOperand(1), I->getName());
5919 break;
5920 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005921 case Instruction::Trunc:
5922 case Instruction::ZExt:
5923 case Instruction::SExt:
5924 case Instruction::BitCast:
5925 // If the source type of the cast is the type we're trying for then we can
5926 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005927 if (I->getOperand(0)->getType() == Ty)
5928 return I->getOperand(0);
5929
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005930 // Some other kind of cast, which shouldn't happen, so just ..
5931 // FALL THROUGH
5932 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005933 // TODO: Can handle more cases here.
5934 assert(0 && "Unreachable!");
5935 break;
5936 }
5937
5938 return InsertNewInstBefore(Res, *I);
5939}
5940
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005941/// @brief Implement the transforms common to all CastInst visitors.
5942Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005943 Value *Src = CI.getOperand(0);
5944
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005945 // Casting undef to anything results in undef so might as just replace it and
5946 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005947 if (isa<UndefValue>(Src)) // cast undef -> undef
5948 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5949
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005950 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5951 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005952 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005953 if (Instruction::CastOps opc =
5954 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5955 // The first cast (CSrc) is eliminable so we need to fix up or replace
5956 // the second cast (CI). CSrc will then have a good chance of being dead.
5957 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005958 }
5959 }
Chris Lattner03841652004-05-25 04:29:21 +00005960
Chris Lattnerd0d51602003-06-21 23:12:02 +00005961 // If casting the result of a getelementptr instruction with no offset, turn
5962 // this into a cast of the original pointer!
5963 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005964 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005965 bool AllZeroOperands = true;
5966 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5967 if (!isa<Constant>(GEP->getOperand(i)) ||
5968 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5969 AllZeroOperands = false;
5970 break;
5971 }
5972 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005973 // Changing the cast operand is usually not a good idea but it is safe
5974 // here because the pointer operand is being replaced with another
5975 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005976 CI.setOperand(0, GEP->getOperand(0));
5977 return &CI;
5978 }
5979 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005980
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005981 // If we are casting a malloc or alloca to a pointer to a type of the same
5982 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005983 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005984 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5985 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005986
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005987 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005988 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5989 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5990 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005991
5992 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005993 if (isa<PHINode>(Src))
5994 if (Instruction *NV = FoldOpIntoPhi(CI))
5995 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005996
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005997 return 0;
5998}
5999
6000/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6001/// integers. This function implements the common transforms for all those
6002/// cases.
6003/// @brief Implement the transforms common to CastInst with integer operands
6004Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6005 if (Instruction *Result = commonCastTransforms(CI))
6006 return Result;
6007
6008 Value *Src = CI.getOperand(0);
6009 const Type *SrcTy = Src->getType();
6010 const Type *DestTy = CI.getType();
6011 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6012 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6013
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006014 // See if we can simplify any instructions used by the LHS whose sole
6015 // purpose is to compute bits we don't care about.
6016 uint64_t KnownZero = 0, KnownOne = 0;
6017 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6018 KnownZero, KnownOne))
6019 return &CI;
6020
6021 // If the source isn't an instruction or has more than one use then we
6022 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006023 Instruction *SrcI = dyn_cast<Instruction>(Src);
6024 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006025 return 0;
6026
6027 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006028 int NumCastsRemoved = 0;
6029 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6030 // If this cast is a truncate, evaluting in a different type always
6031 // eliminates the cast, so it is always a win. If this is a noop-cast
6032 // this just removes a noop cast which isn't pointful, but simplifies
6033 // the code. If this is a zero-extension, we need to do an AND to
6034 // maintain the clear top-part of the computation, so we require that
6035 // the input have eliminated at least one cast. If this is a sign
6036 // extension, we insert two new casts (to do the extension) so we
6037 // require that two casts have been eliminated.
6038 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6039 if (!DoXForm) {
6040 switch (CI.getOpcode()) {
6041 case Instruction::Trunc:
6042 DoXForm = true;
6043 break;
6044 case Instruction::ZExt:
6045 DoXForm = NumCastsRemoved >= 1;
6046 break;
6047 case Instruction::SExt:
6048 DoXForm = NumCastsRemoved >= 2;
6049 break;
6050 case Instruction::BitCast:
6051 DoXForm = false;
6052 break;
6053 default:
6054 // All the others use floating point so we shouldn't actually
6055 // get here because of the check above.
6056 assert(!"Unknown cast type .. unreachable");
6057 break;
6058 }
6059 }
6060
6061 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006062 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6063 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006064 assert(Res->getType() == DestTy);
6065 switch (CI.getOpcode()) {
6066 default: assert(0 && "Unknown cast type!");
6067 case Instruction::Trunc:
6068 case Instruction::BitCast:
6069 // Just replace this cast with the result.
6070 return ReplaceInstUsesWith(CI, Res);
6071 case Instruction::ZExt: {
6072 // We need to emit an AND to clear the high bits.
6073 assert(SrcBitSize < DestBitSize && "Not a zext?");
6074 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006075 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006076 if (DestBitSize < 64)
6077 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006078 return BinaryOperator::createAnd(Res, C);
6079 }
6080 case Instruction::SExt:
6081 // We need to emit a cast to truncate, then a cast to sext.
6082 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006083 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6084 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006085 }
6086 }
6087 }
6088
6089 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6090 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6091
6092 switch (SrcI->getOpcode()) {
6093 case Instruction::Add:
6094 case Instruction::Mul:
6095 case Instruction::And:
6096 case Instruction::Or:
6097 case Instruction::Xor:
6098 // If we are discarding information, or just changing the sign,
6099 // rewrite.
6100 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6101 // Don't insert two casts if they cannot be eliminated. We allow
6102 // two casts to be inserted if the sizes are the same. This could
6103 // only be converting signedness, which is a noop.
6104 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006105 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6106 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006107 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006108 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6109 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6110 return BinaryOperator::create(
6111 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006112 }
6113 }
6114
6115 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6116 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6117 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006118 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006119 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006120 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006121 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6122 }
6123 break;
6124 case Instruction::SDiv:
6125 case Instruction::UDiv:
6126 case Instruction::SRem:
6127 case Instruction::URem:
6128 // If we are just changing the sign, rewrite.
6129 if (DestBitSize == SrcBitSize) {
6130 // Don't insert two casts if they cannot be eliminated. We allow
6131 // two casts to be inserted if the sizes are the same. This could
6132 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006133 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6134 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006135 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6136 Op0, DestTy, SrcI);
6137 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6138 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006139 return BinaryOperator::create(
6140 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6141 }
6142 }
6143 break;
6144
6145 case Instruction::Shl:
6146 // Allow changing the sign of the source operand. Do not allow
6147 // changing the size of the shift, UNLESS the shift amount is a
6148 // constant. We must not change variable sized shifts to a smaller
6149 // size, because it is undefined to shift more bits out than exist
6150 // in the value.
6151 if (DestBitSize == SrcBitSize ||
6152 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006153 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6154 Instruction::BitCast : Instruction::Trunc);
6155 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006156 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6157 }
6158 break;
6159 case Instruction::AShr:
6160 // If this is a signed shr, and if all bits shifted in are about to be
6161 // truncated off, turn it into an unsigned shr to allow greater
6162 // simplifications.
6163 if (DestBitSize < SrcBitSize &&
6164 isa<ConstantInt>(Op1)) {
6165 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6166 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6167 // Insert the new logical shift right.
6168 return new ShiftInst(Instruction::LShr, Op0, Op1);
6169 }
6170 }
6171 break;
6172
Reid Spencer266e42b2006-12-23 06:05:41 +00006173 case Instruction::ICmp:
6174 // If we are just checking for a icmp eq of a single bit and casting it
6175 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006176 // cast to integer to avoid the comparison.
6177 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6178 uint64_t Op1CV = Op1C->getZExtValue();
6179 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6180 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6181 // cast (X == 1) to int --> X iff X has only the low bit set.
6182 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6183 // cast (X != 0) to int --> X iff X has only the low bit set.
6184 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6185 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6186 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6187 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6188 // If Op1C some other power of two, convert:
6189 uint64_t KnownZero, KnownOne;
6190 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6191 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006192
6193 // This only works for EQ and NE
6194 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6195 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6196 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006197
6198 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006199 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006200 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6201 // (X&4) == 2 --> false
6202 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006203 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006204 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006205 return ReplaceInstUsesWith(CI, Res);
6206 }
6207
6208 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6209 Value *In = Op0;
6210 if (ShiftAmt) {
6211 // Perform a logical shr by shiftamt.
6212 // Insert the shift to put the result in the low bit.
6213 In = InsertNewInstBefore(
6214 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006215 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006216 In->getName()+".lobit"), CI);
6217 }
6218
Reid Spencer266e42b2006-12-23 06:05:41 +00006219 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006220 Constant *One = ConstantInt::get(In->getType(), 1);
6221 In = BinaryOperator::createXor(In, One, "tmp");
6222 InsertNewInstBefore(cast<Instruction>(In), CI);
6223 }
6224
6225 if (CI.getType() == In->getType())
6226 return ReplaceInstUsesWith(CI, In);
6227 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006228 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006229 }
6230 }
6231 }
6232 break;
6233 }
6234 return 0;
6235}
6236
6237Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006238 if (Instruction *Result = commonIntCastTransforms(CI))
6239 return Result;
6240
6241 Value *Src = CI.getOperand(0);
6242 const Type *Ty = CI.getType();
6243 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6244
6245 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6246 switch (SrcI->getOpcode()) {
6247 default: break;
6248 case Instruction::LShr:
6249 // We can shrink lshr to something smaller if we know the bits shifted in
6250 // are already zeros.
6251 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6252 unsigned ShAmt = ShAmtV->getZExtValue();
6253
6254 // Get a mask for the bits shifting in.
6255 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006256 Value* SrcIOp0 = SrcI->getOperand(0);
6257 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006258 if (ShAmt >= DestBitWidth) // All zeros.
6259 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6260
6261 // Okay, we can shrink this. Truncate the input, then return a new
6262 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006263 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006264 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6265 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006266 } else { // This is a variable shr.
6267
6268 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6269 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6270 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006271 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006272 Value *One = ConstantInt::get(SrcI->getType(), 1);
6273
6274 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6275 SrcI->getOperand(1),
6276 "tmp"), CI);
6277 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6278 SrcI->getOperand(0),
6279 "tmp"), CI);
6280 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006281 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006282 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006283 }
6284 break;
6285 }
6286 }
6287
6288 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006289}
6290
6291Instruction *InstCombiner::visitZExt(CastInst &CI) {
6292 // If one of the common conversion will work ..
6293 if (Instruction *Result = commonIntCastTransforms(CI))
6294 return Result;
6295
6296 Value *Src = CI.getOperand(0);
6297
6298 // If this is a cast of a cast
6299 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006300 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6301 // types and if the sizes are just right we can convert this into a logical
6302 // 'and' which will be much cheaper than the pair of casts.
6303 if (isa<TruncInst>(CSrc)) {
6304 // Get the sizes of the types involved
6305 Value *A = CSrc->getOperand(0);
6306 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6307 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6308 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6309 // If we're actually extending zero bits and the trunc is a no-op
6310 if (MidSize < DstSize && SrcSize == DstSize) {
6311 // Replace both of the casts with an And of the type mask.
6312 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6313 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6314 Instruction *And =
6315 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6316 // Unfortunately, if the type changed, we need to cast it back.
6317 if (And->getType() != CI.getType()) {
6318 And->setName(CSrc->getName()+".mask");
6319 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006320 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006321 }
6322 return And;
6323 }
6324 }
6325 }
6326
6327 return 0;
6328}
6329
6330Instruction *InstCombiner::visitSExt(CastInst &CI) {
6331 return commonIntCastTransforms(CI);
6332}
6333
6334Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6335 return commonCastTransforms(CI);
6336}
6337
6338Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6339 return commonCastTransforms(CI);
6340}
6341
6342Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006343 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006344}
6345
6346Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006347 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006348}
6349
6350Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6351 return commonCastTransforms(CI);
6352}
6353
6354Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6355 return commonCastTransforms(CI);
6356}
6357
6358Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006359 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006360}
6361
6362Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6363 return commonCastTransforms(CI);
6364}
6365
6366Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6367
6368 // If the operands are integer typed then apply the integer transforms,
6369 // otherwise just apply the common ones.
6370 Value *Src = CI.getOperand(0);
6371 const Type *SrcTy = Src->getType();
6372 const Type *DestTy = CI.getType();
6373
6374 if (SrcTy->isInteger() && DestTy->isInteger()) {
6375 if (Instruction *Result = commonIntCastTransforms(CI))
6376 return Result;
6377 } else {
6378 if (Instruction *Result = commonCastTransforms(CI))
6379 return Result;
6380 }
6381
6382
6383 // Get rid of casts from one type to the same type. These are useless and can
6384 // be replaced by the operand.
6385 if (DestTy == Src->getType())
6386 return ReplaceInstUsesWith(CI, Src);
6387
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006388 // If the source and destination are pointers, and this cast is equivalent to
6389 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6390 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006391 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6392 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6393 const Type *DstElTy = DstPTy->getElementType();
6394 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006395
Reid Spencerc635f472006-12-31 05:48:39 +00006396 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006397 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006398 while (SrcElTy != DstElTy &&
6399 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6400 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6401 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006402 ++NumZeros;
6403 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006404
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006405 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006406 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006407 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6408 return new GetElementPtrInst(Src, Idxs);
6409 }
6410 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006411 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006412
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006413 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6414 if (SVI->hasOneUse()) {
6415 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6416 // a bitconvert to a vector with the same # elts.
6417 if (isa<PackedType>(DestTy) &&
6418 cast<PackedType>(DestTy)->getNumElements() ==
6419 SVI->getType()->getNumElements()) {
6420 CastInst *Tmp;
6421 // If either of the operands is a cast from CI.getType(), then
6422 // evaluating the shuffle in the casted destination's type will allow
6423 // us to eliminate at least one cast.
6424 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6425 Tmp->getOperand(0)->getType() == DestTy) ||
6426 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6427 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006428 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6429 SVI->getOperand(0), DestTy, &CI);
6430 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6431 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006432 // Return a new shuffle vector. Use the same element ID's, as we
6433 // know the vector types match #elts.
6434 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006435 }
6436 }
6437 }
6438 }
Chris Lattner260ab202002-04-18 17:39:14 +00006439 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006440}
6441
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006442/// GetSelectFoldableOperands - We want to turn code that looks like this:
6443/// %C = or %A, %B
6444/// %D = select %cond, %C, %A
6445/// into:
6446/// %C = select %cond, %B, 0
6447/// %D = or %A, %C
6448///
6449/// Assuming that the specified instruction is an operand to the select, return
6450/// a bitmask indicating which operands of this instruction are foldable if they
6451/// equal the other incoming value of the select.
6452///
6453static unsigned GetSelectFoldableOperands(Instruction *I) {
6454 switch (I->getOpcode()) {
6455 case Instruction::Add:
6456 case Instruction::Mul:
6457 case Instruction::And:
6458 case Instruction::Or:
6459 case Instruction::Xor:
6460 return 3; // Can fold through either operand.
6461 case Instruction::Sub: // Can only fold on the amount subtracted.
6462 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006463 case Instruction::LShr:
6464 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006465 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006466 default:
6467 return 0; // Cannot fold
6468 }
6469}
6470
6471/// GetSelectFoldableConstant - For the same transformation as the previous
6472/// function, return the identity constant that goes into the select.
6473static Constant *GetSelectFoldableConstant(Instruction *I) {
6474 switch (I->getOpcode()) {
6475 default: assert(0 && "This cannot happen!"); abort();
6476 case Instruction::Add:
6477 case Instruction::Sub:
6478 case Instruction::Or:
6479 case Instruction::Xor:
6480 return Constant::getNullValue(I->getType());
6481 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006482 case Instruction::LShr:
6483 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006484 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006485 case Instruction::And:
6486 return ConstantInt::getAllOnesValue(I->getType());
6487 case Instruction::Mul:
6488 return ConstantInt::get(I->getType(), 1);
6489 }
6490}
6491
Chris Lattner411336f2005-01-19 21:50:18 +00006492/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6493/// have the same opcode and only one use each. Try to simplify this.
6494Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6495 Instruction *FI) {
6496 if (TI->getNumOperands() == 1) {
6497 // If this is a non-volatile load or a cast from the same type,
6498 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006499 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006500 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6501 return 0;
6502 } else {
6503 return 0; // unknown unary op.
6504 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006505
Chris Lattner411336f2005-01-19 21:50:18 +00006506 // Fold this by inserting a select from the input values.
6507 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6508 FI->getOperand(0), SI.getName()+".v");
6509 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006510 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6511 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006512 }
6513
Reid Spencer266e42b2006-12-23 06:05:41 +00006514 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006515 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006516 return 0;
6517
6518 // Figure out if the operations have any operands in common.
6519 Value *MatchOp, *OtherOpT, *OtherOpF;
6520 bool MatchIsOpZero;
6521 if (TI->getOperand(0) == FI->getOperand(0)) {
6522 MatchOp = TI->getOperand(0);
6523 OtherOpT = TI->getOperand(1);
6524 OtherOpF = FI->getOperand(1);
6525 MatchIsOpZero = true;
6526 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6527 MatchOp = TI->getOperand(1);
6528 OtherOpT = TI->getOperand(0);
6529 OtherOpF = FI->getOperand(0);
6530 MatchIsOpZero = false;
6531 } else if (!TI->isCommutative()) {
6532 return 0;
6533 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6534 MatchOp = TI->getOperand(0);
6535 OtherOpT = TI->getOperand(1);
6536 OtherOpF = FI->getOperand(0);
6537 MatchIsOpZero = true;
6538 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6539 MatchOp = TI->getOperand(1);
6540 OtherOpT = TI->getOperand(0);
6541 OtherOpF = FI->getOperand(1);
6542 MatchIsOpZero = true;
6543 } else {
6544 return 0;
6545 }
6546
6547 // If we reach here, they do have operations in common.
6548 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6549 OtherOpF, SI.getName()+".v");
6550 InsertNewInstBefore(NewSI, SI);
6551
6552 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6553 if (MatchIsOpZero)
6554 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6555 else
6556 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006557 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006558
6559 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6560 if (MatchIsOpZero)
6561 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6562 else
6563 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006564}
6565
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006566Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006567 Value *CondVal = SI.getCondition();
6568 Value *TrueVal = SI.getTrueValue();
6569 Value *FalseVal = SI.getFalseValue();
6570
6571 // select true, X, Y -> X
6572 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006573 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006574 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006575
6576 // select C, X, X -> X
6577 if (TrueVal == FalseVal)
6578 return ReplaceInstUsesWith(SI, TrueVal);
6579
Chris Lattner81a7a232004-10-16 18:11:37 +00006580 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6581 return ReplaceInstUsesWith(SI, FalseVal);
6582 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6583 return ReplaceInstUsesWith(SI, TrueVal);
6584 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6585 if (isa<Constant>(TrueVal))
6586 return ReplaceInstUsesWith(SI, TrueVal);
6587 else
6588 return ReplaceInstUsesWith(SI, FalseVal);
6589 }
6590
Reid Spencer542964f2007-01-11 18:21:29 +00006591 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006592 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006593 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006594 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006595 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006596 } else {
6597 // Change: A = select B, false, C --> A = and !B, C
6598 Value *NotCond =
6599 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6600 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006601 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006602 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006603 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006604 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006605 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006606 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006607 } else {
6608 // Change: A = select B, C, true --> A = or !B, C
6609 Value *NotCond =
6610 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6611 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006612 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006613 }
6614 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006615 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006616
Chris Lattner183b3362004-04-09 19:05:30 +00006617 // Selecting between two integer constants?
6618 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6619 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6620 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006621 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006622 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006623 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006624 // select C, 0, 1 -> cast !C to int
6625 Value *NotCond =
6626 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006627 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006628 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006629 }
Chris Lattner35167c32004-06-09 07:59:58 +00006630
Reid Spencer266e42b2006-12-23 06:05:41 +00006631 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006632
Reid Spencer266e42b2006-12-23 06:05:41 +00006633 // (x <s 0) ? -1 : 0 -> ashr x, 31
6634 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006635 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6636 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6637 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006638 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006639 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006640 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006641 else {
6642 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006643 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006644 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006645 }
6646
6647 if (CanXForm) {
6648 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006649 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006650 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006651 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006652 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006653 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006654 ShAmt, "ones");
6655 InsertNewInstBefore(SRA, SI);
6656
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006657 // Finally, convert to the type of the select RHS. We figure out
6658 // if this requires a SExt, Trunc or BitCast based on the sizes.
6659 Instruction::CastOps opc = Instruction::BitCast;
6660 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6661 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6662 if (SRASize < SISize)
6663 opc = Instruction::SExt;
6664 else if (SRASize > SISize)
6665 opc = Instruction::Trunc;
6666 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006667 }
6668 }
6669
6670
6671 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006672 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006673 // non-constant value, eliminate this whole mess. This corresponds to
6674 // cases like this: ((X & 27) ? 27 : 0)
6675 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006676 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006677 cast<Constant>(IC->getOperand(1))->isNullValue())
6678 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6679 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006680 isa<ConstantInt>(ICA->getOperand(1)) &&
6681 (ICA->getOperand(1) == TrueValC ||
6682 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006683 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6684 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006685 // know whether we have a icmp_ne or icmp_eq and whether the
6686 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006687 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006688 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006689 Value *V = ICA;
6690 if (ShouldNotVal)
6691 V = InsertNewInstBefore(BinaryOperator::create(
6692 Instruction::Xor, V, ICA->getOperand(1)), SI);
6693 return ReplaceInstUsesWith(SI, V);
6694 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006695 }
Chris Lattner533bc492004-03-30 19:37:13 +00006696 }
Chris Lattner623fba12004-04-10 22:21:27 +00006697
6698 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006699 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6700 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006701 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006702 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006703 return ReplaceInstUsesWith(SI, FalseVal);
6704 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006705 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006706 return ReplaceInstUsesWith(SI, TrueVal);
6707 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6708
Reid Spencer266e42b2006-12-23 06:05:41 +00006709 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006710 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006711 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006712 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006713 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006714 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6715 return ReplaceInstUsesWith(SI, TrueVal);
6716 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6717 }
6718 }
6719
6720 // See if we are selecting two values based on a comparison of the two values.
6721 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6722 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6723 // Transform (X == Y) ? X : Y -> Y
6724 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6725 return ReplaceInstUsesWith(SI, FalseVal);
6726 // Transform (X != Y) ? X : Y -> X
6727 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6728 return ReplaceInstUsesWith(SI, TrueVal);
6729 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6730
6731 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6732 // Transform (X == Y) ? Y : X -> X
6733 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6734 return ReplaceInstUsesWith(SI, FalseVal);
6735 // Transform (X != Y) ? Y : X -> Y
6736 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006737 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006738 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6739 }
6740 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006741
Chris Lattnera04c9042005-01-13 22:52:24 +00006742 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6743 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6744 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006745 Instruction *AddOp = 0, *SubOp = 0;
6746
Chris Lattner411336f2005-01-19 21:50:18 +00006747 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6748 if (TI->getOpcode() == FI->getOpcode())
6749 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6750 return IV;
6751
6752 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6753 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006754 if (TI->getOpcode() == Instruction::Sub &&
6755 FI->getOpcode() == Instruction::Add) {
6756 AddOp = FI; SubOp = TI;
6757 } else if (FI->getOpcode() == Instruction::Sub &&
6758 TI->getOpcode() == Instruction::Add) {
6759 AddOp = TI; SubOp = FI;
6760 }
6761
6762 if (AddOp) {
6763 Value *OtherAddOp = 0;
6764 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6765 OtherAddOp = AddOp->getOperand(1);
6766 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6767 OtherAddOp = AddOp->getOperand(0);
6768 }
6769
6770 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006771 // So at this point we know we have (Y -> OtherAddOp):
6772 // select C, (add X, Y), (sub X, Z)
6773 Value *NegVal; // Compute -Z
6774 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6775 NegVal = ConstantExpr::getNeg(C);
6776 } else {
6777 NegVal = InsertNewInstBefore(
6778 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006779 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006780
6781 Value *NewTrueOp = OtherAddOp;
6782 Value *NewFalseOp = NegVal;
6783 if (AddOp != TI)
6784 std::swap(NewTrueOp, NewFalseOp);
6785 Instruction *NewSel =
6786 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6787
6788 NewSel = InsertNewInstBefore(NewSel, SI);
6789 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006790 }
6791 }
6792 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006793
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006794 // See if we can fold the select into one of our operands.
6795 if (SI.getType()->isInteger()) {
6796 // See the comment above GetSelectFoldableOperands for a description of the
6797 // transformation we are doing here.
6798 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6799 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6800 !isa<Constant>(FalseVal))
6801 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6802 unsigned OpToFold = 0;
6803 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6804 OpToFold = 1;
6805 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6806 OpToFold = 2;
6807 }
6808
6809 if (OpToFold) {
6810 Constant *C = GetSelectFoldableConstant(TVI);
6811 std::string Name = TVI->getName(); TVI->setName("");
6812 Instruction *NewSel =
6813 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6814 Name);
6815 InsertNewInstBefore(NewSel, SI);
6816 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6817 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6818 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6819 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6820 else {
6821 assert(0 && "Unknown instruction!!");
6822 }
6823 }
6824 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006825
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006826 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6827 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6828 !isa<Constant>(TrueVal))
6829 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6830 unsigned OpToFold = 0;
6831 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6832 OpToFold = 1;
6833 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6834 OpToFold = 2;
6835 }
6836
6837 if (OpToFold) {
6838 Constant *C = GetSelectFoldableConstant(FVI);
6839 std::string Name = FVI->getName(); FVI->setName("");
6840 Instruction *NewSel =
6841 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6842 Name);
6843 InsertNewInstBefore(NewSel, SI);
6844 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6845 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6846 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6847 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6848 else {
6849 assert(0 && "Unknown instruction!!");
6850 }
6851 }
6852 }
6853 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006854
6855 if (BinaryOperator::isNot(CondVal)) {
6856 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6857 SI.setOperand(1, FalseVal);
6858 SI.setOperand(2, TrueVal);
6859 return &SI;
6860 }
6861
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006862 return 0;
6863}
6864
Chris Lattner82f2ef22006-03-06 20:18:44 +00006865/// GetKnownAlignment - If the specified pointer has an alignment that we can
6866/// determine, return it, otherwise return 0.
6867static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6868 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6869 unsigned Align = GV->getAlignment();
6870 if (Align == 0 && TD)
6871 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6872 return Align;
6873 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6874 unsigned Align = AI->getAlignment();
6875 if (Align == 0 && TD) {
6876 if (isa<AllocaInst>(AI))
6877 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6878 else if (isa<MallocInst>(AI)) {
6879 // Malloc returns maximally aligned memory.
6880 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6881 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc635f472006-12-31 05:48:39 +00006882 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006883 }
6884 }
6885 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006886 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006887 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006888 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006889 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006890 if (isa<PointerType>(CI->getOperand(0)->getType()))
6891 return GetKnownAlignment(CI->getOperand(0), TD);
6892 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006893 } else if (isa<GetElementPtrInst>(V) ||
6894 (isa<ConstantExpr>(V) &&
6895 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6896 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006897 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6898 if (BaseAlignment == 0) return 0;
6899
6900 // If all indexes are zero, it is just the alignment of the base pointer.
6901 bool AllZeroOperands = true;
6902 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6903 if (!isa<Constant>(GEPI->getOperand(i)) ||
6904 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6905 AllZeroOperands = false;
6906 break;
6907 }
6908 if (AllZeroOperands)
6909 return BaseAlignment;
6910
6911 // Otherwise, if the base alignment is >= the alignment we expect for the
6912 // base pointer type, then we know that the resultant pointer is aligned at
6913 // least as much as its type requires.
6914 if (!TD) return 0;
6915
6916 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6917 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006918 <= BaseAlignment) {
6919 const Type *GEPTy = GEPI->getType();
6920 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6921 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006922 return 0;
6923 }
6924 return 0;
6925}
6926
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006927
Chris Lattnerc66b2232006-01-13 20:11:04 +00006928/// visitCallInst - CallInst simplification. This mostly only handles folding
6929/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6930/// the heavy lifting.
6931///
Chris Lattner970c33a2003-06-19 17:00:31 +00006932Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006933 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6934 if (!II) return visitCallSite(&CI);
6935
Chris Lattner51ea1272004-02-28 05:22:00 +00006936 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6937 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006938 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006939 bool Changed = false;
6940
6941 // memmove/cpy/set of zero bytes is a noop.
6942 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6943 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6944
Chris Lattner00648e12004-10-12 04:52:52 +00006945 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006946 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006947 // Replace the instruction with just byte operations. We would
6948 // transform other cases to loads/stores, but we don't know if
6949 // alignment is sufficient.
6950 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006951 }
6952
Chris Lattner00648e12004-10-12 04:52:52 +00006953 // If we have a memmove and the source operation is a constant global,
6954 // then the source and dest pointers can't alias, so we can change this
6955 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006956 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006957 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6958 if (GVSrc->isConstant()) {
6959 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006960 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006961 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006962 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006963 Name = "llvm.memcpy.i32";
6964 else
6965 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00006966 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006967 CI.getCalledFunction()->getFunctionType());
6968 CI.setOperand(0, MemCpy);
6969 Changed = true;
6970 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006971 }
Chris Lattner00648e12004-10-12 04:52:52 +00006972
Chris Lattner82f2ef22006-03-06 20:18:44 +00006973 // If we can determine a pointer alignment that is bigger than currently
6974 // set, update the alignment.
6975 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6976 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6977 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6978 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006979 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006980 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006981 Changed = true;
6982 }
6983 } else if (isa<MemSetInst>(MI)) {
6984 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006985 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00006986 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006987 Changed = true;
6988 }
6989 }
6990
Chris Lattnerc66b2232006-01-13 20:11:04 +00006991 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006992 } else {
6993 switch (II->getIntrinsicID()) {
6994 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006995 case Intrinsic::ppc_altivec_lvx:
6996 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006997 case Intrinsic::x86_sse_loadu_ps:
6998 case Intrinsic::x86_sse2_loadu_pd:
6999 case Intrinsic::x86_sse2_loadu_dq:
7000 // Turn PPC lvx -> load if the pointer is known aligned.
7001 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007002 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007003 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007004 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007005 return new LoadInst(Ptr);
7006 }
7007 break;
7008 case Intrinsic::ppc_altivec_stvx:
7009 case Intrinsic::ppc_altivec_stvxl:
7010 // Turn stvx -> store if the pointer is known aligned.
7011 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007012 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007013 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7014 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007015 return new StoreInst(II->getOperand(1), Ptr);
7016 }
7017 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007018 case Intrinsic::x86_sse_storeu_ps:
7019 case Intrinsic::x86_sse2_storeu_pd:
7020 case Intrinsic::x86_sse2_storeu_dq:
7021 case Intrinsic::x86_sse2_storel_dq:
7022 // Turn X86 storeu -> store if the pointer is known aligned.
7023 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7024 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007025 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7026 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007027 return new StoreInst(II->getOperand(2), Ptr);
7028 }
7029 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007030
7031 case Intrinsic::x86_sse_cvttss2si: {
7032 // These intrinsics only demands the 0th element of its input vector. If
7033 // we can simplify the input based on that, do so now.
7034 uint64_t UndefElts;
7035 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7036 UndefElts)) {
7037 II->setOperand(1, V);
7038 return II;
7039 }
7040 break;
7041 }
7042
Chris Lattnere79d2492006-04-06 19:19:17 +00007043 case Intrinsic::ppc_altivec_vperm:
7044 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7045 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7046 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7047
7048 // Check that all of the elements are integer constants or undefs.
7049 bool AllEltsOk = true;
7050 for (unsigned i = 0; i != 16; ++i) {
7051 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7052 !isa<UndefValue>(Mask->getOperand(i))) {
7053 AllEltsOk = false;
7054 break;
7055 }
7056 }
7057
7058 if (AllEltsOk) {
7059 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007060 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7061 II->getOperand(1), Mask->getType(), CI);
7062 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7063 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007064 Value *Result = UndefValue::get(Op0->getType());
7065
7066 // Only extract each element once.
7067 Value *ExtractedElts[32];
7068 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7069
7070 for (unsigned i = 0; i != 16; ++i) {
7071 if (isa<UndefValue>(Mask->getOperand(i)))
7072 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007073 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007074 Idx &= 31; // Match the hardware behavior.
7075
7076 if (ExtractedElts[Idx] == 0) {
7077 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007078 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007079 InsertNewInstBefore(Elt, CI);
7080 ExtractedElts[Idx] = Elt;
7081 }
7082
7083 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007084 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007085 InsertNewInstBefore(cast<Instruction>(Result), CI);
7086 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007087 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007088 }
7089 }
7090 break;
7091
Chris Lattner503221f2006-01-13 21:28:09 +00007092 case Intrinsic::stackrestore: {
7093 // If the save is right next to the restore, remove the restore. This can
7094 // happen when variable allocas are DCE'd.
7095 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7096 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7097 BasicBlock::iterator BI = SS;
7098 if (&*++BI == II)
7099 return EraseInstFromFunction(CI);
7100 }
7101 }
7102
7103 // If the stack restore is in a return/unwind block and if there are no
7104 // allocas or calls between the restore and the return, nuke the restore.
7105 TerminatorInst *TI = II->getParent()->getTerminator();
7106 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7107 BasicBlock::iterator BI = II;
7108 bool CannotRemove = false;
7109 for (++BI; &*BI != TI; ++BI) {
7110 if (isa<AllocaInst>(BI) ||
7111 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7112 CannotRemove = true;
7113 break;
7114 }
7115 }
7116 if (!CannotRemove)
7117 return EraseInstFromFunction(CI);
7118 }
7119 break;
7120 }
7121 }
Chris Lattner00648e12004-10-12 04:52:52 +00007122 }
7123
Chris Lattnerc66b2232006-01-13 20:11:04 +00007124 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007125}
7126
7127// InvokeInst simplification
7128//
7129Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007130 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007131}
7132
Chris Lattneraec3d942003-10-07 22:32:43 +00007133// visitCallSite - Improvements for call and invoke instructions.
7134//
7135Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007136 bool Changed = false;
7137
7138 // If the callee is a constexpr cast of a function, attempt to move the cast
7139 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007140 if (transformConstExprCastCall(CS)) return 0;
7141
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007142 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007143
Chris Lattner61d9d812005-05-13 07:09:09 +00007144 if (Function *CalleeF = dyn_cast<Function>(Callee))
7145 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7146 Instruction *OldCall = CS.getInstruction();
7147 // If the call and callee calling conventions don't match, this call must
7148 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007149 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007150 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007151 if (!OldCall->use_empty())
7152 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7153 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7154 return EraseInstFromFunction(*OldCall);
7155 return 0;
7156 }
7157
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007158 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7159 // This instruction is not reachable, just remove it. We insert a store to
7160 // undef so that we know that this code is not reachable, despite the fact
7161 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007162 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007163 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007164 CS.getInstruction());
7165
7166 if (!CS.getInstruction()->use_empty())
7167 CS.getInstruction()->
7168 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7169
7170 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7171 // Don't break the CFG, insert a dummy cond branch.
7172 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007173 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007174 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007175 return EraseInstFromFunction(*CS.getInstruction());
7176 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007177
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007178 const PointerType *PTy = cast<PointerType>(Callee->getType());
7179 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7180 if (FTy->isVarArg()) {
7181 // See if we can optimize any arguments passed through the varargs area of
7182 // the call.
7183 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7184 E = CS.arg_end(); I != E; ++I)
7185 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7186 // If this cast does not effect the value passed through the varargs
7187 // area, we can eliminate the use of the cast.
7188 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007189 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007190 *I = Op;
7191 Changed = true;
7192 }
7193 }
7194 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007195
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007196 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007197}
7198
Chris Lattner970c33a2003-06-19 17:00:31 +00007199// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7200// attempt to move the cast to the arguments of the call/invoke.
7201//
7202bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7203 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7204 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007205 if (CE->getOpcode() != Instruction::BitCast ||
7206 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007207 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007208 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007209 Instruction *Caller = CS.getInstruction();
7210
7211 // Okay, this is a cast from a function to a different type. Unless doing so
7212 // would cause a type conversion of one of our arguments, change this call to
7213 // be a direct call with arguments casted to the appropriate types.
7214 //
7215 const FunctionType *FT = Callee->getFunctionType();
7216 const Type *OldRetTy = Caller->getType();
7217
Chris Lattner1f7942f2004-01-14 06:06:08 +00007218 // Check to see if we are changing the return type...
7219 if (OldRetTy != FT->getReturnType()) {
Chris Lattner400f9592007-01-06 02:09:32 +00007220 if (Callee->isExternal() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007221 OldRetTy != FT->getReturnType() &&
7222 // Conversion is ok if changing from pointer to int of same size.
7223 !(isa<PointerType>(FT->getReturnType()) &&
7224 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007225 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007226
7227 // If the callsite is an invoke instruction, and the return value is used by
7228 // a PHI node in a successor, we cannot change the return type of the call
7229 // because there is no place to put the cast instruction (without breaking
7230 // the critical edge). Bail out in this case.
7231 if (!Caller->use_empty())
7232 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7233 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7234 UI != E; ++UI)
7235 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7236 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007237 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007238 return false;
7239 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007240
7241 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7242 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007243
Chris Lattner970c33a2003-06-19 17:00:31 +00007244 CallSite::arg_iterator AI = CS.arg_begin();
7245 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7246 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007247 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007248 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007249 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007250 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007251 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007252 (ParamTy->isIntegral() && ActTy->isIntegral() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007253 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7254 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7255 && c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007256 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007257 }
7258
7259 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7260 Callee->isExternal())
7261 return false; // Do not delete arguments unless we have a function body...
7262
7263 // Okay, we decided that this is a safe thing to do: go ahead and start
7264 // inserting cast instructions as necessary...
7265 std::vector<Value*> Args;
7266 Args.reserve(NumActualArgs);
7267
7268 AI = CS.arg_begin();
7269 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7270 const Type *ParamTy = FT->getParamType(i);
7271 if ((*AI)->getType() == ParamTy) {
7272 Args.push_back(*AI);
7273 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007274 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007275 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007276 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007277 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007278 }
7279 }
7280
7281 // If the function takes more arguments than the call was taking, add them
7282 // now...
7283 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7284 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7285
7286 // If we are removing arguments to the function, emit an obnoxious warning...
7287 if (FT->getNumParams() < NumActualArgs)
7288 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007289 cerr << "WARNING: While resolving call to function '"
7290 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007291 } else {
7292 // Add all of the arguments in their promoted form to the arg list...
7293 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7294 const Type *PTy = getPromotedType((*AI)->getType());
7295 if (PTy != (*AI)->getType()) {
7296 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007297 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7298 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007299 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007300 InsertNewInstBefore(Cast, *Caller);
7301 Args.push_back(Cast);
7302 } else {
7303 Args.push_back(*AI);
7304 }
7305 }
7306 }
7307
7308 if (FT->getReturnType() == Type::VoidTy)
7309 Caller->setName(""); // Void type should not have a name...
7310
7311 Instruction *NC;
7312 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007313 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007314 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007315 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007316 } else {
7317 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007318 if (cast<CallInst>(Caller)->isTailCall())
7319 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007320 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007321 }
7322
7323 // Insert a cast of the return type as necessary...
7324 Value *NV = NC;
7325 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7326 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007327 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007328 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7329 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007330 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007331
7332 // If this is an invoke instruction, we should insert it after the first
7333 // non-phi, instruction in the normal successor block.
7334 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7335 BasicBlock::iterator I = II->getNormalDest()->begin();
7336 while (isa<PHINode>(I)) ++I;
7337 InsertNewInstBefore(NC, *I);
7338 } else {
7339 // Otherwise, it's a call, just insert cast right after the call instr
7340 InsertNewInstBefore(NC, *Caller);
7341 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007342 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007343 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007344 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007345 }
7346 }
7347
7348 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7349 Caller->replaceAllUsesWith(NV);
7350 Caller->getParent()->getInstList().erase(Caller);
7351 removeFromWorkList(Caller);
7352 return true;
7353}
7354
Chris Lattnercadac0c2006-11-01 04:51:18 +00007355/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7356/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7357/// and a single binop.
7358Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7359 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007360 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007361 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007362 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007363 Value *LHSVal = FirstInst->getOperand(0);
7364 Value *RHSVal = FirstInst->getOperand(1);
7365
7366 const Type *LHSType = LHSVal->getType();
7367 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007368
7369 // Scan to see if all operands are the same opcode, all have one use, and all
7370 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007371 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007372 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007373 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007374 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007375 // types or GEP's with different index types.
7376 I->getOperand(0)->getType() != LHSType ||
7377 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007378 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007379
7380 // If they are CmpInst instructions, check their predicates
7381 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7382 if (cast<CmpInst>(I)->getPredicate() !=
7383 cast<CmpInst>(FirstInst)->getPredicate())
7384 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007385
7386 // Keep track of which operand needs a phi node.
7387 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7388 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007389 }
7390
Chris Lattner4f218d52006-11-08 19:42:28 +00007391 // Otherwise, this is safe to transform, determine if it is profitable.
7392
7393 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7394 // Indexes are often folded into load/store instructions, so we don't want to
7395 // hide them behind a phi.
7396 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7397 return 0;
7398
Chris Lattnercadac0c2006-11-01 04:51:18 +00007399 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007400 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007401 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007402 if (LHSVal == 0) {
7403 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7404 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7405 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007406 InsertNewInstBefore(NewLHS, PN);
7407 LHSVal = NewLHS;
7408 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007409
7410 if (RHSVal == 0) {
7411 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7412 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7413 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007414 InsertNewInstBefore(NewRHS, PN);
7415 RHSVal = NewRHS;
7416 }
7417
Chris Lattnercd62f112006-11-08 19:29:23 +00007418 // Add all operands to the new PHIs.
7419 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7420 if (NewLHS) {
7421 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7422 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7423 }
7424 if (NewRHS) {
7425 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7426 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7427 }
7428 }
7429
Chris Lattnercadac0c2006-11-01 04:51:18 +00007430 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007431 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007432 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7433 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7434 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007435 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7436 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7437 else {
7438 assert(isa<GetElementPtrInst>(FirstInst));
7439 return new GetElementPtrInst(LHSVal, RHSVal);
7440 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007441}
7442
Chris Lattner14f82c72006-11-01 07:13:54 +00007443/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7444/// of the block that defines it. This means that it must be obvious the value
7445/// of the load is not changed from the point of the load to the end of the
7446/// block it is in.
7447static bool isSafeToSinkLoad(LoadInst *L) {
7448 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7449
7450 for (++BBI; BBI != E; ++BBI)
7451 if (BBI->mayWriteToMemory())
7452 return false;
7453 return true;
7454}
7455
Chris Lattner970c33a2003-06-19 17:00:31 +00007456
Chris Lattner7515cab2004-11-14 19:13:23 +00007457// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7458// operator and they all are only used by the PHI, PHI together their
7459// inputs, and do the operation once, to the result of the PHI.
7460Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7461 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7462
7463 // Scan the instruction, looking for input operations that can be folded away.
7464 // If all input operands to the phi are the same instruction (e.g. a cast from
7465 // the same type or "+42") we can pull the operation through the PHI, reducing
7466 // code size and simplifying code.
7467 Constant *ConstantOp = 0;
7468 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007469 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007470 if (isa<CastInst>(FirstInst)) {
7471 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007472 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7473 isa<CmpInst>(FirstInst)) {
7474 // Can fold binop, compare or shift here if the RHS is a constant,
7475 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007476 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007477 if (ConstantOp == 0)
7478 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007479 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7480 isVolatile = LI->isVolatile();
7481 // We can't sink the load if the loaded value could be modified between the
7482 // load and the PHI.
7483 if (LI->getParent() != PN.getIncomingBlock(0) ||
7484 !isSafeToSinkLoad(LI))
7485 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007486 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007487 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007488 return FoldPHIArgBinOpIntoPHI(PN);
7489 // Can't handle general GEPs yet.
7490 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007491 } else {
7492 return 0; // Cannot fold this operation.
7493 }
7494
7495 // Check to see if all arguments are the same operation.
7496 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7497 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7498 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007499 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007500 return 0;
7501 if (CastSrcTy) {
7502 if (I->getOperand(0)->getType() != CastSrcTy)
7503 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007504 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007505 // We can't sink the load if the loaded value could be modified between
7506 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007507 if (LI->isVolatile() != isVolatile ||
7508 LI->getParent() != PN.getIncomingBlock(i) ||
7509 !isSafeToSinkLoad(LI))
7510 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007511 } else if (I->getOperand(1) != ConstantOp) {
7512 return 0;
7513 }
7514 }
7515
7516 // Okay, they are all the same operation. Create a new PHI node of the
7517 // correct type, and PHI together all of the LHS's of the instructions.
7518 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7519 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007520 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007521
7522 Value *InVal = FirstInst->getOperand(0);
7523 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007524
7525 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007526 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7527 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7528 if (NewInVal != InVal)
7529 InVal = 0;
7530 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7531 }
7532
7533 Value *PhiVal;
7534 if (InVal) {
7535 // The new PHI unions all of the same values together. This is really
7536 // common, so we handle it intelligently here for compile-time speed.
7537 PhiVal = InVal;
7538 delete NewPN;
7539 } else {
7540 InsertNewInstBefore(NewPN, PN);
7541 PhiVal = NewPN;
7542 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007543
Chris Lattner7515cab2004-11-14 19:13:23 +00007544 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007545 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7546 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007547 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007548 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007549 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007550 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007551 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7552 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7553 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007554 else
7555 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007556 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007557}
Chris Lattner48a44f72002-05-02 17:06:02 +00007558
Chris Lattner71536432005-01-17 05:10:15 +00007559/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7560/// that is dead.
7561static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7562 if (PN->use_empty()) return true;
7563 if (!PN->hasOneUse()) return false;
7564
7565 // Remember this node, and if we find the cycle, return.
7566 if (!PotentiallyDeadPHIs.insert(PN).second)
7567 return true;
7568
7569 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7570 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007571
Chris Lattner71536432005-01-17 05:10:15 +00007572 return false;
7573}
7574
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007575// PHINode simplification
7576//
Chris Lattner113f4f42002-06-25 16:13:24 +00007577Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007578 // If LCSSA is around, don't mess with Phi nodes
7579 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007580
Owen Andersonae8aa642006-07-10 22:03:18 +00007581 if (Value *V = PN.hasConstantValue())
7582 return ReplaceInstUsesWith(PN, V);
7583
Owen Andersonae8aa642006-07-10 22:03:18 +00007584 // If all PHI operands are the same operation, pull them through the PHI,
7585 // reducing code size.
7586 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7587 PN.getIncomingValue(0)->hasOneUse())
7588 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7589 return Result;
7590
7591 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7592 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7593 // PHI)... break the cycle.
7594 if (PN.hasOneUse())
7595 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7596 std::set<PHINode*> PotentiallyDeadPHIs;
7597 PotentiallyDeadPHIs.insert(&PN);
7598 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7599 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7600 }
7601
Chris Lattner91daeb52003-12-19 05:58:40 +00007602 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007603}
7604
Reid Spencer13bc5d72006-12-12 09:18:51 +00007605static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7606 Instruction *InsertPoint,
7607 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007608 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7609 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007610 // We must cast correctly to the pointer type. Ensure that we
7611 // sign extend the integer value if it is smaller as this is
7612 // used for address computation.
7613 Instruction::CastOps opcode =
7614 (VTySize < PtrSize ? Instruction::SExt :
7615 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7616 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007617}
7618
Chris Lattner48a44f72002-05-02 17:06:02 +00007619
Chris Lattner113f4f42002-06-25 16:13:24 +00007620Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007621 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007622 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007623 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007624 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007625 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007626
Chris Lattner81a7a232004-10-16 18:11:37 +00007627 if (isa<UndefValue>(GEP.getOperand(0)))
7628 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7629
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007630 bool HasZeroPointerIndex = false;
7631 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7632 HasZeroPointerIndex = C->isNullValue();
7633
7634 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007635 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007636
Chris Lattner69193f92004-04-05 01:30:19 +00007637 // Eliminate unneeded casts for indices.
7638 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007639 gep_type_iterator GTI = gep_type_begin(GEP);
7640 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7641 if (isa<SequentialType>(*GTI)) {
7642 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7643 Value *Src = CI->getOperand(0);
7644 const Type *SrcTy = Src->getType();
7645 const Type *DestTy = CI->getType();
7646 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007647 if (SrcTy->getPrimitiveSizeInBits() ==
7648 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007649 // We can always eliminate a cast from ulong or long to the other.
7650 // We can always eliminate a cast from uint to int or the other on
7651 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007652 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007653 MadeChange = true;
7654 GEP.setOperand(i, Src);
7655 }
Reid Spencer8f166b02007-01-08 16:32:00 +00007656 } else if (SrcTy->getPrimitiveSizeInBits() <
7657 DestTy->getPrimitiveSizeInBits() &&
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007658 SrcTy->getPrimitiveSizeInBits() == 32) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007659 // We can eliminate a cast from [u]int to [u]long iff the target
7660 // is a 32-bit pointer target.
7661 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007662 MadeChange = true;
7663 GEP.setOperand(i, Src);
7664 }
Chris Lattner69193f92004-04-05 01:30:19 +00007665 }
7666 }
7667 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007668 // If we are using a wider index than needed for this platform, shrink it
7669 // to what we need. If the incoming value needs a cast instruction,
7670 // insert it. This explicit cast can make subsequent optimizations more
7671 // obvious.
7672 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007673 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007674 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007675 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007676 MadeChange = true;
7677 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007678 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7679 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007680 GEP.setOperand(i, Op);
7681 MadeChange = true;
7682 }
Chris Lattner69193f92004-04-05 01:30:19 +00007683 }
7684 if (MadeChange) return &GEP;
7685
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007686 // Combine Indices - If the source pointer to this getelementptr instruction
7687 // is a getelementptr instruction, combine the indices of the two
7688 // getelementptr instructions into a single instruction.
7689 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007690 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007691 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007692 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007693
7694 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007695 // Note that if our source is a gep chain itself that we wait for that
7696 // chain to be resolved before we perform this transformation. This
7697 // avoids us creating a TON of code in some cases.
7698 //
7699 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7700 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7701 return 0; // Wait until our source is folded to completion.
7702
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007703 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007704
7705 // Find out whether the last index in the source GEP is a sequential idx.
7706 bool EndsWithSequential = false;
7707 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7708 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007709 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007710
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007711 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007712 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007713 // Replace: gep (gep %P, long B), long A, ...
7714 // With: T = long A+B; gep %P, T, ...
7715 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007716 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007717 if (SO1 == Constant::getNullValue(SO1->getType())) {
7718 Sum = GO1;
7719 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7720 Sum = SO1;
7721 } else {
7722 // If they aren't the same type, convert both to an integer of the
7723 // target's pointer size.
7724 if (SO1->getType() != GO1->getType()) {
7725 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007726 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007727 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007728 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007729 } else {
7730 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007731 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007732 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007733 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007734
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007735 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007736 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007737 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007738 } else {
7739 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007740 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7741 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007742 }
7743 }
7744 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007745 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7746 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7747 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007748 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7749 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007750 }
Chris Lattner69193f92004-04-05 01:30:19 +00007751 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007752
7753 // Recycle the GEP we already have if possible.
7754 if (SrcGEPOperands.size() == 2) {
7755 GEP.setOperand(0, SrcGEPOperands[0]);
7756 GEP.setOperand(1, Sum);
7757 return &GEP;
7758 } else {
7759 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7760 SrcGEPOperands.end()-1);
7761 Indices.push_back(Sum);
7762 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7763 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007764 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007765 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007766 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007767 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007768 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7769 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007770 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7771 }
7772
7773 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007774 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007775
Chris Lattner5f667a62004-05-07 22:09:22 +00007776 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007777 // GEP of global variable. If all of the indices for this GEP are
7778 // constants, we can promote this to a constexpr instead of an instruction.
7779
7780 // Scan for nonconstants...
7781 std::vector<Constant*> Indices;
7782 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7783 for (; I != E && isa<Constant>(*I); ++I)
7784 Indices.push_back(cast<Constant>(*I));
7785
7786 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007787 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007788
7789 // Replace all uses of the GEP with the new constexpr...
7790 return ReplaceInstUsesWith(GEP, CE);
7791 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007792 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007793 if (!isa<PointerType>(X->getType())) {
7794 // Not interesting. Source pointer must be a cast from pointer.
7795 } else if (HasZeroPointerIndex) {
7796 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7797 // into : GEP [10 x ubyte]* X, long 0, ...
7798 //
7799 // This occurs when the program declares an array extern like "int X[];"
7800 //
7801 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7802 const PointerType *XTy = cast<PointerType>(X->getType());
7803 if (const ArrayType *XATy =
7804 dyn_cast<ArrayType>(XTy->getElementType()))
7805 if (const ArrayType *CATy =
7806 dyn_cast<ArrayType>(CPTy->getElementType()))
7807 if (CATy->getElementType() == XATy->getElementType()) {
7808 // At this point, we know that the cast source type is a pointer
7809 // to an array of the same type as the destination pointer
7810 // array. Because the array type is never stepped over (there
7811 // is a leading zero) we can fold the cast into this GEP.
7812 GEP.setOperand(0, X);
7813 return &GEP;
7814 }
7815 } else if (GEP.getNumOperands() == 2) {
7816 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007817 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7818 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007819 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7820 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7821 if (isa<ArrayType>(SrcElTy) &&
7822 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7823 TD->getTypeSize(ResElTy)) {
7824 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007825 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007826 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007827 // V and GEP are both pointer types --> BitCast
7828 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007829 }
Chris Lattner2a893292005-09-13 18:36:04 +00007830
7831 // Transform things like:
7832 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7833 // (where tmp = 8*tmp2) into:
7834 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7835
7836 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007837 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007838 uint64_t ArrayEltSize =
7839 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7840
7841 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7842 // allow either a mul, shift, or constant here.
7843 Value *NewIdx = 0;
7844 ConstantInt *Scale = 0;
7845 if (ArrayEltSize == 1) {
7846 NewIdx = GEP.getOperand(1);
7847 Scale = ConstantInt::get(NewIdx->getType(), 1);
7848 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007849 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007850 Scale = CI;
7851 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7852 if (Inst->getOpcode() == Instruction::Shl &&
7853 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007854 unsigned ShAmt =
7855 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007856 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007857 NewIdx = Inst->getOperand(0);
7858 } else if (Inst->getOpcode() == Instruction::Mul &&
7859 isa<ConstantInt>(Inst->getOperand(1))) {
7860 Scale = cast<ConstantInt>(Inst->getOperand(1));
7861 NewIdx = Inst->getOperand(0);
7862 }
7863 }
7864
7865 // If the index will be to exactly the right offset with the scale taken
7866 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007867 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007868 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007869 Scale = ConstantInt::get(Scale->getType(),
7870 Scale->getZExtValue() / ArrayEltSize);
7871 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007872 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7873 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007874 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7875 NewIdx = InsertNewInstBefore(Sc, GEP);
7876 }
7877
7878 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007879 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007880 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007881 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007882 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7883 // The NewGEP must be pointer typed, so must the old one -> BitCast
7884 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007885 }
7886 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007887 }
Chris Lattnerca081252001-12-14 16:52:21 +00007888 }
7889
Chris Lattnerca081252001-12-14 16:52:21 +00007890 return 0;
7891}
7892
Chris Lattner1085bdf2002-11-04 16:18:53 +00007893Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7894 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7895 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007896 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7897 const Type *NewTy =
7898 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007899 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007900
7901 // Create and insert the replacement instruction...
7902 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007903 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007904 else {
7905 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007906 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007907 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007908
7909 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007910
Chris Lattner1085bdf2002-11-04 16:18:53 +00007911 // Scan to the end of the allocation instructions, to skip over a block of
7912 // allocas if possible...
7913 //
7914 BasicBlock::iterator It = New;
7915 while (isa<AllocationInst>(*It)) ++It;
7916
7917 // Now that I is pointing to the first non-allocation-inst in the block,
7918 // insert our getelementptr instruction...
7919 //
Reid Spencerc635f472006-12-31 05:48:39 +00007920 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007921 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7922 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007923
7924 // Now make everything use the getelementptr instead of the original
7925 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007926 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007927 } else if (isa<UndefValue>(AI.getArraySize())) {
7928 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007929 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007930
7931 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7932 // Note that we only do this for alloca's, because malloc should allocate and
7933 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007934 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007935 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007936 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7937
Chris Lattner1085bdf2002-11-04 16:18:53 +00007938 return 0;
7939}
7940
Chris Lattner8427bff2003-12-07 01:24:23 +00007941Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7942 Value *Op = FI.getOperand(0);
7943
7944 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7945 if (CastInst *CI = dyn_cast<CastInst>(Op))
7946 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7947 FI.setOperand(0, CI->getOperand(0));
7948 return &FI;
7949 }
7950
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007951 // free undef -> unreachable.
7952 if (isa<UndefValue>(Op)) {
7953 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007954 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007955 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007956 return EraseInstFromFunction(FI);
7957 }
7958
Chris Lattnerf3a36602004-02-28 04:57:37 +00007959 // If we have 'free null' delete the instruction. This can happen in stl code
7960 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007961 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007962 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007963
Chris Lattner8427bff2003-12-07 01:24:23 +00007964 return 0;
7965}
7966
7967
Chris Lattner72684fe2005-01-31 05:51:45 +00007968/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007969static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7970 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007971 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007972
7973 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007974 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007975 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007976
Chris Lattnerebca4762006-04-02 05:37:12 +00007977 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7978 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007979 // If the source is an array, the code below will not succeed. Check to
7980 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7981 // constants.
7982 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7983 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7984 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00007985 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007986 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7987 SrcTy = cast<PointerType>(CastOp->getType());
7988 SrcPTy = SrcTy->getElementType();
7989 }
7990
Chris Lattnerebca4762006-04-02 05:37:12 +00007991 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7992 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007993 // Do not allow turning this into a load of an integer, which is then
7994 // casted to a pointer, this pessimizes pointer analysis a lot.
7995 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007996 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007997 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007998
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007999 // Okay, we are casting from one integer or pointer type to another of
8000 // the same size. Instead of casting the pointer before the load, cast
8001 // the result of the loaded value.
8002 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8003 CI->getName(),
8004 LI.isVolatile()),LI);
8005 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008006 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008007 }
Chris Lattner35e24772004-07-13 01:49:43 +00008008 }
8009 }
8010 return 0;
8011}
8012
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008013/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008014/// from this value cannot trap. If it is not obviously safe to load from the
8015/// specified pointer, we do a quick local scan of the basic block containing
8016/// ScanFrom, to determine if the address is already accessed.
8017static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8018 // If it is an alloca or global variable, it is always safe to load from.
8019 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8020
8021 // Otherwise, be a little bit agressive by scanning the local block where we
8022 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008023 // from/to. If so, the previous load or store would have already trapped,
8024 // so there is no harm doing an extra load (also, CSE will later eliminate
8025 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008026 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8027
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008028 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008029 --BBI;
8030
8031 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8032 if (LI->getOperand(0) == V) return true;
8033 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8034 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008035
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008036 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008037 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008038}
8039
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008040Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8041 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008042
Chris Lattnera9d84e32005-05-01 04:24:53 +00008043 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008044 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008045 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8046 return Res;
8047
8048 // None of the following transforms are legal for volatile loads.
8049 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008050
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008051 if (&LI.getParent()->front() != &LI) {
8052 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008053 // If the instruction immediately before this is a store to the same
8054 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008055 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8056 if (SI->getOperand(1) == LI.getOperand(0))
8057 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008058 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8059 if (LIB->getOperand(0) == LI.getOperand(0))
8060 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008061 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008062
8063 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8064 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8065 isa<UndefValue>(GEPI->getOperand(0))) {
8066 // Insert a new store to null instruction before the load to indicate
8067 // that this code is not reachable. We do this instead of inserting
8068 // an unreachable instruction directly because we cannot modify the
8069 // CFG.
8070 new StoreInst(UndefValue::get(LI.getType()),
8071 Constant::getNullValue(Op->getType()), &LI);
8072 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8073 }
8074
Chris Lattner81a7a232004-10-16 18:11:37 +00008075 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008076 // load null/undef -> undef
8077 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008078 // Insert a new store to null instruction before the load to indicate that
8079 // this code is not reachable. We do this instead of inserting an
8080 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008081 new StoreInst(UndefValue::get(LI.getType()),
8082 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008083 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008084 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008085
Chris Lattner81a7a232004-10-16 18:11:37 +00008086 // Instcombine load (constant global) into the value loaded.
8087 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8088 if (GV->isConstant() && !GV->isExternal())
8089 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008090
Chris Lattner81a7a232004-10-16 18:11:37 +00008091 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8092 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8093 if (CE->getOpcode() == Instruction::GetElementPtr) {
8094 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8095 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008096 if (Constant *V =
8097 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008098 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008099 if (CE->getOperand(0)->isNullValue()) {
8100 // Insert a new store to null instruction before the load to indicate
8101 // that this code is not reachable. We do this instead of inserting
8102 // an unreachable instruction directly because we cannot modify the
8103 // CFG.
8104 new StoreInst(UndefValue::get(LI.getType()),
8105 Constant::getNullValue(Op->getType()), &LI);
8106 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8107 }
8108
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008109 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008110 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8111 return Res;
8112 }
8113 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008114
Chris Lattnera9d84e32005-05-01 04:24:53 +00008115 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008116 // Change select and PHI nodes to select values instead of addresses: this
8117 // helps alias analysis out a lot, allows many others simplifications, and
8118 // exposes redundancy in the code.
8119 //
8120 // Note that we cannot do the transformation unless we know that the
8121 // introduced loads cannot trap! Something like this is valid as long as
8122 // the condition is always false: load (select bool %C, int* null, int* %G),
8123 // but it would not be valid if we transformed it to load from null
8124 // unconditionally.
8125 //
8126 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8127 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008128 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8129 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008130 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008131 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008132 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008133 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008134 return new SelectInst(SI->getCondition(), V1, V2);
8135 }
8136
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008137 // load (select (cond, null, P)) -> load P
8138 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8139 if (C->isNullValue()) {
8140 LI.setOperand(0, SI->getOperand(2));
8141 return &LI;
8142 }
8143
8144 // load (select (cond, P, null)) -> load P
8145 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8146 if (C->isNullValue()) {
8147 LI.setOperand(0, SI->getOperand(1));
8148 return &LI;
8149 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008150 }
8151 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008152 return 0;
8153}
8154
Chris Lattner72684fe2005-01-31 05:51:45 +00008155/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8156/// when possible.
8157static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8158 User *CI = cast<User>(SI.getOperand(1));
8159 Value *CastOp = CI->getOperand(0);
8160
8161 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8162 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8163 const Type *SrcPTy = SrcTy->getElementType();
8164
8165 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8166 // If the source is an array, the code below will not succeed. Check to
8167 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8168 // constants.
8169 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8170 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8171 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008172 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008173 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8174 SrcTy = cast<PointerType>(CastOp->getType());
8175 SrcPTy = SrcTy->getElementType();
8176 }
8177
8178 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008179 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008180 IC.getTargetData().getTypeSize(DestPTy)) {
8181
8182 // Okay, we are casting from one integer or pointer type to another of
8183 // the same size. Instead of casting the pointer before the store, cast
8184 // the value to be stored.
8185 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008186 Instruction::CastOps opcode = Instruction::BitCast;
8187 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008188 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008189 if (SIOp0->getType()->isIntegral())
8190 opcode = Instruction::IntToPtr;
8191 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008192 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008193 opcode = Instruction::PtrToInt;
8194 }
8195 if (Constant *C = dyn_cast<Constant>(SIOp0))
8196 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008197 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008198 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008199 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008200 return new StoreInst(NewCast, CastOp);
8201 }
8202 }
8203 }
8204 return 0;
8205}
8206
Chris Lattner31f486c2005-01-31 05:36:43 +00008207Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8208 Value *Val = SI.getOperand(0);
8209 Value *Ptr = SI.getOperand(1);
8210
8211 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008212 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008213 ++NumCombined;
8214 return 0;
8215 }
8216
Chris Lattner5997cf92006-02-08 03:25:32 +00008217 // Do really simple DSE, to catch cases where there are several consequtive
8218 // stores to the same location, separated by a few arithmetic operations. This
8219 // situation often occurs with bitfield accesses.
8220 BasicBlock::iterator BBI = &SI;
8221 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8222 --ScanInsts) {
8223 --BBI;
8224
8225 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8226 // Prev store isn't volatile, and stores to the same location?
8227 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8228 ++NumDeadStore;
8229 ++BBI;
8230 EraseInstFromFunction(*PrevSI);
8231 continue;
8232 }
8233 break;
8234 }
8235
Chris Lattnerdab43b22006-05-26 19:19:20 +00008236 // If this is a load, we have to stop. However, if the loaded value is from
8237 // the pointer we're loading and is producing the pointer we're storing,
8238 // then *this* store is dead (X = load P; store X -> P).
8239 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8240 if (LI == Val && LI->getOperand(0) == Ptr) {
8241 EraseInstFromFunction(SI);
8242 ++NumCombined;
8243 return 0;
8244 }
8245 // Otherwise, this is a load from some other location. Stores before it
8246 // may not be dead.
8247 break;
8248 }
8249
Chris Lattner5997cf92006-02-08 03:25:32 +00008250 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008251 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008252 break;
8253 }
8254
8255
8256 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008257
8258 // store X, null -> turns into 'unreachable' in SimplifyCFG
8259 if (isa<ConstantPointerNull>(Ptr)) {
8260 if (!isa<UndefValue>(Val)) {
8261 SI.setOperand(0, UndefValue::get(Val->getType()));
8262 if (Instruction *U = dyn_cast<Instruction>(Val))
8263 WorkList.push_back(U); // Dropped a use.
8264 ++NumCombined;
8265 }
8266 return 0; // Do not modify these!
8267 }
8268
8269 // store undef, Ptr -> noop
8270 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008271 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008272 ++NumCombined;
8273 return 0;
8274 }
8275
Chris Lattner72684fe2005-01-31 05:51:45 +00008276 // If the pointer destination is a cast, see if we can fold the cast into the
8277 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008278 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008279 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8280 return Res;
8281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008282 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008283 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8284 return Res;
8285
Chris Lattner219175c2005-09-12 23:23:25 +00008286
8287 // If this store is the last instruction in the basic block, and if the block
8288 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008289 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008290 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8291 if (BI->isUnconditional()) {
8292 // Check to see if the successor block has exactly two incoming edges. If
8293 // so, see if the other predecessor contains a store to the same location.
8294 // if so, insert a PHI node (if needed) and move the stores down.
8295 BasicBlock *Dest = BI->getSuccessor(0);
8296
8297 pred_iterator PI = pred_begin(Dest);
8298 BasicBlock *Other = 0;
8299 if (*PI != BI->getParent())
8300 Other = *PI;
8301 ++PI;
8302 if (PI != pred_end(Dest)) {
8303 if (*PI != BI->getParent())
8304 if (Other)
8305 Other = 0;
8306 else
8307 Other = *PI;
8308 if (++PI != pred_end(Dest))
8309 Other = 0;
8310 }
8311 if (Other) { // If only one other pred...
8312 BBI = Other->getTerminator();
8313 // Make sure this other block ends in an unconditional branch and that
8314 // there is an instruction before the branch.
8315 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8316 BBI != Other->begin()) {
8317 --BBI;
8318 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8319
8320 // If this instruction is a store to the same location.
8321 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8322 // Okay, we know we can perform this transformation. Insert a PHI
8323 // node now if we need it.
8324 Value *MergedVal = OtherStore->getOperand(0);
8325 if (MergedVal != SI.getOperand(0)) {
8326 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8327 PN->reserveOperandSpace(2);
8328 PN->addIncoming(SI.getOperand(0), SI.getParent());
8329 PN->addIncoming(OtherStore->getOperand(0), Other);
8330 MergedVal = InsertNewInstBefore(PN, Dest->front());
8331 }
8332
8333 // Advance to a place where it is safe to insert the new store and
8334 // insert it.
8335 BBI = Dest->begin();
8336 while (isa<PHINode>(BBI)) ++BBI;
8337 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8338 OtherStore->isVolatile()), *BBI);
8339
8340 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008341 EraseInstFromFunction(SI);
8342 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008343 ++NumCombined;
8344 return 0;
8345 }
8346 }
8347 }
8348 }
8349
Chris Lattner31f486c2005-01-31 05:36:43 +00008350 return 0;
8351}
8352
8353
Chris Lattner9eef8a72003-06-04 04:46:00 +00008354Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8355 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008356 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008357 BasicBlock *TrueDest;
8358 BasicBlock *FalseDest;
8359 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8360 !isa<Constant>(X)) {
8361 // Swap Destinations and condition...
8362 BI.setCondition(X);
8363 BI.setSuccessor(0, FalseDest);
8364 BI.setSuccessor(1, TrueDest);
8365 return &BI;
8366 }
8367
Reid Spencer266e42b2006-12-23 06:05:41 +00008368 // Cannonicalize fcmp_one -> fcmp_oeq
8369 FCmpInst::Predicate FPred; Value *Y;
8370 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8371 TrueDest, FalseDest)))
8372 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8373 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8374 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008375 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008376 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8377 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8378 // Swap Destinations and condition...
8379 BI.setCondition(NewSCC);
8380 BI.setSuccessor(0, FalseDest);
8381 BI.setSuccessor(1, TrueDest);
8382 removeFromWorkList(I);
8383 I->getParent()->getInstList().erase(I);
8384 WorkList.push_back(cast<Instruction>(NewSCC));
8385 return &BI;
8386 }
8387
8388 // Cannonicalize icmp_ne -> icmp_eq
8389 ICmpInst::Predicate IPred;
8390 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8391 TrueDest, FalseDest)))
8392 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8393 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8394 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8395 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8396 std::string Name = I->getName(); I->setName("");
8397 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8398 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008399 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008400 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008401 BI.setSuccessor(0, FalseDest);
8402 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008403 removeFromWorkList(I);
8404 I->getParent()->getInstList().erase(I);
8405 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008406 return &BI;
8407 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008408
Chris Lattner9eef8a72003-06-04 04:46:00 +00008409 return 0;
8410}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008411
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008412Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8413 Value *Cond = SI.getCondition();
8414 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8415 if (I->getOpcode() == Instruction::Add)
8416 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8417 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8418 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008419 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008420 AddRHS));
8421 SI.setOperand(0, I->getOperand(0));
8422 WorkList.push_back(I);
8423 return &SI;
8424 }
8425 }
8426 return 0;
8427}
8428
Chris Lattner6bc98652006-03-05 00:22:33 +00008429/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8430/// is to leave as a vector operation.
8431static bool CheapToScalarize(Value *V, bool isConstant) {
8432 if (isa<ConstantAggregateZero>(V))
8433 return true;
8434 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8435 if (isConstant) return true;
8436 // If all elts are the same, we can extract.
8437 Constant *Op0 = C->getOperand(0);
8438 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8439 if (C->getOperand(i) != Op0)
8440 return false;
8441 return true;
8442 }
8443 Instruction *I = dyn_cast<Instruction>(V);
8444 if (!I) return false;
8445
8446 // Insert element gets simplified to the inserted element or is deleted if
8447 // this is constant idx extract element and its a constant idx insertelt.
8448 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8449 isa<ConstantInt>(I->getOperand(2)))
8450 return true;
8451 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8452 return true;
8453 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8454 if (BO->hasOneUse() &&
8455 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8456 CheapToScalarize(BO->getOperand(1), isConstant)))
8457 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008458 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8459 if (CI->hasOneUse() &&
8460 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8461 CheapToScalarize(CI->getOperand(1), isConstant)))
8462 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008463
8464 return false;
8465}
8466
Chris Lattner12249be2006-05-25 23:48:38 +00008467/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8468/// elements into values that are larger than the #elts in the input.
8469static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8470 unsigned NElts = SVI->getType()->getNumElements();
8471 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8472 return std::vector<unsigned>(NElts, 0);
8473 if (isa<UndefValue>(SVI->getOperand(2)))
8474 return std::vector<unsigned>(NElts, 2*NElts);
8475
8476 std::vector<unsigned> Result;
8477 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8478 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8479 if (isa<UndefValue>(CP->getOperand(i)))
8480 Result.push_back(NElts*2); // undef -> 8
8481 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008482 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008483 return Result;
8484}
8485
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008486/// FindScalarElement - Given a vector and an element number, see if the scalar
8487/// value is already around as a register, for example if it were inserted then
8488/// extracted from the vector.
8489static Value *FindScalarElement(Value *V, unsigned EltNo) {
8490 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8491 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008492 unsigned Width = PTy->getNumElements();
8493 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008494 return UndefValue::get(PTy->getElementType());
8495
8496 if (isa<UndefValue>(V))
8497 return UndefValue::get(PTy->getElementType());
8498 else if (isa<ConstantAggregateZero>(V))
8499 return Constant::getNullValue(PTy->getElementType());
8500 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8501 return CP->getOperand(EltNo);
8502 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8503 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008504 if (!isa<ConstantInt>(III->getOperand(2)))
8505 return 0;
8506 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008507
8508 // If this is an insert to the element we are looking for, return the
8509 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008510 if (EltNo == IIElt)
8511 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008512
8513 // Otherwise, the insertelement doesn't modify the value, recurse on its
8514 // vector input.
8515 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008516 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008517 unsigned InEl = getShuffleMask(SVI)[EltNo];
8518 if (InEl < Width)
8519 return FindScalarElement(SVI->getOperand(0), InEl);
8520 else if (InEl < Width*2)
8521 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8522 else
8523 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008524 }
8525
8526 // Otherwise, we don't know.
8527 return 0;
8528}
8529
Robert Bocchinoa8352962006-01-13 22:48:06 +00008530Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008531
Chris Lattner92346c32006-03-31 18:25:14 +00008532 // If packed val is undef, replace extract with scalar undef.
8533 if (isa<UndefValue>(EI.getOperand(0)))
8534 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8535
8536 // If packed val is constant 0, replace extract with scalar 0.
8537 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8538 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8539
Robert Bocchinoa8352962006-01-13 22:48:06 +00008540 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8541 // If packed val is constant with uniform operands, replace EI
8542 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008543 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008544 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008545 if (C->getOperand(i) != op0) {
8546 op0 = 0;
8547 break;
8548 }
8549 if (op0)
8550 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008551 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008552
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008553 // If extracting a specified index from the vector, see if we can recursively
8554 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008555 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008556 // This instruction only demands the single element from the input vector.
8557 // If the input vector has a single use, simplify it based on this use
8558 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008559 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008560 if (EI.getOperand(0)->hasOneUse()) {
8561 uint64_t UndefElts;
8562 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008563 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008564 UndefElts)) {
8565 EI.setOperand(0, V);
8566 return &EI;
8567 }
8568 }
8569
Reid Spencere0fc4df2006-10-20 07:07:24 +00008570 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008571 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008572 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008573
Chris Lattner83f65782006-05-25 22:53:38 +00008574 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008575 if (I->hasOneUse()) {
8576 // Push extractelement into predecessor operation if legal and
8577 // profitable to do so
8578 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008579 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8580 if (CheapToScalarize(BO, isConstantElt)) {
8581 ExtractElementInst *newEI0 =
8582 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8583 EI.getName()+".lhs");
8584 ExtractElementInst *newEI1 =
8585 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8586 EI.getName()+".rhs");
8587 InsertNewInstBefore(newEI0, EI);
8588 InsertNewInstBefore(newEI1, EI);
8589 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8590 }
Reid Spencerde46e482006-11-02 20:25:50 +00008591 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008592 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008593 PointerType::get(EI.getType()), EI);
8594 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008595 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008596 InsertNewInstBefore(GEP, EI);
8597 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008598 }
8599 }
8600 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8601 // Extracting the inserted element?
8602 if (IE->getOperand(2) == EI.getOperand(1))
8603 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8604 // If the inserted and extracted elements are constants, they must not
8605 // be the same value, extract from the pre-inserted value instead.
8606 if (isa<Constant>(IE->getOperand(2)) &&
8607 isa<Constant>(EI.getOperand(1))) {
8608 AddUsesToWorkList(EI);
8609 EI.setOperand(0, IE->getOperand(0));
8610 return &EI;
8611 }
8612 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8613 // If this is extracting an element from a shufflevector, figure out where
8614 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008615 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8616 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008617 Value *Src;
8618 if (SrcIdx < SVI->getType()->getNumElements())
8619 Src = SVI->getOperand(0);
8620 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8621 SrcIdx -= SVI->getType()->getNumElements();
8622 Src = SVI->getOperand(1);
8623 } else {
8624 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008625 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008626 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008627 }
8628 }
Chris Lattner83f65782006-05-25 22:53:38 +00008629 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008630 return 0;
8631}
8632
Chris Lattner90951862006-04-16 00:51:47 +00008633/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8634/// elements from either LHS or RHS, return the shuffle mask and true.
8635/// Otherwise, return false.
8636static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8637 std::vector<Constant*> &Mask) {
8638 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8639 "Invalid CollectSingleShuffleElements");
8640 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8641
8642 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008643 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008644 return true;
8645 } else if (V == LHS) {
8646 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008647 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008648 return true;
8649 } else if (V == RHS) {
8650 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008651 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008652 return true;
8653 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8654 // If this is an insert of an extract from some other vector, include it.
8655 Value *VecOp = IEI->getOperand(0);
8656 Value *ScalarOp = IEI->getOperand(1);
8657 Value *IdxOp = IEI->getOperand(2);
8658
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008659 if (!isa<ConstantInt>(IdxOp))
8660 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008661 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008662
8663 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8664 // Okay, we can handle this if the vector we are insertinting into is
8665 // transitively ok.
8666 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8667 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008668 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008669 return true;
8670 }
8671 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8672 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008673 EI->getOperand(0)->getType() == V->getType()) {
8674 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008675 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008676
8677 // This must be extracting from either LHS or RHS.
8678 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8679 // Okay, we can handle this if the vector we are insertinting into is
8680 // transitively ok.
8681 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8682 // If so, update the mask to reflect the inserted value.
8683 if (EI->getOperand(0) == LHS) {
8684 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008685 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008686 } else {
8687 assert(EI->getOperand(0) == RHS);
8688 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008689 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008690
8691 }
8692 return true;
8693 }
8694 }
8695 }
8696 }
8697 }
8698 // TODO: Handle shufflevector here!
8699
8700 return false;
8701}
8702
8703/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8704/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8705/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008706static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008707 Value *&RHS) {
8708 assert(isa<PackedType>(V->getType()) &&
8709 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008710 "Invalid shuffle!");
8711 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8712
8713 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008714 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008715 return V;
8716 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008717 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008718 return V;
8719 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8720 // If this is an insert of an extract from some other vector, include it.
8721 Value *VecOp = IEI->getOperand(0);
8722 Value *ScalarOp = IEI->getOperand(1);
8723 Value *IdxOp = IEI->getOperand(2);
8724
8725 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8726 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8727 EI->getOperand(0)->getType() == V->getType()) {
8728 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008729 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8730 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008731
8732 // Either the extracted from or inserted into vector must be RHSVec,
8733 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008734 if (EI->getOperand(0) == RHS || RHS == 0) {
8735 RHS = EI->getOperand(0);
8736 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008737 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008738 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008739 return V;
8740 }
8741
Chris Lattner90951862006-04-16 00:51:47 +00008742 if (VecOp == RHS) {
8743 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008744 // Everything but the extracted element is replaced with the RHS.
8745 for (unsigned i = 0; i != NumElts; ++i) {
8746 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008747 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008748 }
8749 return V;
8750 }
Chris Lattner90951862006-04-16 00:51:47 +00008751
8752 // If this insertelement is a chain that comes from exactly these two
8753 // vectors, return the vector and the effective shuffle.
8754 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8755 return EI->getOperand(0);
8756
Chris Lattner39fac442006-04-15 01:39:45 +00008757 }
8758 }
8759 }
Chris Lattner90951862006-04-16 00:51:47 +00008760 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008761
8762 // Otherwise, can't do anything fancy. Return an identity vector.
8763 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008764 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008765 return V;
8766}
8767
8768Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8769 Value *VecOp = IE.getOperand(0);
8770 Value *ScalarOp = IE.getOperand(1);
8771 Value *IdxOp = IE.getOperand(2);
8772
8773 // If the inserted element was extracted from some other vector, and if the
8774 // indexes are constant, try to turn this into a shufflevector operation.
8775 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8776 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8777 EI->getOperand(0)->getType() == IE.getType()) {
8778 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008779 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8780 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008781
8782 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8783 return ReplaceInstUsesWith(IE, VecOp);
8784
8785 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8786 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8787
8788 // If we are extracting a value from a vector, then inserting it right
8789 // back into the same place, just use the input vector.
8790 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8791 return ReplaceInstUsesWith(IE, VecOp);
8792
8793 // We could theoretically do this for ANY input. However, doing so could
8794 // turn chains of insertelement instructions into a chain of shufflevector
8795 // instructions, and right now we do not merge shufflevectors. As such,
8796 // only do this in a situation where it is clear that there is benefit.
8797 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8798 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8799 // the values of VecOp, except then one read from EIOp0.
8800 // Build a new shuffle mask.
8801 std::vector<Constant*> Mask;
8802 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008803 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008804 else {
8805 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008806 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008807 NumVectorElts));
8808 }
Reid Spencerc635f472006-12-31 05:48:39 +00008809 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008810 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8811 ConstantPacked::get(Mask));
8812 }
8813
8814 // If this insertelement isn't used by some other insertelement, turn it
8815 // (and any insertelements it points to), into one big shuffle.
8816 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8817 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008818 Value *RHS = 0;
8819 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8820 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8821 // We now have a shuffle of LHS, RHS, Mask.
8822 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008823 }
8824 }
8825 }
8826
8827 return 0;
8828}
8829
8830
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008831Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8832 Value *LHS = SVI.getOperand(0);
8833 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008834 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008835
8836 bool MadeChange = false;
8837
Chris Lattner2deeaea2006-10-05 06:55:50 +00008838 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008839 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008840 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8841
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008842 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008843 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008844 if (isa<UndefValue>(SVI.getOperand(1))) {
8845 // Scan to see if there are any references to the RHS. If so, replace them
8846 // with undef element refs and set MadeChange to true.
8847 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8848 if (Mask[i] >= e && Mask[i] != 2*e) {
8849 Mask[i] = 2*e;
8850 MadeChange = true;
8851 }
8852 }
8853
8854 if (MadeChange) {
8855 // Remap any references to RHS to use LHS.
8856 std::vector<Constant*> Elts;
8857 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8858 if (Mask[i] == 2*e)
8859 Elts.push_back(UndefValue::get(Type::Int32Ty));
8860 else
8861 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8862 }
8863 SVI.setOperand(2, ConstantPacked::get(Elts));
8864 }
8865 }
Chris Lattner39fac442006-04-15 01:39:45 +00008866
Chris Lattner12249be2006-05-25 23:48:38 +00008867 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8868 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8869 if (LHS == RHS || isa<UndefValue>(LHS)) {
8870 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008871 // shuffle(undef,undef,mask) -> undef.
8872 return ReplaceInstUsesWith(SVI, LHS);
8873 }
8874
Chris Lattner12249be2006-05-25 23:48:38 +00008875 // Remap any references to RHS to use LHS.
8876 std::vector<Constant*> Elts;
8877 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008878 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008879 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008880 else {
8881 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8882 (Mask[i] < e && isa<UndefValue>(LHS)))
8883 Mask[i] = 2*e; // Turn into undef.
8884 else
8885 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008886 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008887 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008888 }
Chris Lattner12249be2006-05-25 23:48:38 +00008889 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008890 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008891 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008892 LHS = SVI.getOperand(0);
8893 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008894 MadeChange = true;
8895 }
8896
Chris Lattner0e477162006-05-26 00:29:06 +00008897 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008898 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008899
Chris Lattner12249be2006-05-25 23:48:38 +00008900 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8901 if (Mask[i] >= e*2) continue; // Ignore undef values.
8902 // Is this an identity shuffle of the LHS value?
8903 isLHSID &= (Mask[i] == i);
8904
8905 // Is this an identity shuffle of the RHS value?
8906 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008907 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008908
Chris Lattner12249be2006-05-25 23:48:38 +00008909 // Eliminate identity shuffles.
8910 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8911 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008912
Chris Lattner0e477162006-05-26 00:29:06 +00008913 // If the LHS is a shufflevector itself, see if we can combine it with this
8914 // one without producing an unusual shuffle. Here we are really conservative:
8915 // we are absolutely afraid of producing a shuffle mask not in the input
8916 // program, because the code gen may not be smart enough to turn a merged
8917 // shuffle into two specific shuffles: it may produce worse code. As such,
8918 // we only merge two shuffles if the result is one of the two input shuffle
8919 // masks. In this case, merging the shuffles just removes one instruction,
8920 // which we know is safe. This is good for things like turning:
8921 // (splat(splat)) -> splat.
8922 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8923 if (isa<UndefValue>(RHS)) {
8924 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8925
8926 std::vector<unsigned> NewMask;
8927 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8928 if (Mask[i] >= 2*e)
8929 NewMask.push_back(2*e);
8930 else
8931 NewMask.push_back(LHSMask[Mask[i]]);
8932
8933 // If the result mask is equal to the src shuffle or this shuffle mask, do
8934 // the replacement.
8935 if (NewMask == LHSMask || NewMask == Mask) {
8936 std::vector<Constant*> Elts;
8937 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8938 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008939 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008940 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008941 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008942 }
8943 }
8944 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8945 LHSSVI->getOperand(1),
8946 ConstantPacked::get(Elts));
8947 }
8948 }
8949 }
8950
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008951 return MadeChange ? &SVI : 0;
8952}
8953
8954
Robert Bocchinoa8352962006-01-13 22:48:06 +00008955
Chris Lattner99f48c62002-09-02 04:59:56 +00008956void InstCombiner::removeFromWorkList(Instruction *I) {
8957 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8958 WorkList.end());
8959}
8960
Chris Lattner39c98bb2004-12-08 23:43:58 +00008961
8962/// TryToSinkInstruction - Try to move the specified instruction from its
8963/// current block into the beginning of DestBlock, which can only happen if it's
8964/// safe to move the instruction past all of the instructions between it and the
8965/// end of its block.
8966static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8967 assert(I->hasOneUse() && "Invariants didn't hold!");
8968
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008969 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8970 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008971
Chris Lattner39c98bb2004-12-08 23:43:58 +00008972 // Do not sink alloca instructions out of the entry block.
8973 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8974 return false;
8975
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008976 // We can only sink load instructions if there is nothing between the load and
8977 // the end of block that could change the value.
8978 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008979 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8980 Scan != E; ++Scan)
8981 if (Scan->mayWriteToMemory())
8982 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008983 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008984
8985 BasicBlock::iterator InsertPos = DestBlock->begin();
8986 while (isa<PHINode>(InsertPos)) ++InsertPos;
8987
Chris Lattner9f269e42005-08-08 19:11:57 +00008988 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008989 ++NumSunkInst;
8990 return true;
8991}
8992
Chris Lattner1443bc52006-05-11 17:11:52 +00008993/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008994/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008995/// if possible.
8996static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8997 if (!TD) return CE;
8998
8999 Constant *Ptr = CE->getOperand(0);
9000 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9001 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9002 // If this is a constant expr gep that is effectively computing an
9003 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9004 bool isFoldableGEP = true;
9005 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9006 if (!isa<ConstantInt>(CE->getOperand(i)))
9007 isFoldableGEP = false;
9008 if (isFoldableGEP) {
9009 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9010 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00009011 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009012 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009013 }
9014 }
9015
9016 return CE;
9017}
9018
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009019
9020/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9021/// all reachable code to the worklist.
9022///
9023/// This has a couple of tricks to make the code faster and more powerful. In
9024/// particular, we constant fold and DCE instructions as we go, to avoid adding
9025/// them to the worklist (this significantly speeds up instcombine on code where
9026/// many instructions are dead or constant). Additionally, if we find a branch
9027/// whose condition is a known constant, we only visit the reachable successors.
9028///
9029static void AddReachableCodeToWorklist(BasicBlock *BB,
9030 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009031 std::vector<Instruction*> &WorkList,
9032 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009033 // We have now visited this block! If we've already been here, bail out.
9034 if (!Visited.insert(BB).second) return;
9035
9036 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9037 Instruction *Inst = BBI++;
9038
9039 // DCE instruction if trivially dead.
9040 if (isInstructionTriviallyDead(Inst)) {
9041 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009042 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009043 Inst->eraseFromParent();
9044 continue;
9045 }
9046
9047 // ConstantProp instruction if trivially constant.
9048 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9050 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009051 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009052 Inst->replaceAllUsesWith(C);
9053 ++NumConstProp;
9054 Inst->eraseFromParent();
9055 continue;
9056 }
9057
9058 WorkList.push_back(Inst);
9059 }
9060
9061 // Recursively visit successors. If this is a branch or switch on a constant,
9062 // only visit the reachable successor.
9063 TerminatorInst *TI = BB->getTerminator();
9064 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009065 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009066 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009067 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9068 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009069 return;
9070 }
9071 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9072 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9073 // See if this is an explicit destination.
9074 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9075 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009076 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009077 return;
9078 }
9079
9080 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009081 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009082 return;
9083 }
9084 }
9085
9086 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009087 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009088}
9089
Chris Lattner113f4f42002-06-25 16:13:24 +00009090bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009091 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009092 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009093
Chris Lattner4ed40f72005-07-07 20:40:38 +00009094 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009095 // Do a depth-first traversal of the function, populate the worklist with
9096 // the reachable instructions. Ignore blocks that are not reachable. Keep
9097 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009098 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009099 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009100
Chris Lattner4ed40f72005-07-07 20:40:38 +00009101 // Do a quick scan over the function. If we find any blocks that are
9102 // unreachable, remove any instructions inside of them. This prevents
9103 // the instcombine code from having to deal with some bad special cases.
9104 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9105 if (!Visited.count(BB)) {
9106 Instruction *Term = BB->getTerminator();
9107 while (Term != BB->begin()) { // Remove instrs bottom-up
9108 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009109
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009110 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009111 ++NumDeadInst;
9112
9113 if (!I->use_empty())
9114 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9115 I->eraseFromParent();
9116 }
9117 }
9118 }
Chris Lattnerca081252001-12-14 16:52:21 +00009119
9120 while (!WorkList.empty()) {
9121 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9122 WorkList.pop_back();
9123
Chris Lattner1443bc52006-05-11 17:11:52 +00009124 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009125 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009126 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009127 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009128 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009129 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009130
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009131 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009132
9133 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009134 removeFromWorkList(I);
9135 continue;
9136 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009137
Chris Lattner1443bc52006-05-11 17:11:52 +00009138 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009139 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009140 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9141 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009142 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009143
Chris Lattner1443bc52006-05-11 17:11:52 +00009144 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009145 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009146 ReplaceInstUsesWith(*I, C);
9147
Chris Lattner99f48c62002-09-02 04:59:56 +00009148 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009149 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009150 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009151 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009152 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009153
Chris Lattner39c98bb2004-12-08 23:43:58 +00009154 // See if we can trivially sink this instruction to a successor basic block.
9155 if (I->hasOneUse()) {
9156 BasicBlock *BB = I->getParent();
9157 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9158 if (UserParent != BB) {
9159 bool UserIsSuccessor = false;
9160 // See if the user is one of our successors.
9161 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9162 if (*SI == UserParent) {
9163 UserIsSuccessor = true;
9164 break;
9165 }
9166
9167 // If the user is one of our immediate successors, and if that successor
9168 // only has us as a predecessors (we'd have to split the critical edge
9169 // otherwise), we can keep going.
9170 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9171 next(pred_begin(UserParent)) == pred_end(UserParent))
9172 // Okay, the CFG is simple enough, try to sink this instruction.
9173 Changed |= TryToSinkInstruction(I, UserParent);
9174 }
9175 }
9176
Chris Lattnerca081252001-12-14 16:52:21 +00009177 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009178 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009179 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009180 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009181 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009182 DOUT << "IC: Old = " << *I
9183 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009184
Chris Lattner396dbfe2004-06-09 05:08:07 +00009185 // Everything uses the new instruction now.
9186 I->replaceAllUsesWith(Result);
9187
9188 // Push the new instruction and any users onto the worklist.
9189 WorkList.push_back(Result);
9190 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009191
9192 // Move the name to the new instruction first...
9193 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009194 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009195
9196 // Insert the new instruction into the basic block...
9197 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009198 BasicBlock::iterator InsertPos = I;
9199
9200 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9201 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9202 ++InsertPos;
9203
9204 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009205
Chris Lattner63d75af2004-05-01 23:27:23 +00009206 // Make sure that we reprocess all operands now that we reduced their
9207 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009208 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9209 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9210 WorkList.push_back(OpI);
9211
Chris Lattner396dbfe2004-06-09 05:08:07 +00009212 // Instructions can end up on the worklist more than once. Make sure
9213 // we do not process an instruction that has been deleted.
9214 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009215
9216 // Erase the old instruction.
9217 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009218 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009219 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009220
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009221 // If the instruction was modified, it's possible that it is now dead.
9222 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009223 if (isInstructionTriviallyDead(I)) {
9224 // Make sure we process all operands now that we are reducing their
9225 // use counts.
9226 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9227 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9228 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009229
Chris Lattner63d75af2004-05-01 23:27:23 +00009230 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009231 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009232 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009233 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009234 } else {
9235 WorkList.push_back(Result);
9236 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009237 }
Chris Lattner053c0932002-05-14 15:24:07 +00009238 }
Chris Lattner260ab202002-04-18 17:39:14 +00009239 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009240 }
9241 }
9242
Chris Lattner260ab202002-04-18 17:39:14 +00009243 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009244}
9245
Brian Gaeke38b79e82004-07-27 17:43:21 +00009246FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009247 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009248}
Brian Gaeke960707c2003-11-11 22:41:34 +00009249