blob: 04b06d28aa71ef725f820ab492d4d28685d3a61d [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattner79a42ac2006-12-19 21:40:18 +000064namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000109
Chris Lattner99f48c62002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000112 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000114
Chris Lattnerf12cc842002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000119 }
120
Chris Lattner69193f92004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattner260ab202002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000129 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000146 Instruction *visitFCmpInst(FCmpInst &I);
147 Instruction *visitICmpInst(ICmpInst &I);
148 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000149
Reid Spencer266e42b2006-12-23 06:05:41 +0000150 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000155 Instruction *commonCastTransforms(CastInst &CI);
156 Instruction *commonIntCastTransforms(CastInst &CI);
157 Instruction *visitTrunc(CastInst &CI);
158 Instruction *visitZExt(CastInst &CI);
159 Instruction *visitSExt(CastInst &CI);
160 Instruction *visitFPTrunc(CastInst &CI);
161 Instruction *visitFPExt(CastInst &CI);
162 Instruction *visitFPToUI(CastInst &CI);
163 Instruction *visitFPToSI(CastInst &CI);
164 Instruction *visitUIToFP(CastInst &CI);
165 Instruction *visitSIToFP(CastInst &CI);
166 Instruction *visitPtrToInt(CastInst &CI);
167 Instruction *visitIntToPtr(CastInst &CI);
168 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000169 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000171 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 Instruction *visitCallInst(CallInst &CI);
173 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitPHINode(PHINode &PN);
175 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000176 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000177 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000178 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000179 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000180 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000181 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000182 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000183 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000184 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000185
186 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000187 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000188
Chris Lattner970c33a2003-06-19 17:00:31 +0000189 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000190 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000191 bool transformConstExprCastCall(CallSite CS);
192
Chris Lattner69193f92004-04-05 01:30:19 +0000193 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 // InsertNewInstBefore - insert an instruction New before instruction Old
195 // in the program. Add the new instruction to the worklist.
196 //
Chris Lattner623826c2004-09-28 21:48:02 +0000197 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000198 assert(New && New->getParent() == 0 &&
199 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000200 BasicBlock *BB = Old.getParent();
201 BB->getInstList().insert(&Old, New); // Insert inst
202 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000203 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000204 }
205
Chris Lattner7e794272004-09-24 15:21:34 +0000206 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207 /// This also adds the cast to the worklist. Finally, this returns the
208 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000209 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000211 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212
Chris Lattnere79d2492006-04-06 19:19:17 +0000213 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000214 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000215
Reid Spencer13bc5d72006-12-12 09:18:51 +0000216 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000217 WorkList.push_back(C);
218 return C;
219 }
220
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000221 // ReplaceInstUsesWith - This method is to be used when an instruction is
222 // found to be dead, replacable with another preexisting expression. Here
223 // we add all uses of I to the worklist, replace all uses of I with the new
224 // value, then return I, so that the inst combiner will know that I was
225 // modified.
226 //
227 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000228 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000229 if (&I != V) {
230 I.replaceAllUsesWith(V);
231 return &I;
232 } else {
233 // If we are replacing the instruction with itself, this must be in a
234 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000235 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000236 return &I;
237 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000238 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000239
Chris Lattner2590e512006-02-07 06:56:34 +0000240 // UpdateValueUsesWith - This method is to be used when an value is
241 // found to be replacable with another preexisting expression or was
242 // updated. Here we add all uses of I to the worklist, replace all uses of
243 // I with the new value (unless the instruction was just updated), then
244 // return true, so that the inst combiner will know that I was modified.
245 //
246 bool UpdateValueUsesWith(Value *Old, Value *New) {
247 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
248 if (Old != New)
249 Old->replaceAllUsesWith(New);
250 if (Instruction *I = dyn_cast<Instruction>(Old))
251 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000252 if (Instruction *I = dyn_cast<Instruction>(New))
253 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000254 return true;
255 }
256
Chris Lattner51ea1272004-02-28 05:22:00 +0000257 // EraseInstFromFunction - When dealing with an instruction that has side
258 // effects or produces a void value, we can't rely on DCE to delete the
259 // instruction. Instead, visit methods should return the value returned by
260 // this function.
261 Instruction *EraseInstFromFunction(Instruction &I) {
262 assert(I.use_empty() && "Cannot erase instruction that is used!");
263 AddUsesToWorkList(I);
264 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000265 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000266 return 0; // Don't do anything with FI
267 }
268
Chris Lattner3ac7c262003-08-13 20:16:26 +0000269 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000270 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271 /// InsertBefore instruction. This is specialized a bit to avoid inserting
272 /// casts that are known to not do anything...
273 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000274 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000276 Instruction *InsertBefore);
277
Reid Spencer266e42b2006-12-23 06:05:41 +0000278 /// SimplifyCommutative - This performs a few simplifications for
279 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000281
Reid Spencer266e42b2006-12-23 06:05:41 +0000282 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283 /// most-complex to least-complex order.
284 bool SimplifyCompare(CmpInst &I);
285
Chris Lattner0157e7f2006-02-11 09:31:47 +0000286 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
287 uint64_t &KnownZero, uint64_t &KnownOne,
288 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000289
Chris Lattner2deeaea2006-10-05 06:55:50 +0000290 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291 uint64_t &UndefElts, unsigned Depth = 0);
292
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000293 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294 // PHI node as operand #0, see if we can fold the instruction into the PHI
295 // (which is only possible if all operands to the PHI are constants).
296 Instruction *FoldOpIntoPhi(Instruction &I);
297
Chris Lattner7515cab2004-11-14 19:13:23 +0000298 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299 // operator and they all are only used by the PHI, PHI together their
300 // inputs, and do the operation once, to the result of the PHI.
301 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000302 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303
304
Zhou Sheng75b871f2007-01-11 12:24:14 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
306 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000307
Zhou Sheng75b871f2007-01-11 12:24:14 +0000308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000309 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000311 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000313 Instruction *MatchBSwap(BinaryOperator &I);
314
Reid Spencer74a528b2006-12-13 18:21:21 +0000315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000316 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000317
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000319}
320
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000322// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000326 return 3;
327 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000331}
Chris Lattner260ab202002-04-18 17:39:14 +0000332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// isOnlyUse - Return true if this instruction will be deleted if we stop using
334// it.
335static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000336 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337}
338
Chris Lattnere79e8542004-02-23 06:38:22 +0000339// getPromotedType - Return the specified type promoted as it would be to pass
340// though a va_arg area...
341static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000342 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
343 if (ITy->getBitWidth() < 32)
344 return Type::Int32Ty;
345 } else if (Ty == Type::FloatTy)
346 return Type::DoubleTy;
347 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000348}
349
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000350/// getBitCastOperand - If the specified operand is a CastInst or a constant
351/// expression bitcast, return the operand value, otherwise return null.
352static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000357 return CE->getOperand(0);
358 return 0;
359}
360
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000361/// This function is a wrapper around CastInst::isEliminableCastPair. It
362/// simply extracts arguments and returns what that function returns.
363/// @Determine if it is valid to eliminate a Convert pair
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000374
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000378
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000382}
383
384/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385/// in any code being generated. It does not require codegen if V is simple
386/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000387static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 if (V->getType() == Ty || isa<Constant>(V)) return false;
390
Chris Lattner99155be2006-05-25 23:24:33 +0000391 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000392 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000393 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000394 return false;
395 return true;
396}
397
398/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399/// InsertBefore instruction. This is specialized a bit to avoid inserting
400/// casts that are known to not do anything...
401///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000402Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000404 Instruction *InsertBefore) {
405 if (V->getType() == DestTy) return V;
406 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000407 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408
Reid Spencer13bc5d72006-12-12 09:18:51 +0000409 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410}
411
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000412// SimplifyCommutative - This performs a few simplifications for commutative
413// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000414//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000415// 1. Order operands such that they are listed from right (least complex) to
416// left (most complex). This puts constants before unary operators before
417// binary operators.
418//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000419// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000422bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000423 bool Changed = false;
424 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000426
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427 if (!I.isAssociative()) return Changed;
428 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000429 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000432 Constant *Folded = ConstantExpr::get(I.getOpcode(),
433 cast<Constant>(I.getOperand(1)),
434 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 I.setOperand(0, Op->getOperand(0));
436 I.setOperand(1, Folded);
437 return true;
438 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440 isOnlyUse(Op) && isOnlyUse(Op1)) {
441 Constant *C1 = cast<Constant>(Op->getOperand(1));
442 Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000445 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000446 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447 Op1->getOperand(0),
448 Op1->getName(), &I);
449 WorkList.push_back(New);
450 I.setOperand(0, New);
451 I.setOperand(1, Folded);
452 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000456}
Chris Lattnerca081252001-12-14 16:52:21 +0000457
Reid Spencer266e42b2006-12-23 06:05:41 +0000458/// SimplifyCompare - For a CmpInst this function just orders the operands
459/// so that theyare listed from right (least complex) to left (most complex).
460/// This puts constants before unary operators before binary operators.
461bool InstCombiner::SimplifyCompare(CmpInst &I) {
462 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463 return false;
464 I.swapOperands();
465 // Compare instructions are not associative so there's nothing else we can do.
466 return true;
467}
468
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000471//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472static inline Value *dyn_castNegVal(Value *V) {
473 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000474 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475
Chris Lattner9ad0d552004-12-14 20:08:06 +0000476 // Constants can be considered to be negated values if they can be folded.
477 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000480}
481
Chris Lattnerbb74e222003-03-10 23:06:50 +0000482static inline Value *dyn_castNotVal(Value *V) {
483 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000484 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485
486 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000487 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000488 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489 return 0;
490}
491
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492// dyn_castFoldableMul - If this value is a multiply that can be folded into
493// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000494// non-constant operand of the multiply, and set CST to point to the multiplier.
495// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000497static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000498 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000499 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000500 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000501 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000504 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 // The multiplier is really 1 << CST.
506 Constant *One = ConstantInt::get(V->getType(), 1);
507 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508 return I->getOperand(0);
509 }
510 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000511 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000512}
Chris Lattner31ae8632002-08-14 17:51:49 +0000513
Chris Lattner0798af32005-01-13 20:14:25 +0000514/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515/// expression, return it.
516static User *dyn_castGetElementPtr(Value *V) {
517 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519 if (CE->getOpcode() == Instruction::GetElementPtr)
520 return cast<User>(V);
521 return false;
522}
523
Chris Lattner623826c2004-09-28 21:48:02 +0000524// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000525static ConstantInt *AddOne(ConstantInt *C) {
526 return cast<ConstantInt>(ConstantExpr::getAdd(C,
527 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000528}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000529static ConstantInt *SubOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getSub(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000532}
533
Chris Lattner4534dd592006-02-09 07:38:58 +0000534/// ComputeMaskedBits - Determine which of the bits specified in Mask are
535/// known to be either zero or one and return them in the KnownZero/KnownOne
536/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
537/// processing.
538static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000540 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
541 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000542 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000543 // optimized based on the contradictory assumption that it is non-zero.
544 // Because instcombine aggressively folds operations with undef args anyway,
545 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000546 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000547 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000548 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000549 KnownZero = ~KnownOne & Mask;
550 return;
551 }
552
553 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000554 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000555 return; // Limit search depth.
556
557 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000558 Instruction *I = dyn_cast<Instruction>(V);
559 if (!I) return;
560
Reid Spencera94d3942007-01-19 21:13:56 +0000561 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000562
Chris Lattner0157e7f2006-02-11 09:31:47 +0000563 switch (I->getOpcode()) {
564 case Instruction::And:
565 // If either the LHS or the RHS are Zero, the result is zero.
566 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
567 Mask &= ~KnownZero;
568 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
570 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
571
572 // Output known-1 bits are only known if set in both the LHS & RHS.
573 KnownOne &= KnownOne2;
574 // Output known-0 are known to be clear if zero in either the LHS | RHS.
575 KnownZero |= KnownZero2;
576 return;
577 case Instruction::Or:
578 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
579 Mask &= ~KnownOne;
580 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
582 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
583
584 // Output known-0 bits are only known if clear in both the LHS & RHS.
585 KnownZero &= KnownZero2;
586 // Output known-1 are known to be set if set in either the LHS | RHS.
587 KnownOne |= KnownOne2;
588 return;
589 case Instruction::Xor: {
590 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
593 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
594
595 // Output known-0 bits are known if clear or set in both the LHS & RHS.
596 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597 // Output known-1 are known to be set if set in only one of the LHS, RHS.
598 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599 KnownZero = KnownZeroOut;
600 return;
601 }
602 case Instruction::Select:
603 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607
608 // Only known if known in both the LHS and RHS.
609 KnownOne &= KnownOne2;
610 KnownZero &= KnownZero2;
611 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000612 case Instruction::FPTrunc:
613 case Instruction::FPExt:
614 case Instruction::FPToUI:
615 case Instruction::FPToSI:
616 case Instruction::SIToFP:
617 case Instruction::PtrToInt:
618 case Instruction::UIToFP:
619 case Instruction::IntToPtr:
620 return; // Can't work with floating point or pointers
621 case Instruction::Trunc:
622 // All these have integer operands
623 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
624 return;
625 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000626 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000627 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000629 return;
630 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631 break;
632 }
633 case Instruction::ZExt: {
634 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000635 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
636 uint64_t NotIn = ~SrcTy->getBitMask();
637 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000638
Reid Spencera94d3942007-01-19 21:13:56 +0000639 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 // The top bits are known to be zero.
643 KnownZero |= NewBits;
644 return;
645 }
646 case Instruction::SExt: {
647 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000648 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
649 uint64_t NotIn = ~SrcTy->getBitMask();
650 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000651
Reid Spencera94d3942007-01-19 21:13:56 +0000652 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000655
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000656 // If the sign bit of the input is known set or clear, then we know the
657 // top bits of the result.
658 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659 if (KnownZero & InSignBit) { // Input sign bit known zero
660 KnownZero |= NewBits;
661 KnownOne &= ~NewBits;
662 } else if (KnownOne & InSignBit) { // Input sign bit known set
663 KnownOne |= NewBits;
664 KnownZero &= ~NewBits;
665 } else { // Input sign bit unknown
666 KnownZero &= ~NewBits;
667 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000668 }
669 return;
670 }
671 case Instruction::Shl:
672 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000673 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674 uint64_t ShiftAmt = SA->getZExtValue();
675 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000676 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000678 KnownZero <<= ShiftAmt;
679 KnownOne <<= ShiftAmt;
680 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 return;
682 }
683 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000684 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000685 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000688 uint64_t ShiftAmt = SA->getZExtValue();
689 uint64_t HighBits = (1ULL << ShiftAmt)-1;
690 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000691
Reid Spencerfdff9382006-11-08 06:47:33 +0000692 // Unsigned shift right.
693 Mask <<= ShiftAmt;
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
696 KnownZero >>= ShiftAmt;
697 KnownOne >>= ShiftAmt;
698 KnownZero |= HighBits; // high bits known zero.
699 return;
700 }
701 break;
702 case Instruction::AShr:
703 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
704 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705 // Compute the new bits that are at the top now.
706 uint64_t ShiftAmt = SA->getZExtValue();
707 uint64_t HighBits = (1ULL << ShiftAmt)-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
709
710 // Signed shift right.
711 Mask <<= ShiftAmt;
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= ShiftAmt;
715 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000716
Reid Spencerfdff9382006-11-08 06:47:33 +0000717 // Handle the sign bits.
718 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720
Reid Spencerfdff9382006-11-08 06:47:33 +0000721 if (KnownZero & SignBit) { // New bits are known zero.
722 KnownZero |= HighBits;
723 } else if (KnownOne & SignBit) { // New bits are known one.
724 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000725 }
726 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000727 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000728 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000729 }
Chris Lattner92a68652006-02-07 08:05:22 +0000730}
731
732/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
733/// this predicate to simplify operations downstream. Mask is known to be zero
734/// for bits that V cannot have.
735static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000736 uint64_t KnownZero, KnownOne;
737 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
739 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000740}
741
Chris Lattner0157e7f2006-02-11 09:31:47 +0000742/// ShrinkDemandedConstant - Check to see if the specified operand of the
743/// specified instruction is a constant integer. If so, check to see if there
744/// are any bits set in the constant that are not demanded. If so, shrink the
745/// constant and return true.
746static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
747 uint64_t Demanded) {
748 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749 if (!OpC) return false;
750
751 // If there are no bits set that aren't demanded, nothing to do.
752 if ((~Demanded & OpC->getZExtValue()) == 0)
753 return false;
754
755 // This is producing any bits that are not needed, shrink the RHS.
756 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000757 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000758 return true;
759}
760
Chris Lattneree0f2802006-02-12 02:07:56 +0000761// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
762// set of known zero and one bits, compute the maximum and minimum values that
763// could have the specified known zero and known one bits, returning them in
764// min/max.
765static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
766 uint64_t KnownZero,
767 uint64_t KnownOne,
768 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000769 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000770 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
771
772 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
773
774 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775 // bit if it is unknown.
776 Min = KnownOne;
777 Max = KnownOne|UnknownBits;
778
779 if (SignBit & UnknownBits) { // Sign bit is unknown
780 Min |= SignBit;
781 Max &= ~SignBit;
782 }
783
784 // Sign extend the min/max values.
785 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786 Min = (Min << ShAmt) >> ShAmt;
787 Max = (Max << ShAmt) >> ShAmt;
788}
789
790// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791// a set of known zero and one bits, compute the maximum and minimum values that
792// could have the specified known zero and known one bits, returning them in
793// min/max.
794static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
795 uint64_t KnownZero,
796 uint64_t KnownOne,
797 uint64_t &Min,
798 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000799 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000800 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801
802 // The minimum value is when the unknown bits are all zeros.
803 Min = KnownOne;
804 // The maximum value is when the unknown bits are all ones.
805 Max = KnownOne|UnknownBits;
806}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000807
808
809/// SimplifyDemandedBits - Look at V. At this point, we know that only the
810/// DemandedMask bits of the result of V are ever used downstream. If we can
811/// use this information to simplify V, do so and return true. Otherwise,
812/// analyze the expression and return a mask of KnownOne and KnownZero bits for
813/// the expression (used to simplify the caller). The KnownZero/One bits may
814/// only be accurate for those bits in the DemandedMask.
815bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000817 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000818 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000819 // We know all of the bits for a constant!
820 KnownOne = CI->getZExtValue() & DemandedMask;
821 KnownZero = ~KnownOne & DemandedMask;
822 return false;
823 }
824
825 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000826 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000827 if (Depth != 0) { // Not at the root.
828 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000830 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 }
Chris Lattner2590e512006-02-07 06:56:34 +0000832 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000833 // just set the DemandedMask to all bits.
Reid Spencera94d3942007-01-19 21:13:56 +0000834 DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000836 if (V != UndefValue::get(V->getType()))
837 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
838 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000839 } else if (Depth == 6) { // Limit search depth.
840 return false;
841 }
842
843 Instruction *I = dyn_cast<Instruction>(V);
844 if (!I) return false; // Only analyze instructions.
845
Reid Spencera94d3942007-01-19 21:13:56 +0000846 DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000847
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000848 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000849 switch (I->getOpcode()) {
850 default: break;
851 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000852 // If either the LHS or the RHS are Zero, the result is zero.
853 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854 KnownZero, KnownOne, Depth+1))
855 return true;
856 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
857
858 // If something is known zero on the RHS, the bits aren't demanded on the
859 // LHS.
860 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861 KnownZero2, KnownOne2, Depth+1))
862 return true;
863 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
864
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000865 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000866 // These bits cannot contribute to the result of the 'and'.
867 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000871
872 // If all of the demanded bits in the inputs are known zeros, return zero.
873 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
875
Chris Lattner0157e7f2006-02-11 09:31:47 +0000876 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000877 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000878 return UpdateValueUsesWith(I, I);
879
880 // Output known-1 bits are only known if set in both the LHS & RHS.
881 KnownOne &= KnownOne2;
882 // Output known-0 are known to be clear if zero in either the LHS | RHS.
883 KnownZero |= KnownZero2;
884 break;
885 case Instruction::Or:
886 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
887 KnownZero, KnownOne, Depth+1))
888 return true;
889 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
890 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
891 KnownZero2, KnownOne2, Depth+1))
892 return true;
893 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
894
895 // If all of the demanded bits are known zero on one side, return the other.
896 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000897 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000899 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000900 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000901
902 // If all of the potentially set bits on one side are known to be set on
903 // the other side, just use the 'other' side.
904 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
905 (DemandedMask & (~KnownZero)))
906 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000907 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
908 (DemandedMask & (~KnownZero2)))
909 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000910
911 // If the RHS is a constant, see if we can simplify it.
912 if (ShrinkDemandedConstant(I, 1, DemandedMask))
913 return UpdateValueUsesWith(I, I);
914
915 // Output known-0 bits are only known if clear in both the LHS & RHS.
916 KnownZero &= KnownZero2;
917 // Output known-1 are known to be set if set in either the LHS | RHS.
918 KnownOne |= KnownOne2;
919 break;
920 case Instruction::Xor: {
921 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922 KnownZero, KnownOne, Depth+1))
923 return true;
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
926 KnownZero2, KnownOne2, Depth+1))
927 return true;
928 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
929
930 // If all of the demanded bits are known zero on one side, return the other.
931 // These bits cannot contribute to the result of the 'xor'.
932 if ((DemandedMask & KnownZero) == DemandedMask)
933 return UpdateValueUsesWith(I, I->getOperand(0));
934 if ((DemandedMask & KnownZero2) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(1));
936
937 // Output known-0 bits are known if clear or set in both the LHS & RHS.
938 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939 // Output known-1 are known to be set if set in only one of the LHS, RHS.
940 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
941
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000942 // If all of the demanded bits are known to be zero on one side or the
943 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000944 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000945 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
946 Instruction *Or =
947 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
948 I->getName());
949 InsertNewInstBefore(Or, *I);
950 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000951 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000952
Chris Lattner5b2edb12006-02-12 08:02:11 +0000953 // If all of the demanded bits on one side are known, and all of the set
954 // bits on that side are also known to be set on the other side, turn this
955 // into an AND, as we know the bits will be cleared.
956 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000959 Constant *AndC = ConstantInt::get(I->getType(),
960 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000961 Instruction *And =
962 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963 InsertNewInstBefore(And, *I);
964 return UpdateValueUsesWith(I, And);
965 }
966 }
967
Chris Lattner0157e7f2006-02-11 09:31:47 +0000968 // If the RHS is a constant, see if we can simplify it.
969 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
971 return UpdateValueUsesWith(I, I);
972
973 KnownZero = KnownZeroOut;
974 KnownOne = KnownOneOut;
975 break;
976 }
977 case Instruction::Select:
978 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979 KnownZero, KnownOne, Depth+1))
980 return true;
981 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
982 KnownZero2, KnownOne2, Depth+1))
983 return true;
984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
985 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
986
987 // If the operands are constants, see if we can simplify them.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
989 return UpdateValueUsesWith(I, I);
990 if (ShrinkDemandedConstant(I, 2, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992
993 // Only known if known in both the LHS and RHS.
994 KnownOne &= KnownOne2;
995 KnownZero &= KnownZero2;
996 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000997 case Instruction::Trunc:
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 KnownZero, KnownOne, Depth+1))
1000 return true;
1001 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1002 break;
1003 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001004 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001005 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001006
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 KnownZero, KnownOne, Depth+1))
1009 return true;
1010 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1011 break;
1012 case Instruction::ZExt: {
1013 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001014 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1015 uint64_t NotIn = ~SrcTy->getBitMask();
1016 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001017
Reid Spencera94d3942007-01-19 21:13:56 +00001018 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 // The top bits are known to be zero.
1024 KnownZero |= NewBits;
1025 break;
1026 }
1027 case Instruction::SExt: {
1028 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001029 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1030 uint64_t NotIn = ~SrcTy->getBitMask();
1031 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001032
1033 // Get the sign bit for the source type
1034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001035 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
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;
Reid Spencera94d3942007-01-19 21:13:56 +00001177 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001178 // Unsigned shift right.
1179 if (SimplifyDemandedBits(I->getOperand(0),
1180 (DemandedMask << ShiftAmt) & TypeMask,
1181 KnownZero, KnownOne, Depth+1))
1182 return true;
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1184 KnownZero &= TypeMask;
1185 KnownOne &= TypeMask;
1186 KnownZero >>= ShiftAmt;
1187 KnownOne >>= ShiftAmt;
1188 KnownZero |= HighBits; // high bits known zero.
1189 }
1190 break;
1191 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001192 // If this is an arithmetic shift right and only the low-bit is set, we can
1193 // always convert this into a logical shr, even if the shift amount is
1194 // variable. The low bit of the shift cannot be an input sign bit unless
1195 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001196 if (DemandedMask == 1) {
1197 // Perform the logical shift right.
1198 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1199 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001200 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001201 return UpdateValueUsesWith(I, NewVal);
1202 }
1203
Reid Spencere0fc4df2006-10-20 07:07:24 +00001204 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001206
1207 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001208 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001210 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001211 // Signed shift right.
1212 if (SimplifyDemandedBits(I->getOperand(0),
1213 (DemandedMask << ShiftAmt) & TypeMask,
1214 KnownZero, KnownOne, Depth+1))
1215 return true;
1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1217 KnownZero &= TypeMask;
1218 KnownOne &= TypeMask;
1219 KnownZero >>= ShiftAmt;
1220 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001221
Reid Spencerfdff9382006-11-08 06:47:33 +00001222 // Handle the sign bits.
1223 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001225
Reid Spencerfdff9382006-11-08 06:47:33 +00001226 // If the input sign bit is known to be zero, or if none of the top bits
1227 // are demanded, turn this into an unsigned shift right.
1228 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229 // Perform the logical shift right.
1230 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1231 SA, I->getName());
1232 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233 return UpdateValueUsesWith(I, NewVal);
1234 } else if (KnownOne & SignBit) { // New bits are known one.
1235 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001236 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001237 }
Chris Lattner2590e512006-02-07 06:56:34 +00001238 break;
1239 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001240
1241 // If the client is only demanding bits that we know, return the known
1242 // constant.
1243 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001244 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001245 return false;
1246}
1247
Chris Lattner2deeaea2006-10-05 06:55:50 +00001248
1249/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250/// 64 or fewer elements. DemandedElts contains the set of elements that are
1251/// actually used by the caller. This method analyzes which elements of the
1252/// operand are undef and returns that information in UndefElts.
1253///
1254/// If the information about demanded elements can be used to simplify the
1255/// operation, the operation is simplified, then the resultant value is
1256/// returned. This returns null if no change was made.
1257Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258 uint64_t &UndefElts,
1259 unsigned Depth) {
1260 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261 assert(VWidth <= 64 && "Vector too wide to analyze!");
1262 uint64_t EltMask = ~0ULL >> (64-VWidth);
1263 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264 "Invalid DemandedElts!");
1265
1266 if (isa<UndefValue>(V)) {
1267 // If the entire vector is undefined, just return this info.
1268 UndefElts = EltMask;
1269 return 0;
1270 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271 UndefElts = EltMask;
1272 return UndefValue::get(V->getType());
1273 }
1274
1275 UndefElts = 0;
1276 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278 Constant *Undef = UndefValue::get(EltTy);
1279
1280 std::vector<Constant*> Elts;
1281 for (unsigned i = 0; i != VWidth; ++i)
1282 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1283 Elts.push_back(Undef);
1284 UndefElts |= (1ULL << i);
1285 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1286 Elts.push_back(Undef);
1287 UndefElts |= (1ULL << i);
1288 } else { // Otherwise, defined.
1289 Elts.push_back(CP->getOperand(i));
1290 }
1291
1292 // If we changed the constant, return it.
1293 Constant *NewCP = ConstantPacked::get(Elts);
1294 return NewCP != CP ? NewCP : 0;
1295 } else if (isa<ConstantAggregateZero>(V)) {
1296 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1297 // set to undef.
1298 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299 Constant *Zero = Constant::getNullValue(EltTy);
1300 Constant *Undef = UndefValue::get(EltTy);
1301 std::vector<Constant*> Elts;
1302 for (unsigned i = 0; i != VWidth; ++i)
1303 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304 UndefElts = DemandedElts ^ EltMask;
1305 return ConstantPacked::get(Elts);
1306 }
1307
1308 if (!V->hasOneUse()) { // Other users may use these bits.
1309 if (Depth != 0) { // Not at the root.
1310 // TODO: Just compute the UndefElts information recursively.
1311 return false;
1312 }
1313 return false;
1314 } else if (Depth == 10) { // Limit search depth.
1315 return false;
1316 }
1317
1318 Instruction *I = dyn_cast<Instruction>(V);
1319 if (!I) return false; // Only analyze instructions.
1320
1321 bool MadeChange = false;
1322 uint64_t UndefElts2;
1323 Value *TmpV;
1324 switch (I->getOpcode()) {
1325 default: break;
1326
1327 case Instruction::InsertElement: {
1328 // If this is a variable index, we don't know which element it overwrites.
1329 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001330 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001331 if (Idx == 0) {
1332 // Note that we can't propagate undef elt info, because we don't know
1333 // which elt is getting updated.
1334 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335 UndefElts2, Depth+1);
1336 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1337 break;
1338 }
1339
1340 // If this is inserting an element that isn't demanded, remove this
1341 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001342 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001343 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344 return AddSoonDeadInstToWorklist(*I, 0);
1345
1346 // Otherwise, the element inserted overwrites whatever was there, so the
1347 // input demanded set is simpler than the output set.
1348 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349 DemandedElts & ~(1ULL << IdxNo),
1350 UndefElts, Depth+1);
1351 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1352
1353 // The inserted element is defined.
1354 UndefElts |= 1ULL << IdxNo;
1355 break;
1356 }
1357
1358 case Instruction::And:
1359 case Instruction::Or:
1360 case Instruction::Xor:
1361 case Instruction::Add:
1362 case Instruction::Sub:
1363 case Instruction::Mul:
1364 // div/rem demand all inputs, because they don't want divide by zero.
1365 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366 UndefElts, Depth+1);
1367 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369 UndefElts2, Depth+1);
1370 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1371
1372 // Output elements are undefined if both are undefined. Consider things
1373 // like undef&0. The result is known zero, not undef.
1374 UndefElts &= UndefElts2;
1375 break;
1376
1377 case Instruction::Call: {
1378 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1379 if (!II) break;
1380 switch (II->getIntrinsicID()) {
1381 default: break;
1382
1383 // Binary vector operations that work column-wise. A dest element is a
1384 // function of the corresponding input elements from the two inputs.
1385 case Intrinsic::x86_sse_sub_ss:
1386 case Intrinsic::x86_sse_mul_ss:
1387 case Intrinsic::x86_sse_min_ss:
1388 case Intrinsic::x86_sse_max_ss:
1389 case Intrinsic::x86_sse2_sub_sd:
1390 case Intrinsic::x86_sse2_mul_sd:
1391 case Intrinsic::x86_sse2_min_sd:
1392 case Intrinsic::x86_sse2_max_sd:
1393 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394 UndefElts, Depth+1);
1395 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397 UndefElts2, Depth+1);
1398 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1399
1400 // If only the low elt is demanded and this is a scalarizable intrinsic,
1401 // scalarize it now.
1402 if (DemandedElts == 1) {
1403 switch (II->getIntrinsicID()) {
1404 default: break;
1405 case Intrinsic::x86_sse_sub_ss:
1406 case Intrinsic::x86_sse_mul_ss:
1407 case Intrinsic::x86_sse2_sub_sd:
1408 case Intrinsic::x86_sse2_mul_sd:
1409 // TODO: Lower MIN/MAX/ABS/etc
1410 Value *LHS = II->getOperand(1);
1411 Value *RHS = II->getOperand(2);
1412 // Extract the element as scalars.
1413 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1415
1416 switch (II->getIntrinsicID()) {
1417 default: assert(0 && "Case stmts out of sync!");
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse2_sub_sd:
1420 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421 II->getName()), *II);
1422 break;
1423 case Intrinsic::x86_sse_mul_ss:
1424 case Intrinsic::x86_sse2_mul_sd:
1425 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426 II->getName()), *II);
1427 break;
1428 }
1429
1430 Instruction *New =
1431 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1432 II->getName());
1433 InsertNewInstBefore(New, *II);
1434 AddSoonDeadInstToWorklist(*II, 0);
1435 return New;
1436 }
1437 }
1438
1439 // Output elements are undefined if both are undefined. Consider things
1440 // like undef&0. The result is known zero, not undef.
1441 UndefElts &= UndefElts2;
1442 break;
1443 }
1444 break;
1445 }
1446 }
1447 return MadeChange ? I : 0;
1448}
1449
Reid Spencer266e42b2006-12-23 06:05:41 +00001450/// @returns true if the specified compare instruction is
1451/// true when both operands are equal...
1452/// @brief Determine if the ICmpInst returns true if both operands are equal
1453static bool isTrueWhenEqual(ICmpInst &ICI) {
1454 ICmpInst::Predicate pred = ICI.getPredicate();
1455 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1456 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1457 pred == ICmpInst::ICMP_SLE;
1458}
1459
Chris Lattnerb8b97502003-08-13 19:01:45 +00001460/// AssociativeOpt - Perform an optimization on an associative operator. This
1461/// function is designed to check a chain of associative operators for a
1462/// potential to apply a certain optimization. Since the optimization may be
1463/// applicable if the expression was reassociated, this checks the chain, then
1464/// reassociates the expression as necessary to expose the optimization
1465/// opportunity. This makes use of a special Functor, which must define
1466/// 'shouldApply' and 'apply' methods.
1467///
1468template<typename Functor>
1469Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1470 unsigned Opcode = Root.getOpcode();
1471 Value *LHS = Root.getOperand(0);
1472
1473 // Quick check, see if the immediate LHS matches...
1474 if (F.shouldApply(LHS))
1475 return F.apply(Root);
1476
1477 // Otherwise, if the LHS is not of the same opcode as the root, return.
1478 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001479 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001480 // Should we apply this transform to the RHS?
1481 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1482
1483 // If not to the RHS, check to see if we should apply to the LHS...
1484 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1485 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1486 ShouldApply = true;
1487 }
1488
1489 // If the functor wants to apply the optimization to the RHS of LHSI,
1490 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1491 if (ShouldApply) {
1492 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001493
Chris Lattnerb8b97502003-08-13 19:01:45 +00001494 // Now all of the instructions are in the current basic block, go ahead
1495 // and perform the reassociation.
1496 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1497
1498 // First move the selected RHS to the LHS of the root...
1499 Root.setOperand(0, LHSI->getOperand(1));
1500
1501 // Make what used to be the LHS of the root be the user of the root...
1502 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001503 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001504 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1505 return 0;
1506 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001507 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001508 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001509 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1510 BasicBlock::iterator ARI = &Root; ++ARI;
1511 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1512 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001513
1514 // Now propagate the ExtraOperand down the chain of instructions until we
1515 // get to LHSI.
1516 while (TmpLHSI != LHSI) {
1517 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001518 // Move the instruction to immediately before the chain we are
1519 // constructing to avoid breaking dominance properties.
1520 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1521 BB->getInstList().insert(ARI, NextLHSI);
1522 ARI = NextLHSI;
1523
Chris Lattnerb8b97502003-08-13 19:01:45 +00001524 Value *NextOp = NextLHSI->getOperand(1);
1525 NextLHSI->setOperand(1, ExtraOperand);
1526 TmpLHSI = NextLHSI;
1527 ExtraOperand = NextOp;
1528 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001529
Chris Lattnerb8b97502003-08-13 19:01:45 +00001530 // Now that the instructions are reassociated, have the functor perform
1531 // the transformation...
1532 return F.apply(Root);
1533 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534
Chris Lattnerb8b97502003-08-13 19:01:45 +00001535 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1536 }
1537 return 0;
1538}
1539
1540
1541// AddRHS - Implements: X + X --> X << 1
1542struct AddRHS {
1543 Value *RHS;
1544 AddRHS(Value *rhs) : RHS(rhs) {}
1545 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1546 Instruction *apply(BinaryOperator &Add) const {
1547 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001548 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001549 }
1550};
1551
1552// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1553// iff C1&C2 == 0
1554struct AddMaskingAnd {
1555 Constant *C2;
1556 AddMaskingAnd(Constant *c) : C2(c) {}
1557 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001559 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001560 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001561 }
1562 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001563 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001564 }
1565};
1566
Chris Lattner86102b82005-01-01 16:22:27 +00001567static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001568 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001569 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001570 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001571 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001572
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001573 return IC->InsertNewInstBefore(CastInst::create(
1574 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001575 }
1576
Chris Lattner183b3362004-04-09 19:05:30 +00001577 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001578 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1579 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001580
Chris Lattner183b3362004-04-09 19:05:30 +00001581 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1582 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001583 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1584 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001585 }
1586
1587 Value *Op0 = SO, *Op1 = ConstOperand;
1588 if (!ConstIsRHS)
1589 std::swap(Op0, Op1);
1590 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1592 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001593 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1594 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1595 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001596 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001598 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001599 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001600 abort();
1601 }
Chris Lattner86102b82005-01-01 16:22:27 +00001602 return IC->InsertNewInstBefore(New, I);
1603}
1604
1605// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606// constant as the other operand, try to fold the binary operator into the
1607// select arguments. This also works for Cast instructions, which obviously do
1608// not have a second operand.
1609static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610 InstCombiner *IC) {
1611 // Don't modify shared select instructions
1612 if (!SI->hasOneUse()) return 0;
1613 Value *TV = SI->getOperand(1);
1614 Value *FV = SI->getOperand(2);
1615
1616 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001617 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001618 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001619
Chris Lattner86102b82005-01-01 16:22:27 +00001620 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623 return new SelectInst(SI->getCondition(), SelectTrueVal,
1624 SelectFalseVal);
1625 }
1626 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001627}
1628
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001629
1630/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631/// node as operand #0, see if we can fold the instruction into the PHI (which
1632/// is only possible if all operands to the PHI are constants).
1633Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001635 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001636 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001637
Chris Lattner04689872006-09-09 22:02:56 +00001638 // Check to see if all of the operands of the PHI are constants. If there is
1639 // one non-constant value, remember the BB it is. If there is more than one
1640 // bail out.
1641 BasicBlock *NonConstBB = 0;
1642 for (unsigned i = 0; i != NumPHIValues; ++i)
1643 if (!isa<Constant>(PN->getIncomingValue(i))) {
1644 if (NonConstBB) return 0; // More than one non-const value.
1645 NonConstBB = PN->getIncomingBlock(i);
1646
1647 // If the incoming non-constant value is in I's block, we have an infinite
1648 // loop.
1649 if (NonConstBB == I.getParent())
1650 return 0;
1651 }
1652
1653 // If there is exactly one non-constant value, we can insert a copy of the
1654 // operation in that block. However, if this is a critical edge, we would be
1655 // inserting the computation one some other paths (e.g. inside a loop). Only
1656 // do this if the pred block is unconditionally branching into the phi block.
1657 if (NonConstBB) {
1658 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659 if (!BI || !BI->isUnconditional()) return 0;
1660 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001661
1662 // Okay, we can do the transformation: create the new PHI node.
1663 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001665 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001666 InsertNewInstBefore(NewPN, *PN);
1667
1668 // Next, add all of the operands to the PHI.
1669 if (I.getNumOperands() == 2) {
1670 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001671 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001672 Value *InV;
1673 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001674 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1675 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1676 else
1677 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001678 } else {
1679 assert(PN->getIncomingBlock(i) == NonConstBB);
1680 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1681 InV = BinaryOperator::create(BO->getOpcode(),
1682 PN->getIncomingValue(i), C, "phitmp",
1683 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001684 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685 InV = CmpInst::create(CI->getOpcode(),
1686 CI->getPredicate(),
1687 PN->getIncomingValue(i), C, "phitmp",
1688 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001689 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1690 InV = new ShiftInst(SI->getOpcode(),
1691 PN->getIncomingValue(i), C, "phitmp",
1692 NonConstBB->getTerminator());
1693 else
1694 assert(0 && "Unknown binop!");
1695
1696 WorkList.push_back(cast<Instruction>(InV));
1697 }
1698 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001699 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001700 } else {
1701 CastInst *CI = cast<CastInst>(&I);
1702 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001703 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001704 Value *InV;
1705 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001706 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001707 } else {
1708 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001709 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1710 I.getType(), "phitmp",
1711 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001712 WorkList.push_back(cast<Instruction>(InV));
1713 }
1714 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001715 }
1716 }
1717 return ReplaceInstUsesWith(I, NewPN);
1718}
1719
Chris Lattner113f4f42002-06-25 16:13:24 +00001720Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001721 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001722 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001723
Chris Lattnercf4a9962004-04-10 22:01:55 +00001724 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001725 // X + undef -> undef
1726 if (isa<UndefValue>(RHS))
1727 return ReplaceInstUsesWith(I, RHS);
1728
Chris Lattnercf4a9962004-04-10 22:01:55 +00001729 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001730 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001731 if (RHSC->isNullValue())
1732 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001733 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1734 if (CFP->isExactlyValue(-0.0))
1735 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001736 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001737
Chris Lattnercf4a9962004-04-10 22:01:55 +00001738 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001739 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001740 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001741 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001742 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001743
1744 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1745 // (X & 254)+1 -> (X&254)|1
1746 uint64_t KnownZero, KnownOne;
1747 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00001748 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001749 KnownZero, KnownOne))
1750 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001751 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001752
1753 if (isa<PHINode>(LHS))
1754 if (Instruction *NV = FoldOpIntoPhi(I))
1755 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001756
Chris Lattner330628a2006-01-06 17:59:59 +00001757 ConstantInt *XorRHS = 0;
1758 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001759 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1760 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1761 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1762 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1763
1764 uint64_t C0080Val = 1ULL << 31;
1765 int64_t CFF80Val = -C0080Val;
1766 unsigned Size = 32;
1767 do {
1768 if (TySizeBits > Size) {
1769 bool Found = false;
1770 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1771 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1772 if (RHSSExt == CFF80Val) {
1773 if (XorRHS->getZExtValue() == C0080Val)
1774 Found = true;
1775 } else if (RHSZExt == C0080Val) {
1776 if (XorRHS->getSExtValue() == CFF80Val)
1777 Found = true;
1778 }
1779 if (Found) {
1780 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001781 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001782 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00001783 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001784 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001785 Size = 0; // Not a sign ext, but can't be any others either.
1786 goto FoundSExt;
1787 }
1788 }
1789 Size >>= 1;
1790 C0080Val >>= Size;
1791 CFF80Val >>= Size;
1792 } while (Size >= 8);
1793
1794FoundSExt:
1795 const Type *MiddleType = 0;
1796 switch (Size) {
1797 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001798 case 32: MiddleType = Type::Int32Ty; break;
1799 case 16: MiddleType = Type::Int16Ty; break;
1800 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001801 }
1802 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001803 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001804 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001805 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001806 }
1807 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001808 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001809
Chris Lattnerb8b97502003-08-13 19:01:45 +00001810 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001811 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001812 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001813
1814 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1815 if (RHSI->getOpcode() == Instruction::Sub)
1816 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1817 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1818 }
1819 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1820 if (LHSI->getOpcode() == Instruction::Sub)
1821 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1822 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1823 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001824 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001825
Chris Lattner147e9752002-05-08 22:46:53 +00001826 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001827 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001828 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001829
1830 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001831 if (!isa<Constant>(RHS))
1832 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001833 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001834
Misha Brukmanb1c93172005-04-21 23:48:37 +00001835
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001836 ConstantInt *C2;
1837 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1838 if (X == RHS) // X*C + X --> X * (C+1)
1839 return BinaryOperator::createMul(RHS, AddOne(C2));
1840
1841 // X*C1 + X*C2 --> X * (C1+C2)
1842 ConstantInt *C1;
1843 if (X == dyn_castFoldableMul(RHS, C1))
1844 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001845 }
1846
1847 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001848 if (dyn_castFoldableMul(RHS, C2) == LHS)
1849 return BinaryOperator::createMul(LHS, AddOne(C2));
1850
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001851 // X + ~X --> -1 since ~X = -X-1
1852 if (dyn_castNotVal(LHS) == RHS ||
1853 dyn_castNotVal(RHS) == LHS)
1854 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1855
Chris Lattner57c8d992003-02-18 19:57:07 +00001856
Chris Lattnerb8b97502003-08-13 19:01:45 +00001857 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001858 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001859 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1860 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001861
Chris Lattnerb9cde762003-10-02 15:11:26 +00001862 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001863 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001864 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1865 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1866 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001867 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001868
Chris Lattnerbff91d92004-10-08 05:07:56 +00001869 // (X & FF00) + xx00 -> (X+xx00) & FF00
1870 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1871 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1872 if (Anded == CRHS) {
1873 // See if all bits from the first bit set in the Add RHS up are included
1874 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001875 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001876
1877 // Form a mask of all bits from the lowest bit added through the top.
1878 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001879 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001880
1881 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001882 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001883
Chris Lattnerbff91d92004-10-08 05:07:56 +00001884 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1885 // Okay, the xform is safe. Insert the new add pronto.
1886 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1887 LHS->getName()), I);
1888 return BinaryOperator::createAnd(NewAdd, C2);
1889 }
1890 }
1891 }
1892
Chris Lattnerd4252a72004-07-30 07:50:03 +00001893 // Try to fold constant add into select arguments.
1894 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001895 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001896 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001897 }
1898
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001899 // add (cast *A to intptrtype) B ->
1900 // cast (GEP (cast *A to sbyte*) B) ->
1901 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001902 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001903 CastInst *CI = dyn_cast<CastInst>(LHS);
1904 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001905 if (!CI) {
1906 CI = dyn_cast<CastInst>(RHS);
1907 Other = LHS;
1908 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001909 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001910 (CI->getType()->getPrimitiveSizeInBits() ==
1911 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001912 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001913 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001914 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001915 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001916 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001917 }
1918 }
1919
Chris Lattner113f4f42002-06-25 16:13:24 +00001920 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001921}
1922
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001923// isSignBit - Return true if the value represented by the constant only has the
1924// highest order bit set.
1925static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001926 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001927 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001928}
1929
Chris Lattner113f4f42002-06-25 16:13:24 +00001930Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001932
Chris Lattnere6794492002-08-12 21:17:25 +00001933 if (Op0 == Op1) // sub X, X -> 0
1934 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001935
Chris Lattnere6794492002-08-12 21:17:25 +00001936 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001937 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001938 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001939
Chris Lattner81a7a232004-10-16 18:11:37 +00001940 if (isa<UndefValue>(Op0))
1941 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1942 if (isa<UndefValue>(Op1))
1943 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1944
Chris Lattner8f2f5982003-11-05 01:06:05 +00001945 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1946 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001947 if (C->isAllOnesValue())
1948 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001949
Chris Lattner8f2f5982003-11-05 01:06:05 +00001950 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001951 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001952 if (match(Op1, m_Not(m_Value(X))))
1953 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001954 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001955 // -(X >>u 31) -> (X >>s 31)
1956 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001957 if (C->isNullValue()) {
Chris Lattner27df1db2007-01-15 07:02:54 +00001958 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001959 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001960 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001961 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 if (CU->getZExtValue() ==
1963 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001964 // Ok, the transformation is safe. Insert AShr.
Chris Lattner27df1db2007-01-15 07:02:54 +00001965 return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
Reid Spencer193df252006-12-24 00:40:59 +00001966 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001967 }
1968 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001969 }
1970 else if (SI->getOpcode() == Instruction::AShr) {
1971 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1972 // Check to see if we are shifting out everything but the sign bit.
1973 if (CU->getZExtValue() ==
1974 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00001975 // Ok, the transformation is safe. Insert LShr.
1976 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
1977 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001978 }
1979 }
1980 }
Chris Lattner022167f2004-03-13 00:11:49 +00001981 }
Chris Lattner183b3362004-04-09 19:05:30 +00001982
1983 // Try to fold constant sub into select arguments.
1984 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001986 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001987
1988 if (isa<PHINode>(Op0))
1989 if (Instruction *NV = FoldOpIntoPhi(I))
1990 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001991 }
1992
Chris Lattnera9be4492005-04-07 16:15:25 +00001993 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1994 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001995 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001996 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001997 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001998 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002000 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2001 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2002 // C1-(X+C2) --> (C1-C2)-X
2003 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2004 Op1I->getOperand(0));
2005 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002006 }
2007
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002008 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002009 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2010 // is not used by anyone else...
2011 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002012 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002013 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002014 // Swap the two operands of the subexpr...
2015 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2016 Op1I->setOperand(0, IIOp1);
2017 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002018
Chris Lattner3082c5a2003-02-18 19:28:33 +00002019 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002020 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 }
2022
2023 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024 //
2025 if (Op1I->getOpcode() == Instruction::And &&
2026 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2027 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2028
Chris Lattner396dbfe2004-06-09 05:08:07 +00002029 Value *NewNot =
2030 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002031 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002032 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002033
Reid Spencer3c514952006-10-16 23:08:08 +00002034 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002035 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002036 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002037 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002038 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002039 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002040 ConstantExpr::getNeg(DivRHS));
2041
Chris Lattner57c8d992003-02-18 19:57:07 +00002042 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002043 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002044 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002045 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002046 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002047 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002048 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002049 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002050 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051
Chris Lattner7a002fe2006-12-02 00:13:08 +00002052 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2054 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002055 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2056 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2057 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2058 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002059 } else if (Op0I->getOpcode() == Instruction::Sub) {
2060 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2061 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002062 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002063
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002064 ConstantInt *C1;
2065 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2066 if (X == Op1) { // X*C - X --> X * (C-1)
2067 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2068 return BinaryOperator::createMul(Op1, CP1);
2069 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002070
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002071 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2072 if (X == dyn_castFoldableMul(Op1, C2))
2073 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2074 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002075 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002076}
2077
Reid Spencer266e42b2006-12-23 06:05:41 +00002078/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002079/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002080static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2081 switch (pred) {
2082 case ICmpInst::ICMP_SLT:
2083 // True if LHS s< RHS and RHS == 0
2084 return RHS->isNullValue();
2085 case ICmpInst::ICMP_SLE:
2086 // True if LHS s<= RHS and RHS == -1
2087 return RHS->isAllOnesValue();
2088 case ICmpInst::ICMP_UGE:
2089 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2090 return RHS->getZExtValue() == (1ULL <<
2091 (RHS->getType()->getPrimitiveSizeInBits()-1));
2092 case ICmpInst::ICMP_UGT:
2093 // True if LHS u> RHS and RHS == high-bit-mask - 1
2094 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002095 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002096 default:
2097 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002098 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002099}
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002102 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002103 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002104
Chris Lattner81a7a232004-10-16 18:11:37 +00002105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
Chris Lattnere6794492002-08-12 21:17:25 +00002108 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002111
2112 // ((X << C1)*C2) == (X * (C2 << C1))
2113 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114 if (SI->getOpcode() == Instruction::Shl)
2115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002116 return BinaryOperator::createMul(SI->getOperand(0),
2117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118
Chris Lattnercce81be2003-09-11 22:24:54 +00002119 if (CI->isNullValue())
2120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2121 if (CI->equalsInt(1)) // X * 1 == X
2122 return ReplaceInstUsesWith(I, Op0);
2123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002124 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002125
Reid Spencere0fc4df2006-10-20 07:07:24 +00002126 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002127 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2128 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002129 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002130 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002131 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002132 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 if (Op1F->isNullValue())
2134 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002135
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2137 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138 if (Op1F->getValue() == 1.0)
2139 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2140 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002141
2142 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144 isa<ConstantInt>(Op0I->getOperand(1))) {
2145 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147 Op1, "tmp");
2148 InsertNewInstBefore(Add, I);
2149 Value *C1C2 = ConstantExpr::getMul(Op1,
2150 cast<Constant>(Op0I->getOperand(1)));
2151 return BinaryOperator::createAdd(Add, C1C2);
2152
2153 }
Chris Lattner183b3362004-04-09 19:05:30 +00002154
2155 // Try to fold constant mul into select arguments.
2156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002158 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002159
2160 if (isa<PHINode>(Op0))
2161 if (Instruction *NV = FoldOpIntoPhi(I))
2162 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002163 }
2164
Chris Lattner934a64cf2003-03-10 23:23:04 +00002165 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2166 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002167 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002168
Chris Lattner2635b522004-02-23 05:39:21 +00002169 // If one of the operands of the multiply is a cast from a boolean value, then
2170 // we know the bool is either zero or one, so this is a 'masking' multiply.
2171 // See if we can simplify things based on how the boolean was originally
2172 // formed.
2173 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002174 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002175 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002176 BoolCast = CI;
2177 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002178 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002179 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002180 BoolCast = CI;
2181 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002182 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002183 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184 const Type *SCOpTy = SCIOp0->getType();
2185
Reid Spencer266e42b2006-12-23 06:05:41 +00002186 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002187 // multiply into a shift/and combination.
2188 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002189 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002190 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002191 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002192 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002193 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002194 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002195 BoolCast->getOperand(0)->getName()+
2196 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002197
2198 // If the multiply type is not the same as the source type, sign extend
2199 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002200 if (I.getType() != V->getType()) {
2201 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2202 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2203 Instruction::CastOps opcode =
2204 (SrcBits == DstBits ? Instruction::BitCast :
2205 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2206 V = InsertCastBefore(opcode, V, I.getType(), I);
2207 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002208
Chris Lattner2635b522004-02-23 05:39:21 +00002209 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002210 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002211 }
2212 }
2213 }
2214
Chris Lattner113f4f42002-06-25 16:13:24 +00002215 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002216}
2217
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002218/// This function implements the transforms on div instructions that work
2219/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2220/// used by the visitors to those instructions.
2221/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002222Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002223 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002224
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002225 // undef / X -> 0
2226 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002227 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002228
2229 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002230 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002231 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002232
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002233 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002234 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2235 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002236 // same basic block, then we replace the select with Y, and the condition
2237 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002238 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002239 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002240 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2241 if (ST->isNullValue()) {
2242 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2243 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002244 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002245 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2246 I.setOperand(1, SI->getOperand(2));
2247 else
2248 UpdateValueUsesWith(SI, SI->getOperand(2));
2249 return &I;
2250 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002251
Chris Lattnerd79dc792006-09-09 20:26:32 +00002252 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2253 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2254 if (ST->isNullValue()) {
2255 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2256 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002257 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002258 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2259 I.setOperand(1, SI->getOperand(1));
2260 else
2261 UpdateValueUsesWith(SI, SI->getOperand(1));
2262 return &I;
2263 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002264 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002265
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266 return 0;
2267}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002268
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002269/// This function implements the transforms common to both integer division
2270/// instructions (udiv and sdiv). It is called by the visitors to those integer
2271/// division instructions.
2272/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002273Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2275
2276 if (Instruction *Common = commonDivTransforms(I))
2277 return Common;
2278
2279 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2280 // div X, 1 == X
2281 if (RHS->equalsInt(1))
2282 return ReplaceInstUsesWith(I, Op0);
2283
2284 // (X / C1) / C2 -> X / (C1*C2)
2285 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2286 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2287 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2288 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2289 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002290 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002291
2292 if (!RHS->isNullValue()) { // avoid X udiv 0
2293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2295 return R;
2296 if (isa<PHINode>(Op0))
2297 if (Instruction *NV = FoldOpIntoPhi(I))
2298 return NV;
2299 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002300 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002301
Chris Lattner3082c5a2003-02-18 19:28:33 +00002302 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002303 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002304 if (LHS->equalsInt(0))
2305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2306
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002307 return 0;
2308}
2309
2310Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2312
2313 // Handle the integer div common cases
2314 if (Instruction *Common = commonIDivTransforms(I))
2315 return Common;
2316
2317 // X udiv C^2 -> X >> C
2318 // Check to see if this is an unsigned division with an exact power of 2,
2319 // if so, convert to a right shift.
2320 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2321 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2322 if (isPowerOf2_64(Val)) {
2323 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002324 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002325 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002326 }
2327 }
2328
2329 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2330 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2331 if (RHSI->getOpcode() == Instruction::Shl &&
2332 isa<ConstantInt>(RHSI->getOperand(0))) {
2333 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2334 if (isPowerOf2_64(C1)) {
2335 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002336 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002337 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002338 Constant *C2V = ConstantInt::get(NTy, C2);
2339 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002340 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002341 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002342 }
2343 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002344 }
2345
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002346 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2347 // where C1&C2 are powers of two.
2348 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2349 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2350 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2351 if (!STO->isNullValue() && !STO->isNullValue()) {
2352 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2353 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2354 // Compute the shift amounts
2355 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002356 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002357 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002358 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002359 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002360 TSI = InsertNewInstBefore(TSI, I);
2361
2362 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002363 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002364 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002365 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366 FSI = InsertNewInstBefore(FSI, I);
2367
2368 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002369 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002370 }
2371 }
2372 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002373 return 0;
2374}
2375
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002376Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378
2379 // Handle the integer div common cases
2380 if (Instruction *Common = commonIDivTransforms(I))
2381 return Common;
2382
2383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2384 // sdiv X, -1 == -X
2385 if (RHS->isAllOnesValue())
2386 return BinaryOperator::createNeg(Op0);
2387
2388 // -X/C -> X/-C
2389 if (Value *LHSNeg = dyn_castNegVal(Op0))
2390 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2391 }
2392
2393 // If the sign bits of both operands are zero (i.e. we can prove they are
2394 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002395 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002396 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2397 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2398 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2399 }
2400 }
2401
2402 return 0;
2403}
2404
2405Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2406 return commonDivTransforms(I);
2407}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002408
Chris Lattner85dda9a2006-03-02 06:50:58 +00002409/// GetFactor - If we can prove that the specified value is at least a multiple
2410/// of some factor, return that factor.
2411static Constant *GetFactor(Value *V) {
2412 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2413 return CI;
2414
2415 // Unless we can be tricky, we know this is a multiple of 1.
2416 Constant *Result = ConstantInt::get(V->getType(), 1);
2417
2418 Instruction *I = dyn_cast<Instruction>(V);
2419 if (!I) return Result;
2420
2421 if (I->getOpcode() == Instruction::Mul) {
2422 // Handle multiplies by a constant, etc.
2423 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2424 GetFactor(I->getOperand(1)));
2425 } else if (I->getOpcode() == Instruction::Shl) {
2426 // (X<<C) -> X * (1 << C)
2427 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2428 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2429 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2430 }
2431 } else if (I->getOpcode() == Instruction::And) {
2432 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2433 // X & 0xFFF0 is known to be a multiple of 16.
2434 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2435 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2436 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002437 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002438 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002439 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002440 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002441 if (!CI->isIntegerCast())
2442 return Result;
2443 Value *Op = CI->getOperand(0);
2444 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002445 }
2446 return Result;
2447}
2448
Reid Spencer7eb55b32006-11-02 01:53:59 +00002449/// This function implements the transforms on rem instructions that work
2450/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2451/// is used by the visitors to those instructions.
2452/// @brief Transforms common to all three rem instructions
2453Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002454 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002455
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002456 // 0 % X == 0, we don't need to preserve faults!
2457 if (Constant *LHS = dyn_cast<Constant>(Op0))
2458 if (LHS->isNullValue())
2459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461 if (isa<UndefValue>(Op0)) // undef % X -> 0
2462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463 if (isa<UndefValue>(Op1))
2464 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002465
2466 // Handle cases involving: rem X, (select Cond, Y, Z)
2467 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2468 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2469 // the same basic block, then we replace the select with Y, and the
2470 // condition of the select with false (if the cond value is in the same
2471 // BB). If the select has uses other than the div, this allows them to be
2472 // simplified also.
2473 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2474 if (ST->isNullValue()) {
2475 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2476 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002477 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002478 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2479 I.setOperand(1, SI->getOperand(2));
2480 else
2481 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002482 return &I;
2483 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002484 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2485 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2486 if (ST->isNullValue()) {
2487 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2488 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002489 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002490 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2491 I.setOperand(1, SI->getOperand(1));
2492 else
2493 UpdateValueUsesWith(SI, SI->getOperand(1));
2494 return &I;
2495 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002496 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002497
Reid Spencer7eb55b32006-11-02 01:53:59 +00002498 return 0;
2499}
2500
2501/// This function implements the transforms common to both integer remainder
2502/// instructions (urem and srem). It is called by the visitors to those integer
2503/// remainder instructions.
2504/// @brief Common integer remainder transforms
2505Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508 if (Instruction *common = commonRemTransforms(I))
2509 return common;
2510
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002511 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002512 // X % 0 == undef, we don't need to preserve faults!
2513 if (RHS->equalsInt(0))
2514 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2515
Chris Lattner3082c5a2003-02-18 19:28:33 +00002516 if (RHS->equalsInt(1)) // X % 1 == 0
2517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
Chris Lattnerb70f1412006-02-28 05:49:21 +00002519 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2520 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2521 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2522 return R;
2523 } else if (isa<PHINode>(Op0I)) {
2524 if (Instruction *NV = FoldOpIntoPhi(I))
2525 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002526 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002527 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2528 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002529 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002530 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002531 }
2532
Reid Spencer7eb55b32006-11-02 01:53:59 +00002533 return 0;
2534}
2535
2536Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539 if (Instruction *common = commonIRemTransforms(I))
2540 return common;
2541
2542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2543 // X urem C^2 -> X and C
2544 // Check to see if this is an unsigned remainder with an exact power of 2,
2545 // if so, convert to a bitwise and.
2546 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2547 if (isPowerOf2_64(C->getZExtValue()))
2548 return BinaryOperator::createAnd(Op0, SubOne(C));
2549 }
2550
Chris Lattner2e90b732006-02-05 07:54:04 +00002551 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002552 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2553 if (RHSI->getOpcode() == Instruction::Shl &&
2554 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002555 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002556 if (isPowerOf2_64(C1)) {
2557 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2558 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2559 "tmp"), I);
2560 return BinaryOperator::createAnd(Op0, Add);
2561 }
2562 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002563 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002564
Reid Spencer7eb55b32006-11-02 01:53:59 +00002565 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2566 // where C1&C2 are powers of two.
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2568 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2569 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2570 // STO == 0 and SFO == 0 handled above.
2571 if (isPowerOf2_64(STO->getZExtValue()) &&
2572 isPowerOf2_64(SFO->getZExtValue())) {
2573 Value *TrueAnd = InsertNewInstBefore(
2574 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2575 Value *FalseAnd = InsertNewInstBefore(
2576 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2577 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2578 }
2579 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002580 }
2581
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002582 return 0;
2583}
2584
Reid Spencer7eb55b32006-11-02 01:53:59 +00002585Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2586 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588 if (Instruction *common = commonIRemTransforms(I))
2589 return common;
2590
2591 if (Value *RHSNeg = dyn_castNegVal(Op1))
2592 if (!isa<ConstantInt>(RHSNeg) ||
2593 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2594 // X % -Y -> X % Y
2595 AddUsesToWorkList(I);
2596 I.setOperand(1, RHSNeg);
2597 return &I;
2598 }
2599
2600 // If the top bits of both operands are zero (i.e. we can prove they are
2601 // unsigned inputs), turn this into a urem.
2602 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2603 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2604 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2605 return BinaryOperator::createURem(Op0, Op1, I.getName());
2606 }
2607
2608 return 0;
2609}
2610
2611Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002612 return commonRemTransforms(I);
2613}
2614
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002615// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002616static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2617 if (isSigned) {
2618 // Calculate 0111111111..11111
2619 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2620 int64_t Val = INT64_MAX; // All ones
2621 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2622 return C->getSExtValue() == Val-1;
2623 }
Reid Spencera94d3942007-01-19 21:13:56 +00002624 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002625}
2626
2627// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002628static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2629 if (isSigned) {
2630 // Calculate 1111111111000000000000
2631 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2632 int64_t Val = -1; // All ones
2633 Val <<= TypeBits-1; // Shift over to the right spot
2634 return C->getSExtValue() == Val+1;
2635 }
2636 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002637}
2638
Chris Lattner35167c32004-06-09 07:59:58 +00002639// isOneBitSet - Return true if there is exactly one bit set in the specified
2640// constant.
2641static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002642 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002643 return V && (V & (V-1)) == 0;
2644}
2645
Chris Lattner8fc5af42004-09-23 21:46:38 +00002646#if 0 // Currently unused
2647// isLowOnes - Return true if the constant is of the form 0+1+.
2648static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002649 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002650
2651 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002652 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002653
2654 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2655 return U && V && (U & V) == 0;
2656}
2657#endif
2658
2659// isHighOnes - Return true if the constant is of the form 1+0+.
2660// This is the same as lowones(~X).
2661static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002662 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002663 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002664
2665 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002666 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002667
2668 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2669 return U && V && (U & V) == 0;
2670}
2671
Reid Spencer266e42b2006-12-23 06:05:41 +00002672/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002673/// are carefully arranged to allow folding of expressions such as:
2674///
2675/// (A < B) | (A > B) --> (A != B)
2676///
Reid Spencer266e42b2006-12-23 06:05:41 +00002677/// Note that this is only valid if the first and second predicates have the
2678/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002679///
Reid Spencer266e42b2006-12-23 06:05:41 +00002680/// Three bits are used to represent the condition, as follows:
2681/// 0 A > B
2682/// 1 A == B
2683/// 2 A < B
2684///
2685/// <=> Value Definition
2686/// 000 0 Always false
2687/// 001 1 A > B
2688/// 010 2 A == B
2689/// 011 3 A >= B
2690/// 100 4 A < B
2691/// 101 5 A != B
2692/// 110 6 A <= B
2693/// 111 7 Always true
2694///
2695static unsigned getICmpCode(const ICmpInst *ICI) {
2696 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002697 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002698 case ICmpInst::ICMP_UGT: return 1; // 001
2699 case ICmpInst::ICMP_SGT: return 1; // 001
2700 case ICmpInst::ICMP_EQ: return 2; // 010
2701 case ICmpInst::ICMP_UGE: return 3; // 011
2702 case ICmpInst::ICMP_SGE: return 3; // 011
2703 case ICmpInst::ICMP_ULT: return 4; // 100
2704 case ICmpInst::ICMP_SLT: return 4; // 100
2705 case ICmpInst::ICMP_NE: return 5; // 101
2706 case ICmpInst::ICMP_ULE: return 6; // 110
2707 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002708 // True -> 7
2709 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002710 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002711 return 0;
2712 }
2713}
2714
Reid Spencer266e42b2006-12-23 06:05:41 +00002715/// getICmpValue - This is the complement of getICmpCode, which turns an
2716/// opcode and two operands into either a constant true or false, or a brand
2717/// new /// ICmp instruction. The sign is passed in to determine which kind
2718/// of predicate to use in new icmp instructions.
2719static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2720 switch (code) {
2721 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002722 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002723 case 1:
2724 if (sign)
2725 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2726 else
2727 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2728 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2729 case 3:
2730 if (sign)
2731 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2732 else
2733 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2734 case 4:
2735 if (sign)
2736 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2737 else
2738 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2739 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2740 case 6:
2741 if (sign)
2742 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2743 else
2744 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002745 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002746 }
2747}
2748
Reid Spencer266e42b2006-12-23 06:05:41 +00002749static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2750 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2751 (ICmpInst::isSignedPredicate(p1) &&
2752 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2753 (ICmpInst::isSignedPredicate(p2) &&
2754 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2755}
2756
2757namespace {
2758// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2759struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002760 InstCombiner &IC;
2761 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002762 ICmpInst::Predicate pred;
2763 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2764 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2765 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002766 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002767 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2768 if (PredicatesFoldable(pred, ICI->getPredicate()))
2769 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2770 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002771 return false;
2772 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002773 Instruction *apply(Instruction &Log) const {
2774 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2775 if (ICI->getOperand(0) != LHS) {
2776 assert(ICI->getOperand(1) == LHS);
2777 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002778 }
2779
Reid Spencer266e42b2006-12-23 06:05:41 +00002780 unsigned LHSCode = getICmpCode(ICI);
2781 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002782 unsigned Code;
2783 switch (Log.getOpcode()) {
2784 case Instruction::And: Code = LHSCode & RHSCode; break;
2785 case Instruction::Or: Code = LHSCode | RHSCode; break;
2786 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002787 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002788 }
2789
Reid Spencer266e42b2006-12-23 06:05:41 +00002790 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 if (Instruction *I = dyn_cast<Instruction>(RV))
2792 return I;
2793 // Otherwise, it's a constant boolean value...
2794 return IC.ReplaceInstUsesWith(Log, RV);
2795 }
2796};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002797} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002798
Chris Lattnerba1cb382003-09-19 17:17:26 +00002799// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2800// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2801// guaranteed to be either a shift instruction or a binary operator.
2802Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002803 ConstantInt *OpRHS,
2804 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002805 BinaryOperator &TheAnd) {
2806 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002807 Constant *Together = 0;
2808 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002809 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002810
Chris Lattnerba1cb382003-09-19 17:17:26 +00002811 switch (Op->getOpcode()) {
2812 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002813 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002814 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2815 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002816 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002817 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002818 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002819 }
2820 break;
2821 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002822 if (Together == AndRHS) // (X | C) & C --> C
2823 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002824
Chris Lattner86102b82005-01-01 16:22:27 +00002825 if (Op->hasOneUse() && Together != OpRHS) {
2826 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2827 std::string Op0Name = Op->getName(); Op->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2829 InsertNewInstBefore(Or, TheAnd);
2830 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002831 }
2832 break;
2833 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002834 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002835 // Adding a one to a single bit bit-field should be turned into an XOR
2836 // of the bit. First thing to check is to see if this AND is with a
2837 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002838 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002839
2840 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00002841 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842
2843 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002844 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845 // Ok, at this point, we know that we are masking the result of the
2846 // ADD down to exactly one bit. If the constant we are adding has
2847 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002848 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002849
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 // Check to see if any bits below the one bit set in AndRHSV are set.
2851 if ((AddRHS & (AndRHSV-1)) == 0) {
2852 // If not, the only thing that can effect the output of the AND is
2853 // the bit specified by AndRHSV. If that bit is set, the effect of
2854 // the XOR is to toggle the bit. If it is clear, then the ADD has
2855 // no effect.
2856 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2857 TheAnd.setOperand(0, X);
2858 return &TheAnd;
2859 } else {
2860 std::string Name = Op->getName(); Op->setName("");
2861 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002862 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002863 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002864 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002865 }
2866 }
2867 }
2868 }
2869 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002870
2871 case Instruction::Shl: {
2872 // We know that the AND will not produce any of the bits shifted in, so if
2873 // the anded constant includes them, clear them now!
2874 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002875 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002876 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2877 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002878
Chris Lattner7e794272004-09-24 15:21:34 +00002879 if (CI == ShlMask) { // Masking out bits that the shift already masks
2880 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2881 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002882 TheAnd.setOperand(1, CI);
2883 return &TheAnd;
2884 }
2885 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002886 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002887 case Instruction::LShr:
2888 {
Chris Lattner2da29172003-09-19 19:05:02 +00002889 // We know that the AND will not produce any of the bits shifted in, so if
2890 // the anded constant includes them, clear them now! This only applies to
2891 // unsigned shifts, because a signed shr may bring in set bits!
2892 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002893 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002894 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2895 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002896
Reid Spencerfdff9382006-11-08 06:47:33 +00002897 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2898 return ReplaceInstUsesWith(TheAnd, Op);
2899 } else if (CI != AndRHS) {
2900 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2901 return &TheAnd;
2902 }
2903 break;
2904 }
2905 case Instruction::AShr:
2906 // Signed shr.
2907 // See if this is shifting in some sign extension, then masking it out
2908 // with an and.
2909 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002910 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002911 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002912 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2913 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002914 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002915 // Make the argument unsigned.
2916 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002917 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2918 OpRHS, Op->getName()), TheAnd);
2919 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002920 }
Chris Lattner2da29172003-09-19 19:05:02 +00002921 }
2922 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002923 }
2924 return 0;
2925}
2926
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002927
Chris Lattner6862fbd2004-09-29 17:40:11 +00002928/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2929/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002930/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2931/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002932/// insert new instructions.
2933Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002934 bool isSigned, bool Inside,
2935 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002936 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002937 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002938 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002939
Chris Lattner6862fbd2004-09-29 17:40:11 +00002940 if (Inside) {
2941 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002942 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002943
Reid Spencer266e42b2006-12-23 06:05:41 +00002944 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002945 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002946 ICmpInst::Predicate pred = (isSigned ?
2947 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2948 return new ICmpInst(pred, V, Hi);
2949 }
2950
2951 // Emit V-Lo <u Hi-Lo
2952 Constant *NegLo = ConstantExpr::getNeg(Lo);
2953 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002954 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002955 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2956 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002957 }
2958
2959 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002960 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961
Reid Spencer266e42b2006-12-23 06:05:41 +00002962 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002963 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002964 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002965 ICmpInst::Predicate pred = (isSigned ?
2966 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2967 return new ICmpInst(pred, V, Hi);
2968 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00002969
Reid Spencer266e42b2006-12-23 06:05:41 +00002970 // Emit V-Lo > Hi-1-Lo
2971 Constant *NegLo = ConstantExpr::getNeg(Lo);
2972 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002973 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002974 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2975 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002976}
2977
Chris Lattnerb4b25302005-09-18 07:22:02 +00002978// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2979// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2980// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2981// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002982static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002983 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002984 if (!isShiftedMask_64(V)) return false;
2985
2986 // look for the first zero bit after the run of ones
2987 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2988 // look for the first non-zero bit
2989 ME = 64-CountLeadingZeros_64(V);
2990 return true;
2991}
2992
2993
2994
2995/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2996/// where isSub determines whether the operator is a sub. If we can fold one of
2997/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002998///
2999/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3000/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3001/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3002///
3003/// return (A +/- B).
3004///
3005Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003006 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003007 Instruction &I) {
3008 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3009 if (!LHSI || LHSI->getNumOperands() != 2 ||
3010 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3011
3012 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3013
3014 switch (LHSI->getOpcode()) {
3015 default: return 0;
3016 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003017 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3018 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003019 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003020 break;
3021
3022 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3023 // part, we don't need any explicit masks to take them out of A. If that
3024 // is all N is, ignore it.
3025 unsigned MB, ME;
3026 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003027 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003028 Mask >>= 64-MB+1;
3029 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003030 break;
3031 }
3032 }
Chris Lattneraf517572005-09-18 04:24:45 +00003033 return 0;
3034 case Instruction::Or:
3035 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003036 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003037 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003038 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003039 break;
3040 return 0;
3041 }
3042
3043 Instruction *New;
3044 if (isSub)
3045 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3046 else
3047 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3048 return InsertNewInstBefore(New, I);
3049}
3050
Chris Lattner113f4f42002-06-25 16:13:24 +00003051Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003052 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003054
Chris Lattner81a7a232004-10-16 18:11:37 +00003055 if (isa<UndefValue>(Op1)) // X & undef -> 0
3056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3057
Chris Lattner86102b82005-01-01 16:22:27 +00003058 // and X, X = X
3059 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003060 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003061
Chris Lattner5b2edb12006-02-12 08:02:11 +00003062 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003063 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003064 uint64_t KnownZero, KnownOne;
Chris Lattner120ab032007-01-18 22:16:33 +00003065 if (!isa<PackedType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003066 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003067 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003068 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003069 } else {
3070 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Op1)) {
3071 if (CP->isAllOnesValue())
3072 return ReplaceInstUsesWith(I, I.getOperand(0));
3073 }
3074 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003075
Zhou Sheng75b871f2007-01-11 12:24:14 +00003076 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003077 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003078 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003079 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003080
Chris Lattnerba1cb382003-09-19 17:17:26 +00003081 // Optimize a variety of ((val OP C1) & C2) combinations...
3082 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3083 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003084 Value *Op0LHS = Op0I->getOperand(0);
3085 Value *Op0RHS = Op0I->getOperand(1);
3086 switch (Op0I->getOpcode()) {
3087 case Instruction::Xor:
3088 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003089 // If the mask is only needed on one incoming arm, push it up.
3090 if (Op0I->hasOneUse()) {
3091 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3092 // Not masking anything out for the LHS, move to RHS.
3093 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3094 Op0RHS->getName()+".masked");
3095 InsertNewInstBefore(NewRHS, I);
3096 return BinaryOperator::create(
3097 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003098 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003099 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003100 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3101 // Not masking anything out for the RHS, move to LHS.
3102 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3103 Op0LHS->getName()+".masked");
3104 InsertNewInstBefore(NewLHS, I);
3105 return BinaryOperator::create(
3106 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3107 }
3108 }
3109
Chris Lattner86102b82005-01-01 16:22:27 +00003110 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003111 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003112 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3113 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3114 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3115 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3116 return BinaryOperator::createAnd(V, AndRHS);
3117 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3118 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003119 break;
3120
3121 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003122 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3123 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3124 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3125 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3126 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003127 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003128 }
3129
Chris Lattner16464b32003-07-23 19:25:52 +00003130 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003131 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003132 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003133 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003134 // If this is an integer truncation or change from signed-to-unsigned, and
3135 // if the source is an and/or with immediate, transform it. This
3136 // frequently occurs for bitfield accesses.
3137 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003138 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003139 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003140 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003141 if (CastOp->getOpcode() == Instruction::And) {
3142 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003143 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3144 // This will fold the two constants together, which may allow
3145 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003146 Instruction *NewCast = CastInst::createTruncOrBitCast(
3147 CastOp->getOperand(0), I.getType(),
3148 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003149 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003150 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003151 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003152 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003153 return BinaryOperator::createAnd(NewCast, C3);
3154 } else if (CastOp->getOpcode() == Instruction::Or) {
3155 // Change: and (cast (or X, C1) to T), C2
3156 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003157 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003158 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3159 return ReplaceInstUsesWith(I, AndRHS);
3160 }
3161 }
Chris Lattner33217db2003-07-23 19:36:21 +00003162 }
Chris Lattner183b3362004-04-09 19:05:30 +00003163
3164 // Try to fold constant and into select arguments.
3165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003166 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003167 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003168 if (isa<PHINode>(Op0))
3169 if (Instruction *NV = FoldOpIntoPhi(I))
3170 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003171 }
3172
Chris Lattnerbb74e222003-03-10 23:06:50 +00003173 Value *Op0NotVal = dyn_castNotVal(Op0);
3174 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003175
Chris Lattner023a4832004-06-18 06:07:51 +00003176 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3177 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3178
Misha Brukman9c003d82004-07-30 12:50:08 +00003179 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003180 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003181 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3182 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003183 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003184 return BinaryOperator::createNot(Or);
3185 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003186
3187 {
3188 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003189 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3190 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3191 return ReplaceInstUsesWith(I, Op1);
3192 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3193 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3194 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003195
3196 if (Op0->hasOneUse() &&
3197 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3198 if (A == Op1) { // (A^B)&A -> A&(A^B)
3199 I.swapOperands(); // Simplify below
3200 std::swap(Op0, Op1);
3201 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3202 cast<BinaryOperator>(Op0)->swapOperands();
3203 I.swapOperands(); // Simplify below
3204 std::swap(Op0, Op1);
3205 }
3206 }
3207 if (Op1->hasOneUse() &&
3208 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3209 if (B == Op0) { // B&(A^B) -> B&(B^A)
3210 cast<BinaryOperator>(Op1)->swapOperands();
3211 std::swap(A, B);
3212 }
3213 if (A == Op0) { // A&(A^B) -> A & ~B
3214 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3215 InsertNewInstBefore(NotB, I);
3216 return BinaryOperator::createAnd(A, NotB);
3217 }
3218 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003219 }
3220
Reid Spencer266e42b2006-12-23 06:05:41 +00003221 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3222 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3223 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003224 return R;
3225
Chris Lattner623826c2004-09-28 21:48:02 +00003226 Value *LHSVal, *RHSVal;
3227 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003228 ICmpInst::Predicate LHSCC, RHSCC;
3229 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3230 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3231 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3232 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3233 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3234 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3235 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3236 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003237 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003238 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3239 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3240 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3241 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003242 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003243 std::swap(LHS, RHS);
3244 std::swap(LHSCst, RHSCst);
3245 std::swap(LHSCC, RHSCC);
3246 }
3247
Reid Spencer266e42b2006-12-23 06:05:41 +00003248 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003249 // comparing a value against two constants and and'ing the result
3250 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003251 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3252 // (from the FoldICmpLogical check above), that the two constants
3253 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003254 assert(LHSCst != RHSCst && "Compares not folded above?");
3255
3256 switch (LHSCC) {
3257 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003258 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003259 switch (RHSCC) {
3260 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003261 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3262 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3263 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003264 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003265 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3266 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3267 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003268 return ReplaceInstUsesWith(I, LHS);
3269 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003270 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003271 switch (RHSCC) {
3272 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003273 case ICmpInst::ICMP_ULT:
3274 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3275 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3276 break; // (X != 13 & X u< 15) -> no change
3277 case ICmpInst::ICMP_SLT:
3278 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3279 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3280 break; // (X != 13 & X s< 15) -> no change
3281 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3282 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3283 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003284 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003285 case ICmpInst::ICMP_NE:
3286 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003287 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3288 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3289 LHSVal->getName()+".off");
3290 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003291 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003292 }
3293 break; // (X != 13 & X != 15) -> no change
3294 }
3295 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003296 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003297 switch (RHSCC) {
3298 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003299 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3300 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003301 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003302 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3303 break;
3304 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3305 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003306 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003307 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3308 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003309 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003310 break;
3311 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003312 switch (RHSCC) {
3313 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003314 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3315 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003316 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003317 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3318 break;
3319 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3320 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003321 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003322 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3323 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003324 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003325 break;
3326 case ICmpInst::ICMP_UGT:
3327 switch (RHSCC) {
3328 default: assert(0 && "Unknown integer condition code!");
3329 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3330 return ReplaceInstUsesWith(I, LHS);
3331 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3332 return ReplaceInstUsesWith(I, RHS);
3333 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3334 break;
3335 case ICmpInst::ICMP_NE:
3336 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3337 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3338 break; // (X u> 13 & X != 15) -> no change
3339 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3340 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3341 true, I);
3342 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3343 break;
3344 }
3345 break;
3346 case ICmpInst::ICMP_SGT:
3347 switch (RHSCC) {
3348 default: assert(0 && "Unknown integer condition code!");
3349 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3350 return ReplaceInstUsesWith(I, LHS);
3351 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3352 return ReplaceInstUsesWith(I, RHS);
3353 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3354 break;
3355 case ICmpInst::ICMP_NE:
3356 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3357 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3358 break; // (X s> 13 & X != 15) -> no change
3359 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3360 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3361 true, I);
3362 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3363 break;
3364 }
3365 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003366 }
3367 }
3368 }
3369
Chris Lattner3af10532006-05-05 06:39:07 +00003370 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003371 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3372 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3373 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3374 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003375 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003376 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003377 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3378 I.getType(), TD) &&
3379 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3380 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003381 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3382 Op1C->getOperand(0),
3383 I.getName());
3384 InsertNewInstBefore(NewOp, I);
3385 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3386 }
Chris Lattner3af10532006-05-05 06:39:07 +00003387 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003388
3389 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3390 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3391 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3392 if (SI0->getOpcode() == SI1->getOpcode() &&
3393 SI0->getOperand(1) == SI1->getOperand(1) &&
3394 (SI0->hasOneUse() || SI1->hasOneUse())) {
3395 Instruction *NewOp =
3396 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3397 SI1->getOperand(0),
3398 SI0->getName()), I);
3399 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3400 }
Chris Lattner3af10532006-05-05 06:39:07 +00003401 }
3402
Chris Lattner113f4f42002-06-25 16:13:24 +00003403 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003404}
3405
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003406/// CollectBSwapParts - Look to see if the specified value defines a single byte
3407/// in the result. If it does, and if the specified byte hasn't been filled in
3408/// yet, fill it in and return false.
3409static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3410 Instruction *I = dyn_cast<Instruction>(V);
3411 if (I == 0) return true;
3412
3413 // If this is an or instruction, it is an inner node of the bswap.
3414 if (I->getOpcode() == Instruction::Or)
3415 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3416 CollectBSwapParts(I->getOperand(1), ByteValues);
3417
3418 // If this is a shift by a constant int, and it is "24", then its operand
3419 // defines a byte. We only handle unsigned types here.
3420 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3421 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003422 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003423 8*(ByteValues.size()-1))
3424 return true;
3425
3426 unsigned DestNo;
3427 if (I->getOpcode() == Instruction::Shl) {
3428 // X << 24 defines the top byte with the lowest of the input bytes.
3429 DestNo = ByteValues.size()-1;
3430 } else {
3431 // X >>u 24 defines the low byte with the highest of the input bytes.
3432 DestNo = 0;
3433 }
3434
3435 // If the destination byte value is already defined, the values are or'd
3436 // together, which isn't a bswap (unless it's an or of the same bits).
3437 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3438 return true;
3439 ByteValues[DestNo] = I->getOperand(0);
3440 return false;
3441 }
3442
3443 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3444 // don't have this.
3445 Value *Shift = 0, *ShiftLHS = 0;
3446 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3447 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3448 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3449 return true;
3450 Instruction *SI = cast<Instruction>(Shift);
3451
3452 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003453 if (ShiftAmt->getZExtValue() & 7 ||
3454 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003455 return true;
3456
3457 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3458 unsigned DestByte;
3459 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003460 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003461 break;
3462 // Unknown mask for bswap.
3463 if (DestByte == ByteValues.size()) return true;
3464
Reid Spencere0fc4df2006-10-20 07:07:24 +00003465 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003466 unsigned SrcByte;
3467 if (SI->getOpcode() == Instruction::Shl)
3468 SrcByte = DestByte - ShiftBytes;
3469 else
3470 SrcByte = DestByte + ShiftBytes;
3471
3472 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3473 if (SrcByte != ByteValues.size()-DestByte-1)
3474 return true;
3475
3476 // If the destination byte value is already defined, the values are or'd
3477 // together, which isn't a bswap (unless it's an or of the same bits).
3478 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3479 return true;
3480 ByteValues[DestByte] = SI->getOperand(0);
3481 return false;
3482}
3483
3484/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3485/// If so, insert the new bswap intrinsic and return it.
3486Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3487 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003488 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003489 return 0;
3490
3491 /// ByteValues - For each byte of the result, we keep track of which value
3492 /// defines each byte.
3493 std::vector<Value*> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003494 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003495
3496 // Try to find all the pieces corresponding to the bswap.
3497 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3498 CollectBSwapParts(I.getOperand(1), ByteValues))
3499 return 0;
3500
3501 // Check to see if all of the bytes come from the same value.
3502 Value *V = ByteValues[0];
3503 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3504
3505 // Check to make sure that all of the bytes come from the same value.
3506 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3507 if (ByteValues[i] != V)
3508 return 0;
3509
3510 // If they do then *success* we can turn this into a bswap. Figure out what
3511 // bswap to make it into.
3512 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003513 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003514 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003515 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003516 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003517 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003518 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003519 FnName = "llvm.bswap.i64";
3520 else
3521 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003522 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003523 return new CallInst(F, V);
3524}
3525
3526
Chris Lattner113f4f42002-06-25 16:13:24 +00003527Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003528 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003530
Chris Lattner81a7a232004-10-16 18:11:37 +00003531 if (isa<UndefValue>(Op1))
3532 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003533 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003534
Chris Lattner5b2edb12006-02-12 08:02:11 +00003535 // or X, X = X
3536 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003537 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003538
Chris Lattner5b2edb12006-02-12 08:02:11 +00003539 // See if we can simplify any instructions used by the instruction whose sole
3540 // purpose is to compute bits we don't care about.
3541 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003542 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003543 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003544 KnownZero, KnownOne))
3545 return &I;
3546
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003547 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003548 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003549 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003550 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3551 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003552 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3553 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003554 InsertNewInstBefore(Or, I);
3555 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3556 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003557
Chris Lattnerd4252a72004-07-30 07:50:03 +00003558 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3559 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3560 std::string Op0Name = Op0->getName(); Op0->setName("");
3561 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3562 InsertNewInstBefore(Or, I);
3563 return BinaryOperator::createXor(Or,
3564 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003565 }
Chris Lattner183b3362004-04-09 19:05:30 +00003566
3567 // Try to fold constant and into select arguments.
3568 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003569 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003570 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003571 if (isa<PHINode>(Op0))
3572 if (Instruction *NV = FoldOpIntoPhi(I))
3573 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003574 }
3575
Chris Lattner330628a2006-01-06 17:59:59 +00003576 Value *A = 0, *B = 0;
3577 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003578
3579 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3580 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3581 return ReplaceInstUsesWith(I, Op1);
3582 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3583 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3584 return ReplaceInstUsesWith(I, Op0);
3585
Chris Lattnerb7845d62006-07-10 20:25:24 +00003586 // (A | B) | C and A | (B | C) -> bswap if possible.
3587 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003588 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003589 match(Op1, m_Or(m_Value(), m_Value())) ||
3590 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3591 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003592 if (Instruction *BSwap = MatchBSwap(I))
3593 return BSwap;
3594 }
3595
Chris Lattnerb62f5082005-05-09 04:58:36 +00003596 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3597 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003598 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003599 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3600 Op0->setName("");
3601 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3602 }
3603
3604 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3605 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003606 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003607 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3608 Op0->setName("");
3609 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3610 }
3611
Chris Lattner15212982005-09-18 03:42:07 +00003612 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003613 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003614 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3615
3616 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3617 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3618
3619
Chris Lattner01f56c62005-09-18 06:02:59 +00003620 // If we have: ((V + N) & C1) | (V & C2)
3621 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3622 // replace with V+N.
3623 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003624 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003625 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003626 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3627 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003628 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003629 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003630 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003631 return ReplaceInstUsesWith(I, A);
3632 }
3633 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003634 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003635 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3636 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003637 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003638 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003639 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003640 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003641 }
3642 }
3643 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003644
3645 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3646 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3647 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3648 if (SI0->getOpcode() == SI1->getOpcode() &&
3649 SI0->getOperand(1) == SI1->getOperand(1) &&
3650 (SI0->hasOneUse() || SI1->hasOneUse())) {
3651 Instruction *NewOp =
3652 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3653 SI1->getOperand(0),
3654 SI0->getName()), I);
3655 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3656 }
3657 }
Chris Lattner812aab72003-08-12 19:11:07 +00003658
Chris Lattnerd4252a72004-07-30 07:50:03 +00003659 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3660 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003661 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003662 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003663 } else {
3664 A = 0;
3665 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003666 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003667 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3668 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003669 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003670 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003671
Misha Brukman9c003d82004-07-30 12:50:08 +00003672 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003673 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3674 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3675 I.getName()+".demorgan"), I);
3676 return BinaryOperator::createNot(And);
3677 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003678 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003679
Reid Spencer266e42b2006-12-23 06:05:41 +00003680 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3681 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3682 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003683 return R;
3684
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003685 Value *LHSVal, *RHSVal;
3686 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003687 ICmpInst::Predicate LHSCC, RHSCC;
3688 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3689 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3690 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3691 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3692 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3693 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3694 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3695 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003696 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003697 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3698 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3699 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3700 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003701 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003702 std::swap(LHS, RHS);
3703 std::swap(LHSCst, RHSCst);
3704 std::swap(LHSCC, RHSCC);
3705 }
3706
Reid Spencer266e42b2006-12-23 06:05:41 +00003707 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003708 // comparing a value against two constants and or'ing the result
3709 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003710 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3711 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003712 // equal.
3713 assert(LHSCst != RHSCst && "Compares not folded above?");
3714
3715 switch (LHSCC) {
3716 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003717 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003718 switch (RHSCC) {
3719 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003720 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003721 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3722 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3723 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3724 LHSVal->getName()+".off");
3725 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003726 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003727 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003728 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003729 break; // (X == 13 | X == 15) -> no change
3730 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3731 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003732 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003733 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3734 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3735 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003736 return ReplaceInstUsesWith(I, RHS);
3737 }
3738 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003739 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003740 switch (RHSCC) {
3741 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003742 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3743 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3744 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003745 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003746 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3747 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3748 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003749 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003750 }
3751 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003752 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003753 switch (RHSCC) {
3754 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003756 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003757 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3758 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3759 false, I);
3760 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3761 break;
3762 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3763 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003764 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003765 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3766 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003767 }
3768 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003769 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003770 switch (RHSCC) {
3771 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003772 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3773 break;
3774 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3775 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3776 false, I);
3777 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3778 break;
3779 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3780 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3781 return ReplaceInstUsesWith(I, RHS);
3782 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3783 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003784 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003785 break;
3786 case ICmpInst::ICMP_UGT:
3787 switch (RHSCC) {
3788 default: assert(0 && "Unknown integer condition code!");
3789 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3790 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3791 return ReplaceInstUsesWith(I, LHS);
3792 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3793 break;
3794 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3795 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003796 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003797 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3798 break;
3799 }
3800 break;
3801 case ICmpInst::ICMP_SGT:
3802 switch (RHSCC) {
3803 default: assert(0 && "Unknown integer condition code!");
3804 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3805 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3806 return ReplaceInstUsesWith(I, LHS);
3807 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3808 break;
3809 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3810 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003811 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003812 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3813 break;
3814 }
3815 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003816 }
3817 }
3818 }
Chris Lattner3af10532006-05-05 06:39:07 +00003819
3820 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003821 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003822 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003823 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3824 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003825 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003826 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003827 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3828 I.getType(), TD) &&
3829 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3830 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003831 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3832 Op1C->getOperand(0),
3833 I.getName());
3834 InsertNewInstBefore(NewOp, I);
3835 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3836 }
Chris Lattner3af10532006-05-05 06:39:07 +00003837 }
Chris Lattner3af10532006-05-05 06:39:07 +00003838
Chris Lattner15212982005-09-18 03:42:07 +00003839
Chris Lattner113f4f42002-06-25 16:13:24 +00003840 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003841}
3842
Chris Lattnerc2076352004-02-16 01:20:27 +00003843// XorSelf - Implements: X ^ X --> 0
3844struct XorSelf {
3845 Value *RHS;
3846 XorSelf(Value *rhs) : RHS(rhs) {}
3847 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3848 Instruction *apply(BinaryOperator &Xor) const {
3849 return &Xor;
3850 }
3851};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003852
3853
Chris Lattner113f4f42002-06-25 16:13:24 +00003854Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003855 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003856 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003857
Chris Lattner81a7a232004-10-16 18:11:37 +00003858 if (isa<UndefValue>(Op1))
3859 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3860
Chris Lattnerc2076352004-02-16 01:20:27 +00003861 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3862 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3863 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003864 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003865 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003866
3867 // See if we can simplify any instructions used by the instruction whose sole
3868 // purpose is to compute bits we don't care about.
3869 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003870 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003871 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003872 KnownZero, KnownOne))
3873 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003874
Zhou Sheng75b871f2007-01-11 12:24:14 +00003875 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003876 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3877 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003878 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003879 return new ICmpInst(ICI->getInversePredicate(),
3880 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003881
Reid Spencer266e42b2006-12-23 06:05:41 +00003882 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003883 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003884 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3885 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003886 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3887 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003888 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003889 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003890 }
Chris Lattner023a4832004-06-18 06:07:51 +00003891
3892 // ~(~X & Y) --> (X | ~Y)
3893 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3894 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3895 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3896 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003897 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003898 Op0I->getOperand(1)->getName()+".not");
3899 InsertNewInstBefore(NotY, I);
3900 return BinaryOperator::createOr(Op0NotVal, NotY);
3901 }
3902 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003903
Chris Lattner97638592003-07-23 21:37:07 +00003904 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003905 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003906 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003907 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003908 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3909 return BinaryOperator::createSub(
3910 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003911 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003912 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003913 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003914 } else if (Op0I->getOpcode() == Instruction::Or) {
3915 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3916 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3917 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3918 // Anything in both C1 and C2 is known to be zero, remove it from
3919 // NewRHS.
3920 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3921 NewRHS = ConstantExpr::getAnd(NewRHS,
3922 ConstantExpr::getNot(CommonBits));
3923 WorkList.push_back(Op0I);
3924 I.setOperand(0, Op0I->getOperand(0));
3925 I.setOperand(1, NewRHS);
3926 return &I;
3927 }
Chris Lattner97638592003-07-23 21:37:07 +00003928 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003929 }
Chris Lattner183b3362004-04-09 19:05:30 +00003930
3931 // Try to fold constant and into select arguments.
3932 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003933 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003934 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003935 if (isa<PHINode>(Op0))
3936 if (Instruction *NV = FoldOpIntoPhi(I))
3937 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003938 }
3939
Chris Lattnerbb74e222003-03-10 23:06:50 +00003940 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003941 if (X == Op1)
3942 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003943 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003944
Chris Lattnerbb74e222003-03-10 23:06:50 +00003945 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003946 if (X == Op0)
3947 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003948 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003949
Chris Lattnerdcd07922006-04-01 08:03:55 +00003950 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003951 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003952 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003953 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003954 I.swapOperands();
3955 std::swap(Op0, Op1);
3956 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003957 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003958 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003959 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003960 } else if (Op1I->getOpcode() == Instruction::Xor) {
3961 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3962 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3963 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3964 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003965 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3966 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3967 Op1I->swapOperands();
3968 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3969 I.swapOperands(); // Simplified below.
3970 std::swap(Op0, Op1);
3971 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003972 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003973
Chris Lattnerdcd07922006-04-01 08:03:55 +00003974 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003975 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003976 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003977 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003978 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003979 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3980 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003981 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003982 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003983 } else if (Op0I->getOpcode() == Instruction::Xor) {
3984 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3985 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3986 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3987 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003988 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3989 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3990 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003991 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3992 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003993 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3994 InsertNewInstBefore(N, I);
3995 return BinaryOperator::createAnd(N, Op1);
3996 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003997 }
3998
Reid Spencer266e42b2006-12-23 06:05:41 +00003999 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4001 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004002 return R;
4003
Chris Lattner3af10532006-05-05 06:39:07 +00004004 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004005 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004006 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004007 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4008 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004009 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004010 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004011 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4012 I.getType(), TD) &&
4013 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4014 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004015 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4016 Op1C->getOperand(0),
4017 I.getName());
4018 InsertNewInstBefore(NewOp, I);
4019 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4020 }
Chris Lattner3af10532006-05-05 06:39:07 +00004021 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004022
4023 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4024 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4025 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4026 if (SI0->getOpcode() == SI1->getOpcode() &&
4027 SI0->getOperand(1) == SI1->getOperand(1) &&
4028 (SI0->hasOneUse() || SI1->hasOneUse())) {
4029 Instruction *NewOp =
4030 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4031 SI1->getOperand(0),
4032 SI0->getName()), I);
4033 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4034 }
4035 }
Chris Lattner3af10532006-05-05 06:39:07 +00004036
Chris Lattner113f4f42002-06-25 16:13:24 +00004037 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004038}
4039
Chris Lattner6862fbd2004-09-29 17:40:11 +00004040static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004041 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004042}
4043
4044/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4045/// overflowed for this type.
4046static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4047 ConstantInt *In2) {
4048 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4049
Reid Spencerc635f472006-12-31 05:48:39 +00004050 return cast<ConstantInt>(Result)->getZExtValue() <
4051 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004052}
4053
Chris Lattner0798af32005-01-13 20:14:25 +00004054/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4055/// code necessary to compute the offset from the base pointer (without adding
4056/// in the base pointer). Return the result as a signed integer of intptr size.
4057static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4058 TargetData &TD = IC.getTargetData();
4059 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004060 const Type *IntPtrTy = TD.getIntPtrType();
4061 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004062
4063 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004064 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004065
Chris Lattner0798af32005-01-13 20:14:25 +00004066 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4067 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004068 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004069 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004070 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4071 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004072 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004073 Scale = ConstantExpr::getMul(OpC, Scale);
4074 if (Constant *RC = dyn_cast<Constant>(Result))
4075 Result = ConstantExpr::getAdd(RC, Scale);
4076 else {
4077 // Emit an add instruction.
4078 Result = IC.InsertNewInstBefore(
4079 BinaryOperator::createAdd(Result, Scale,
4080 GEP->getName()+".offs"), I);
4081 }
4082 }
4083 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004084 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004085 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004086 Op->getName()+".c"), I);
4087 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004088 // We'll let instcombine(mul) convert this to a shl if possible.
4089 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4090 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004091
4092 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004093 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004094 GEP->getName()+".offs"), I);
4095 }
4096 }
4097 return Result;
4098}
4099
Reid Spencer266e42b2006-12-23 06:05:41 +00004100/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004101/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004102Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4103 ICmpInst::Predicate Cond,
4104 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004105 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004106
4107 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4108 if (isa<PointerType>(CI->getOperand(0)->getType()))
4109 RHS = CI->getOperand(0);
4110
Chris Lattner0798af32005-01-13 20:14:25 +00004111 Value *PtrBase = GEPLHS->getOperand(0);
4112 if (PtrBase == RHS) {
4113 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004114 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4115 // each index is zero or not.
4116 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004117 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004118 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4119 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004120 bool EmitIt = true;
4121 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4122 if (isa<UndefValue>(C)) // undef index -> undef.
4123 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4124 if (C->isNullValue())
4125 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004126 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4127 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004128 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004129 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004130 ConstantInt::get(Type::Int1Ty,
4131 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004132 }
4133
4134 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004135 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004136 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004137 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4138 if (InVal == 0)
4139 InVal = Comp;
4140 else {
4141 InVal = InsertNewInstBefore(InVal, I);
4142 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004143 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004144 InVal = BinaryOperator::createOr(InVal, Comp);
4145 else // True if all are equal
4146 InVal = BinaryOperator::createAnd(InVal, Comp);
4147 }
4148 }
4149 }
4150
4151 if (InVal)
4152 return InVal;
4153 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004154 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004155 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4156 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004157 }
Chris Lattner0798af32005-01-13 20:14:25 +00004158
Reid Spencer266e42b2006-12-23 06:05:41 +00004159 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004160 // the result to fold to a constant!
4161 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4162 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4163 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004164 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4165 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004166 }
4167 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004168 // If the base pointers are different, but the indices are the same, just
4169 // compare the base pointer.
4170 if (PtrBase != GEPRHS->getOperand(0)) {
4171 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004172 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004173 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004174 if (IndicesTheSame)
4175 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4176 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4177 IndicesTheSame = false;
4178 break;
4179 }
4180
4181 // If all indices are the same, just compare the base pointers.
4182 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004183 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4184 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004185
4186 // Otherwise, the base pointers are different and the indices are
4187 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004188 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004189 }
Chris Lattner0798af32005-01-13 20:14:25 +00004190
Chris Lattner81e84172005-01-13 22:25:21 +00004191 // If one of the GEPs has all zero indices, recurse.
4192 bool AllZeros = true;
4193 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4194 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4195 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4196 AllZeros = false;
4197 break;
4198 }
4199 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004200 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4201 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004202
4203 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004204 AllZeros = true;
4205 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4206 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4207 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4208 AllZeros = false;
4209 break;
4210 }
4211 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004212 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004213
Chris Lattner4fa89822005-01-14 00:20:05 +00004214 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4215 // If the GEPs only differ by one index, compare it.
4216 unsigned NumDifferences = 0; // Keep track of # differences.
4217 unsigned DiffOperand = 0; // The operand that differs.
4218 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4219 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004220 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4221 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004222 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004223 NumDifferences = 2;
4224 break;
4225 } else {
4226 if (NumDifferences++) break;
4227 DiffOperand = i;
4228 }
4229 }
4230
4231 if (NumDifferences == 0) // SAME GEP?
4232 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004233 ConstantInt::get(Type::Int1Ty,
4234 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004235 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004236 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4237 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004238 // Make sure we do a signed comparison here.
4239 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004240 }
4241 }
4242
Reid Spencer266e42b2006-12-23 06:05:41 +00004243 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004244 // the result to fold to a constant!
4245 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4246 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4247 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4248 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4249 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004250 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004251 }
4252 }
4253 return 0;
4254}
4255
Reid Spencer266e42b2006-12-23 06:05:41 +00004256Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4257 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004259
Chris Lattner6ee923f2007-01-14 19:42:17 +00004260 // Fold trivial predicates.
4261 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4262 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4263 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4264 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4265
4266 // Simplify 'fcmp pred X, X'
4267 if (Op0 == Op1) {
4268 switch (I.getPredicate()) {
4269 default: assert(0 && "Unknown predicate!");
4270 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4271 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4272 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4273 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4274 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4275 case FCmpInst::FCMP_OLT: // True if ordered and less than
4276 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4277 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4278
4279 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4280 case FCmpInst::FCMP_ULT: // True if unordered or less than
4281 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4282 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4283 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4284 I.setPredicate(FCmpInst::FCMP_UNO);
4285 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4286 return &I;
4287
4288 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4289 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4290 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4291 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4292 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4293 I.setPredicate(FCmpInst::FCMP_ORD);
4294 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4295 return &I;
4296 }
4297 }
4298
Reid Spencer266e42b2006-12-23 06:05:41 +00004299 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004300 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004301
Reid Spencer266e42b2006-12-23 06:05:41 +00004302 // Handle fcmp with constant RHS
4303 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4304 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4305 switch (LHSI->getOpcode()) {
4306 case Instruction::PHI:
4307 if (Instruction *NV = FoldOpIntoPhi(I))
4308 return NV;
4309 break;
4310 case Instruction::Select:
4311 // If either operand of the select is a constant, we can fold the
4312 // comparison into the select arms, which will cause one to be
4313 // constant folded and the select turned into a bitwise or.
4314 Value *Op1 = 0, *Op2 = 0;
4315 if (LHSI->hasOneUse()) {
4316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4317 // Fold the known value into the constant operand.
4318 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4319 // Insert a new FCmp of the other select operand.
4320 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4321 LHSI->getOperand(2), RHSC,
4322 I.getName()), I);
4323 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4324 // Fold the known value into the constant operand.
4325 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4326 // Insert a new FCmp of the other select operand.
4327 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4328 LHSI->getOperand(1), RHSC,
4329 I.getName()), I);
4330 }
4331 }
4332
4333 if (Op1)
4334 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4335 break;
4336 }
4337 }
4338
4339 return Changed ? &I : 0;
4340}
4341
4342Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4343 bool Changed = SimplifyCompare(I);
4344 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4345 const Type *Ty = Op0->getType();
4346
4347 // icmp X, X
4348 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004349 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4350 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004351
4352 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004353 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004354
4355 // icmp of GlobalValues can never equal each other as long as they aren't
4356 // external weak linkage type.
4357 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4358 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4359 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004360 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4361 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004362
4363 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004364 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004365 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4366 isa<ConstantPointerNull>(Op0)) &&
4367 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004368 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004369 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4370 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004371
Reid Spencer266e42b2006-12-23 06:05:41 +00004372 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004373 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004374 switch (I.getPredicate()) {
4375 default: assert(0 && "Invalid icmp instruction!");
4376 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004377 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004378 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004379 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004380 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004381 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004382 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004383
Reid Spencer266e42b2006-12-23 06:05:41 +00004384 case ICmpInst::ICMP_UGT:
4385 case ICmpInst::ICMP_SGT:
4386 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004387 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004388 case ICmpInst::ICMP_ULT:
4389 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004390 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4391 InsertNewInstBefore(Not, I);
4392 return BinaryOperator::createAnd(Not, Op1);
4393 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004394 case ICmpInst::ICMP_UGE:
4395 case ICmpInst::ICMP_SGE:
4396 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004397 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004398 case ICmpInst::ICMP_ULE:
4399 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004400 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4401 InsertNewInstBefore(Not, I);
4402 return BinaryOperator::createOr(Not, Op1);
4403 }
4404 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004405 }
4406
Chris Lattner2dd01742004-06-09 04:24:29 +00004407 // See if we are doing a comparison between a constant and an instruction that
4408 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004410 switch (I.getPredicate()) {
4411 default: break;
4412 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4413 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004414 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004415 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4416 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4417 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4418 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4419 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004420
Reid Spencer266e42b2006-12-23 06:05:41 +00004421 case ICmpInst::ICMP_SLT:
4422 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004423 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004424 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4425 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4426 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4427 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4428 break;
4429
4430 case ICmpInst::ICMP_UGT:
4431 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004432 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004433 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4434 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4435 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4436 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4437 break;
4438
4439 case ICmpInst::ICMP_SGT:
4440 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004441 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004442 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4443 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4444 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4445 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4446 break;
4447
4448 case ICmpInst::ICMP_ULE:
4449 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004450 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004451 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4452 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4453 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4454 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4455 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004456
Reid Spencer266e42b2006-12-23 06:05:41 +00004457 case ICmpInst::ICMP_SLE:
4458 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004459 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004460 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4461 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4462 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4463 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4464 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004465
Reid Spencer266e42b2006-12-23 06:05:41 +00004466 case ICmpInst::ICMP_UGE:
4467 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004468 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004469 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4470 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4471 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4472 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4473 break;
4474
4475 case ICmpInst::ICMP_SGE:
4476 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004477 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004478 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4479 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4480 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4481 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4482 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004483 }
4484
Reid Spencer266e42b2006-12-23 06:05:41 +00004485 // If we still have a icmp le or icmp ge instruction, turn it into the
4486 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004487 // already been handled above, this requires little checking.
4488 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004489 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4490 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4491 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4492 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4493 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4494 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4495 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4496 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004497
4498 // See if we can fold the comparison based on bits known to be zero or one
4499 // in the input.
4500 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004501 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004502 KnownZero, KnownOne, 0))
4503 return &I;
4504
4505 // Given the known and unknown bits, compute a range that the LHS could be
4506 // in.
4507 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004508 // Compute the Min, Max and RHS values based on the known bits. For the
4509 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004510 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4511 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004512 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4513 SRHSVal = CI->getSExtValue();
4514 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4515 SMax);
4516 } else {
4517 URHSVal = CI->getZExtValue();
4518 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4519 UMax);
4520 }
4521 switch (I.getPredicate()) { // LE/GE have been folded already.
4522 default: assert(0 && "Unknown icmp opcode!");
4523 case ICmpInst::ICMP_EQ:
4524 if (UMax < URHSVal || 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_NE:
4528 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004529 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 break;
4531 case ICmpInst::ICMP_ULT:
4532 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004534 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004535 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004536 break;
4537 case ICmpInst::ICMP_UGT:
4538 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004539 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004541 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 break;
4543 case ICmpInst::ICMP_SLT:
4544 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004545 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004546 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004547 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004548 break;
4549 case ICmpInst::ICMP_SGT:
4550 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004551 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004553 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004555 }
4556 }
4557
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004559 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004560 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004561 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004562 switch (LHSI->getOpcode()) {
4563 case Instruction::And:
4564 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4565 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004566 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4567
Reid Spencer266e42b2006-12-23 06:05:41 +00004568 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004569 // and/compare to be the input width without changing the value
4570 // produced, eliminating a cast.
4571 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4572 // We can do this transformation if either the AND constant does not
4573 // have its sign bit set or if it is an equality comparison.
4574 // Extending a relational comparison when we're checking the sign
4575 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004576 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004577 (I.isEquality() ||
4578 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4579 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4580 ConstantInt *NewCST;
4581 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004582 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4583 AndCST->getZExtValue());
4584 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4585 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004586 Instruction *NewAnd =
4587 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4588 LHSI->getName());
4589 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004590 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004591 }
4592 }
4593
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004594 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4595 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4596 // happens a LOT in code produced by the C front-end, for bitfield
4597 // access.
4598 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004599
4600 // Check to see if there is a noop-cast between the shift and the and.
4601 if (!Shift) {
4602 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004603 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004604 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4605 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004606
Reid Spencere0fc4df2006-10-20 07:07:24 +00004607 ConstantInt *ShAmt;
4608 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004609 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4610 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004611
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004612 // We can fold this as long as we can't shift unknown bits
4613 // into the mask. This can only happen with signed shift
4614 // rights, as they sign-extend.
4615 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004616 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004617 if (!CanFold) {
4618 // To test for the bad case of the signed shr, see if any
4619 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004620 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004621 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4622
Reid Spencerc635f472006-12-31 05:48:39 +00004623 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004624 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004625 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4626 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004627 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4628 CanFold = true;
4629 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004630
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004631 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004632 Constant *NewCst;
4633 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004634 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004635 else
4636 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004637
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004638 // Check to see if we are shifting out any of the bits being
4639 // compared.
4640 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4641 // If we shifted bits out, the fold is not going to work out.
4642 // As a special case, check to see if this means that the
4643 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004644 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004645 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004646 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004647 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004648 } else {
4649 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004650 Constant *NewAndCST;
4651 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004652 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004653 else
4654 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4655 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004656 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004657 WorkList.push_back(Shift); // Shift is dead.
4658 AddUsesToWorkList(I);
4659 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004660 }
4661 }
Chris Lattner35167c32004-06-09 07:59:58 +00004662 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004663
4664 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4665 // preferable because it allows the C<<Y expression to be hoisted out
4666 // of a loop if Y is invariant and X is not.
4667 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004668 I.isEquality() && !Shift->isArithmeticShift() &&
4669 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004670 // Compute C << Y.
4671 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004672 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004673 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4674 "tmp");
4675 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004676 // Insert a logical shift.
4677 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004678 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004679 }
4680 InsertNewInstBefore(cast<Instruction>(NS), I);
4681
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004682 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004683 Instruction *NewAnd = BinaryOperator::createAnd(
4684 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004685 InsertNewInstBefore(NewAnd, I);
4686
4687 I.setOperand(0, NewAnd);
4688 return &I;
4689 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004690 }
4691 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004692
Reid Spencer266e42b2006-12-23 06:05:41 +00004693 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004694 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004695 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004696 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4697
4698 // Check that the shift amount is in range. If not, don't perform
4699 // undefined shifts. When the shift is visited it will be
4700 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004701 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004702 break;
4703
Chris Lattner272d5ca2004-09-28 18:22:15 +00004704 // If we are comparing against bits always shifted out, the
4705 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004706 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004707 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004708 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004709 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004710 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004711 return ReplaceInstUsesWith(I, Cst);
4712 }
4713
4714 if (LHSI->hasOneUse()) {
4715 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004716 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004717 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004718 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004719
Chris Lattner272d5ca2004-09-28 18:22:15 +00004720 Instruction *AndI =
4721 BinaryOperator::createAnd(LHSI->getOperand(0),
4722 Mask, LHSI->getName()+".mask");
4723 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004724 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004725 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004726 }
4727 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004728 }
4729 break;
4730
Reid Spencer266e42b2006-12-23 06:05:41 +00004731 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004732 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004733 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004734 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004735 // Check that the shift amount is in range. If not, don't perform
4736 // undefined shifts. When the shift is visited it will be
4737 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004738 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004739 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004740 break;
4741
Chris Lattner1023b872004-09-27 16:18:50 +00004742 // If we are comparing against bits always shifted out, the
4743 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004744 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004745 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004746 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4747 ShAmt);
4748 else
4749 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4750 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004751
Chris Lattner1023b872004-09-27 16:18:50 +00004752 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004753 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004754 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004755 return ReplaceInstUsesWith(I, Cst);
4756 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004757
Chris Lattner1023b872004-09-27 16:18:50 +00004758 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004759 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004760
Chris Lattner1023b872004-09-27 16:18:50 +00004761 // Otherwise strength reduce the shift into an and.
4762 uint64_t Val = ~0ULL; // All ones.
4763 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004764 Val &= ~0ULL >> (64-TypeBits);
4765 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004766
Chris Lattner1023b872004-09-27 16:18:50 +00004767 Instruction *AndI =
4768 BinaryOperator::createAnd(LHSI->getOperand(0),
4769 Mask, LHSI->getName()+".mask");
4770 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004771 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004772 ConstantExpr::getShl(CI, ShAmt));
4773 }
Chris Lattner1023b872004-09-27 16:18:50 +00004774 }
4775 }
4776 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004777
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004778 case Instruction::SDiv:
4779 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004780 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004781 // Fold this div into the comparison, producing a range check.
4782 // Determine, based on the divide type, what the range is being
4783 // checked. If there is an overflow on the low or high side, remember
4784 // it, otherwise compute the range [low, hi) bounding the new value.
4785 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004786 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004787 // FIXME: If the operand types don't match the type of the divide
4788 // then don't attempt this transform. The code below doesn't have the
4789 // logic to deal with a signed divide and an unsigned compare (and
4790 // vice versa). This is because (x /s C1) <s C2 produces different
4791 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4792 // (x /u C1) <u C2. Simply casting the operands and result won't
4793 // work. :( The if statement below tests that condition and bails
4794 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004795 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4796 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004797 break;
4798
4799 // Initialize the variables that will indicate the nature of the
4800 // range check.
4801 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004802 ConstantInt *LoBound = 0, *HiBound = 0;
4803
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004804 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4805 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4806 // C2 (CI). By solving for X we can turn this into a range check
4807 // instead of computing a divide.
4808 ConstantInt *Prod =
4809 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004810
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004811 // Determine if the product overflows by seeing if the product is
4812 // not equal to the divide. Make sure we do the same kind of divide
4813 // as in the LHS instruction that we're folding.
4814 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004815 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004816 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4817
Reid Spencer266e42b2006-12-23 06:05:41 +00004818 // Get the ICmp opcode
4819 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004820
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004821 if (DivRHS->isNullValue()) {
4822 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004823 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004824 LoBound = Prod;
4825 LoOverflow = ProdOV;
4826 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004827 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004828 if (CI->isNullValue()) { // (X / pos) op 0
4829 // Can't overflow.
4830 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4831 HiBound = DivRHS;
4832 } else if (isPositive(CI)) { // (X / pos) op pos
4833 LoBound = Prod;
4834 LoOverflow = ProdOV;
4835 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4836 } else { // (X / pos) op neg
4837 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4838 LoOverflow = AddWithOverflow(LoBound, Prod,
4839 cast<ConstantInt>(DivRHSH));
4840 HiBound = Prod;
4841 HiOverflow = ProdOV;
4842 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004843 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004844 if (CI->isNullValue()) { // (X / neg) op 0
4845 LoBound = AddOne(DivRHS);
4846 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004847 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004848 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004849 } else if (isPositive(CI)) { // (X / neg) op pos
4850 HiOverflow = LoOverflow = ProdOV;
4851 if (!LoOverflow)
4852 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4853 HiBound = AddOne(Prod);
4854 } else { // (X / neg) op neg
4855 LoBound = Prod;
4856 LoOverflow = HiOverflow = ProdOV;
4857 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4858 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004859
Chris Lattnera92af962004-10-11 19:40:04 +00004860 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004861 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004862 }
4863
4864 if (LoBound) {
4865 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004866 switch (predicate) {
4867 default: assert(0 && "Unhandled icmp opcode!");
4868 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004869 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004870 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004871 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004872 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4873 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004874 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004875 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4876 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004877 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004878 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4879 true, I);
4880 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004881 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004882 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004883 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004884 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4885 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004886 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004887 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4888 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004889 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004890 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4891 false, I);
4892 case ICmpInst::ICMP_ULT:
4893 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004894 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004895 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004896 return new ICmpInst(predicate, X, LoBound);
4897 case ICmpInst::ICMP_UGT:
4898 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004899 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004901 if (predicate == ICmpInst::ICMP_UGT)
4902 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4903 else
4904 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004905 }
4906 }
4907 }
4908 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004909 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004910
Reid Spencer266e42b2006-12-23 06:05:41 +00004911 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004912 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004913 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004914
Reid Spencere0fc4df2006-10-20 07:07:24 +00004915 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4916 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4918 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004919 case Instruction::SRem:
4920 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4921 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4922 BO->hasOneUse()) {
4923 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4924 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004925 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4926 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004927 return new ICmpInst(I.getPredicate(), NewRem,
4928 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004929 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004930 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004931 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004932 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004933 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4934 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004935 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004936 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4937 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004938 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004939 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4940 // efficiently invertible, or if the add has just this one use.
4941 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004942
Chris Lattnerc992add2003-08-13 05:33:12 +00004943 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004944 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004945 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004946 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004947 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004948 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4949 BO->setName("");
4950 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004951 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004952 }
4953 }
4954 break;
4955 case Instruction::Xor:
4956 // For the xor case, we can xor two constants together, eliminating
4957 // the explicit xor.
4958 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004959 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4960 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004961
4962 // FALLTHROUGH
4963 case Instruction::Sub:
4964 // Replace (([sub|xor] A, B) != 0) with (A != B)
4965 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004966 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4967 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004968 break;
4969
4970 case Instruction::Or:
4971 // If bits are being or'd in that are not present in the constant we
4972 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004973 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004974 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004975 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004976 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4977 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004978 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004979 break;
4980
4981 case Instruction::And:
4982 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004983 // If bits are being compared against that are and'd out, then the
4984 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004985 if (!ConstantExpr::getAnd(CI,
4986 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004987 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4988 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004989
Chris Lattner35167c32004-06-09 07:59:58 +00004990 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004991 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004992 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4993 ICmpInst::ICMP_NE, Op0,
4994 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004995
Reid Spencer266e42b2006-12-23 06:05:41 +00004996 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00004997 if (isSignBit(BOC)) {
4998 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004999 Constant *Zero = Constant::getNullValue(X->getType());
5000 ICmpInst::Predicate pred = isICMP_NE ?
5001 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5002 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005003 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005004
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005005 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005006 if (CI->isNullValue() && isHighOnes(BOC)) {
5007 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005008 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005009 ICmpInst::Predicate pred = isICMP_NE ?
5010 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5011 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005012 }
5013
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005014 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005015 default: break;
5016 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005017 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5018 // Handle set{eq|ne} <intrinsic>, intcst.
5019 switch (II->getIntrinsicID()) {
5020 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005021 case Intrinsic::bswap_i16:
5022 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005023 WorkList.push_back(II); // Dead?
5024 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005025 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005026 ByteSwap_16(CI->getZExtValue())));
5027 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005028 case Intrinsic::bswap_i32:
5029 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005030 WorkList.push_back(II); // Dead?
5031 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005032 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005033 ByteSwap_32(CI->getZExtValue())));
5034 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005035 case Intrinsic::bswap_i64:
5036 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005037 WorkList.push_back(II); // Dead?
5038 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005039 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005040 ByteSwap_64(CI->getZExtValue())));
5041 return &I;
5042 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005043 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005044 } else { // Not a ICMP_EQ/ICMP_NE
5045 // If the LHS is a cast from an integral value of the same size, then
5046 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005047 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5048 Value *CastOp = Cast->getOperand(0);
5049 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005050 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005051 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005052 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005053 // If this is an unsigned comparison, try to make the comparison use
5054 // smaller constant values.
5055 switch (I.getPredicate()) {
5056 default: break;
5057 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5058 ConstantInt *CUI = cast<ConstantInt>(CI);
5059 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5060 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5061 ConstantInt::get(SrcTy, -1));
5062 break;
5063 }
5064 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5065 ConstantInt *CUI = cast<ConstantInt>(CI);
5066 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5067 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5068 Constant::getNullValue(SrcTy));
5069 break;
5070 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005071 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005072
Chris Lattner2b55ea32004-02-23 07:16:20 +00005073 }
5074 }
Chris Lattnere967b342003-06-04 05:10:11 +00005075 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005076 }
5077
Reid Spencer266e42b2006-12-23 06:05:41 +00005078 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005079 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5080 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5081 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005082 case Instruction::GetElementPtr:
5083 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005084 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005085 bool isAllZeros = true;
5086 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5087 if (!isa<Constant>(LHSI->getOperand(i)) ||
5088 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5089 isAllZeros = false;
5090 break;
5091 }
5092 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005093 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005094 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5095 }
5096 break;
5097
Chris Lattner77c32c32005-04-23 15:31:55 +00005098 case Instruction::PHI:
5099 if (Instruction *NV = FoldOpIntoPhi(I))
5100 return NV;
5101 break;
5102 case Instruction::Select:
5103 // If either operand of the select is a constant, we can fold the
5104 // comparison into the select arms, which will cause one to be
5105 // constant folded and the select turned into a bitwise or.
5106 Value *Op1 = 0, *Op2 = 0;
5107 if (LHSI->hasOneUse()) {
5108 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5109 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005110 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5111 // Insert a new ICmp of the other select operand.
5112 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5113 LHSI->getOperand(2), RHSC,
5114 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005115 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5116 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005117 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5118 // Insert a new ICmp of the other select operand.
5119 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5120 LHSI->getOperand(1), RHSC,
5121 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005122 }
5123 }
Jeff Cohen82639852005-04-23 21:38:35 +00005124
Chris Lattner77c32c32005-04-23 15:31:55 +00005125 if (Op1)
5126 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5127 break;
5128 }
5129 }
5130
Reid Spencer266e42b2006-12-23 06:05:41 +00005131 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005132 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005133 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005134 return NI;
5135 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005136 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5137 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005138 return NI;
5139
Reid Spencer266e42b2006-12-23 06:05:41 +00005140 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005141 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5142 // now.
5143 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5144 if (isa<PointerType>(Op0->getType()) &&
5145 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005146 // We keep moving the cast from the left operand over to the right
5147 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005148 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005149
Chris Lattner64d87b02007-01-06 01:45:59 +00005150 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5151 // so eliminate it as well.
5152 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5153 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005154
Chris Lattner16930792003-11-03 04:25:02 +00005155 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005156 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005157 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005158 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005159 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005160 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005161 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005162 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005163 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005164 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005165 }
5166
5167 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005168 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005169 // This comes up when you have code like
5170 // int X = A < B;
5171 // if (X) ...
5172 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005173 // with a constant or another cast from the same type.
5174 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005175 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005176 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005177 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005178
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005179 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005180 Value *A, *B, *C, *D;
5181 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5182 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5183 Value *OtherVal = A == Op1 ? B : A;
5184 return new ICmpInst(I.getPredicate(), OtherVal,
5185 Constant::getNullValue(A->getType()));
5186 }
5187
5188 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5189 // A^c1 == C^c2 --> A == C^(c1^c2)
5190 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5191 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5192 if (Op1->hasOneUse()) {
5193 Constant *NC = ConstantExpr::getXor(C1, C2);
5194 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5195 return new ICmpInst(I.getPredicate(), A,
5196 InsertNewInstBefore(Xor, I));
5197 }
5198
5199 // A^B == A^D -> B == D
5200 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5201 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5202 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5203 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5204 }
5205 }
5206
5207 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5208 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005209 // A == (A^B) -> B == 0
5210 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005211 return new ICmpInst(I.getPredicate(), OtherVal,
5212 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005213 }
5214 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005215 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005216 return new ICmpInst(I.getPredicate(), B,
5217 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005218 }
5219 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005220 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 return new ICmpInst(I.getPredicate(), B,
5222 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005223 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005224
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005225 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5226 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5227 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5228 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5229 Value *X = 0, *Y = 0, *Z = 0;
5230
5231 if (A == C) {
5232 X = B; Y = D; Z = A;
5233 } else if (A == D) {
5234 X = B; Y = C; Z = A;
5235 } else if (B == C) {
5236 X = A; Y = D; Z = B;
5237 } else if (B == D) {
5238 X = A; Y = C; Z = B;
5239 }
5240
5241 if (X) { // Build (X^Y) & Z
5242 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5243 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5244 I.setOperand(0, Op1);
5245 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5246 return &I;
5247 }
5248 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005249 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005250 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005251}
5252
Reid Spencer266e42b2006-12-23 06:05:41 +00005253// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005254// We only handle extending casts so far.
5255//
Reid Spencer266e42b2006-12-23 06:05:41 +00005256Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5257 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005258 Value *LHSCIOp = LHSCI->getOperand(0);
5259 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005260 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005261 Value *RHSCIOp;
5262
Reid Spencer266e42b2006-12-23 06:05:41 +00005263 // We only handle extension cast instructions, so far. Enforce this.
5264 if (LHSCI->getOpcode() != Instruction::ZExt &&
5265 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005266 return 0;
5267
Reid Spencer266e42b2006-12-23 06:05:41 +00005268 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5269 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005270
Reid Spencer266e42b2006-12-23 06:05:41 +00005271 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005272 // Not an extension from the same type?
5273 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005274 if (RHSCIOp->getType() != LHSCIOp->getType())
5275 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005276
5277 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5278 // and the other is a zext), then we can't handle this.
5279 if (CI->getOpcode() != LHSCI->getOpcode())
5280 return 0;
5281
5282 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5283 // then we can't handle this.
5284 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5285 return 0;
5286
5287 // Okay, just insert a compare of the reduced operands now!
5288 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005289 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005290
Reid Spencer266e42b2006-12-23 06:05:41 +00005291 // If we aren't dealing with a constant on the RHS, exit early
5292 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5293 if (!CI)
5294 return 0;
5295
5296 // Compute the constant that would happen if we truncated to SrcTy then
5297 // reextended to DestTy.
5298 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5299 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5300
5301 // If the re-extended constant didn't change...
5302 if (Res2 == CI) {
5303 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5304 // For example, we might have:
5305 // %A = sext short %X to uint
5306 // %B = icmp ugt uint %A, 1330
5307 // It is incorrect to transform this into
5308 // %B = icmp ugt short %X, 1330
5309 // because %A may have negative value.
5310 //
5311 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5312 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005313 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005314 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5315 else
5316 return 0;
5317 }
5318
5319 // The re-extended constant changed so the constant cannot be represented
5320 // in the shorter type. Consequently, we cannot emit a simple comparison.
5321
5322 // First, handle some easy cases. We know the result cannot be equal at this
5323 // point so handle the ICI.isEquality() cases
5324 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005325 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005326 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005327 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005328
5329 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5330 // should have been folded away previously and not enter in here.
5331 Value *Result;
5332 if (isSignedCmp) {
5333 // We're performing a signed comparison.
5334 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005335 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005336 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005337 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005338 } else {
5339 // We're performing an unsigned comparison.
5340 if (isSignedExt) {
5341 // We're performing an unsigned comp with a sign extended value.
5342 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005343 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005344 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5345 NegOne, ICI.getName()), ICI);
5346 } else {
5347 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005348 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005349 }
5350 }
5351
5352 // Finally, return the value computed.
5353 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5354 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5355 return ReplaceInstUsesWith(ICI, Result);
5356 } else {
5357 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5358 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5359 "ICmp should be folded!");
5360 if (Constant *CI = dyn_cast<Constant>(Result))
5361 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5362 else
5363 return BinaryOperator::createNot(Result);
5364 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005365}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005366
Chris Lattnere8d6c602003-03-10 19:16:08 +00005367Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005368 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005369 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005370
5371 // shl X, 0 == X and shr X, 0 == X
5372 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005373 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005374 Op0 == Constant::getNullValue(Op0->getType()))
5375 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005376
Reid Spencer266e42b2006-12-23 06:05:41 +00005377 if (isa<UndefValue>(Op0)) {
5378 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005379 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005380 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005381 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5382 }
5383 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005384 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5385 return ReplaceInstUsesWith(I, Op0);
5386 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005387 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005388 }
5389
Chris Lattnerd4dee402006-11-10 23:38:52 +00005390 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5391 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005392 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005393 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005394 return ReplaceInstUsesWith(I, CSI);
5395
Chris Lattner183b3362004-04-09 19:05:30 +00005396 // Try to fold constant and into select arguments.
5397 if (isa<Constant>(Op0))
5398 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005399 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005400 return R;
5401
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005402 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005403 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005404 if (MaskedValueIsZero(Op0,
5405 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005406 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005407 }
5408 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005409
Reid Spencere0fc4df2006-10-20 07:07:24 +00005410 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005411 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5412 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005413 return 0;
5414}
5415
Reid Spencere0fc4df2006-10-20 07:07:24 +00005416Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005417 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005418 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5419 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005420 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005421
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005422 // See if we can simplify any instructions used by the instruction whose sole
5423 // purpose is to compute bits we don't care about.
5424 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005425 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005426 KnownZero, KnownOne))
5427 return &I;
5428
Chris Lattner14553932006-01-06 07:12:35 +00005429 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5430 // of a signed value.
5431 //
5432 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005433 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005434 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005435 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5436 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005437 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005438 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005439 }
Chris Lattner14553932006-01-06 07:12:35 +00005440 }
5441
5442 // ((X*C1) << C2) == (X * (C1 << C2))
5443 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5444 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5445 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5446 return BinaryOperator::createMul(BO->getOperand(0),
5447 ConstantExpr::getShl(BOOp, Op1));
5448
5449 // Try to fold constant and into select arguments.
5450 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5452 return R;
5453 if (isa<PHINode>(Op0))
5454 if (Instruction *NV = FoldOpIntoPhi(I))
5455 return NV;
5456
5457 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005458 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5459 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5460 Value *V1, *V2;
5461 ConstantInt *CC;
5462 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005463 default: break;
5464 case Instruction::Add:
5465 case Instruction::And:
5466 case Instruction::Or:
5467 case Instruction::Xor:
5468 // These operators commute.
5469 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005470 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5471 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005472 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005473 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005474 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005475 Op0BO->getName());
5476 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005477 Instruction *X =
5478 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5479 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005480 InsertNewInstBefore(X, I); // (X + (Y << C))
5481 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005482 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005483 return BinaryOperator::createAnd(X, C2);
5484 }
Chris Lattner14553932006-01-06 07:12:35 +00005485
Chris Lattner797dee72005-09-18 06:30:59 +00005486 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5487 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5488 match(Op0BO->getOperand(1),
5489 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005490 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005491 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005492 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005493 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005494 Op0BO->getName());
5495 InsertNewInstBefore(YS, I); // (Y << C)
5496 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005497 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005498 V1->getName()+".mask");
5499 InsertNewInstBefore(XM, I); // X & (CC << C)
5500
5501 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5502 }
Chris Lattner14553932006-01-06 07:12:35 +00005503
Chris Lattner797dee72005-09-18 06:30:59 +00005504 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005505 case Instruction::Sub:
5506 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005507 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5508 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005509 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005510 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005511 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005512 Op0BO->getName());
5513 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005514 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005515 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005516 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005517 InsertNewInstBefore(X, I); // (X + (Y << C))
5518 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005519 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005520 return BinaryOperator::createAnd(X, C2);
5521 }
Chris Lattner14553932006-01-06 07:12:35 +00005522
Chris Lattner1df0e982006-05-31 21:14:00 +00005523 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005524 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5525 match(Op0BO->getOperand(0),
5526 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005527 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005528 cast<BinaryOperator>(Op0BO->getOperand(0))
5529 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005530 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005531 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005532 Op0BO->getName());
5533 InsertNewInstBefore(YS, I); // (Y << C)
5534 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005535 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005536 V1->getName()+".mask");
5537 InsertNewInstBefore(XM, I); // X & (CC << C)
5538
Chris Lattner1df0e982006-05-31 21:14:00 +00005539 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005540 }
Chris Lattner14553932006-01-06 07:12:35 +00005541
Chris Lattner27cb9db2005-09-18 05:12:10 +00005542 break;
Chris Lattner14553932006-01-06 07:12:35 +00005543 }
5544
5545
5546 // If the operand is an bitwise operator with a constant RHS, and the
5547 // shift is the only use, we can pull it out of the shift.
5548 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5549 bool isValid = true; // Valid only for And, Or, Xor
5550 bool highBitSet = false; // Transform if high bit of constant set?
5551
5552 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005553 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005554 case Instruction::Add:
5555 isValid = isLeftShift;
5556 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005557 case Instruction::Or:
5558 case Instruction::Xor:
5559 highBitSet = false;
5560 break;
5561 case Instruction::And:
5562 highBitSet = true;
5563 break;
Chris Lattner14553932006-01-06 07:12:35 +00005564 }
5565
5566 // If this is a signed shift right, and the high bit is modified
5567 // by the logical operation, do not perform the transformation.
5568 // The highBitSet boolean indicates the value of the high bit of
5569 // the constant which would cause it to be modified for this
5570 // operation.
5571 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005572 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005573 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005574 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5575 }
5576
5577 if (isValid) {
5578 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5579
5580 Instruction *NewShift =
5581 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5582 Op0BO->getName());
5583 Op0BO->setName("");
5584 InsertNewInstBefore(NewShift, I);
5585
5586 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5587 NewRHS);
5588 }
5589 }
5590 }
5591 }
5592
Chris Lattnereb372a02006-01-06 07:52:12 +00005593 // Find out if this is a shift of a shift by a constant.
5594 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005595 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005596 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005597 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5598 // If this is a noop-integer cast of a shift instruction, use the shift.
5599 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005600 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5601 }
5602 }
5603
Reid Spencere0fc4df2006-10-20 07:07:24 +00005604 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005605 // Find the operands and properties of the input shift. Note that the
5606 // signedness of the input shift may differ from the current shift if there
5607 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005608 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5609 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005610 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005611
Reid Spencere0fc4df2006-10-20 07:07:24 +00005612 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005613
Reid Spencere0fc4df2006-10-20 07:07:24 +00005614 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5615 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005616
5617 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5618 if (isLeftShift == isShiftOfLeftShift) {
5619 // Do not fold these shifts if the first one is signed and the second one
5620 // is unsigned and this is a right shift. Further, don't do any folding
5621 // on them.
5622 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5623 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005624
Chris Lattnereb372a02006-01-06 07:52:12 +00005625 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5626 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5627 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005628
Chris Lattnereb372a02006-01-06 07:52:12 +00005629 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005630 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005631 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005632 if (I.getType() == ShiftResult->getType())
5633 return ShiftResult;
5634 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005635 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005636 }
5637
5638 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5639 // signed types, we can only support the (A >> c1) << c2 configuration,
5640 // because it can not turn an arbitrary bit of A into a sign bit.
5641 if (isUnsignedShift || isLeftShift) {
5642 // Calculate bitmask for what gets shifted off the edge.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005643 Constant *C = ConstantInt::getAllOnesValue(I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005644 if (isLeftShift)
5645 C = ConstantExpr::getShl(C, ShiftAmt1C);
5646 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005647 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005648
5649 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005650
5651 Instruction *Mask =
5652 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5653 InsertNewInstBefore(Mask, I);
5654
5655 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005656 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005657 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005658 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005659 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005660 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005661 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5662 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005663 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005664 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005665 } else {
5666 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005667 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005668 }
5669 } else {
5670 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005671 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005672 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005673 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005674 InsertNewInstBefore(Shift, I);
5675
Zhou Sheng75b871f2007-01-11 12:24:14 +00005676 C = ConstantInt::getAllOnesValue(Shift->getType());
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005677 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005678 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005679 }
5680 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005681 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005682 // this case, C1 == C2 and C1 is 8, 16, or 32.
5683 if (ShiftAmt1 == ShiftAmt2) {
5684 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005685 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005686 case 8 : SExtType = Type::Int8Ty; break;
5687 case 16: SExtType = Type::Int16Ty; break;
5688 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005689 }
5690
5691 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005692 Instruction *NewTrunc =
5693 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005694 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005695 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005696 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005697 }
Chris Lattner86102b82005-01-01 16:22:27 +00005698 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005699 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005700 return 0;
5701}
5702
Chris Lattner48a44f72002-05-02 17:06:02 +00005703
Chris Lattner8f663e82005-10-29 04:36:15 +00005704/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5705/// expression. If so, decompose it, returning some value X, such that Val is
5706/// X*Scale+Offset.
5707///
5708static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5709 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005710 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005712 Offset = CI->getZExtValue();
5713 Scale = 1;
5714 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005715 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5716 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005717 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005718 if (I->getOpcode() == Instruction::Shl) {
5719 // This is a value scaled by '1 << the shift amt'.
5720 Scale = 1U << CUI->getZExtValue();
5721 Offset = 0;
5722 return I->getOperand(0);
5723 } else if (I->getOpcode() == Instruction::Mul) {
5724 // This value is scaled by 'CUI'.
5725 Scale = CUI->getZExtValue();
5726 Offset = 0;
5727 return I->getOperand(0);
5728 } else if (I->getOpcode() == Instruction::Add) {
5729 // We have X+C. Check to see if we really have (X*C2)+C1,
5730 // where C1 is divisible by C2.
5731 unsigned SubScale;
5732 Value *SubVal =
5733 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5734 Offset += CUI->getZExtValue();
5735 if (SubScale > 1 && (Offset % SubScale == 0)) {
5736 Scale = SubScale;
5737 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005738 }
5739 }
5740 }
5741 }
5742 }
5743
5744 // Otherwise, we can't look past this.
5745 Scale = 1;
5746 Offset = 0;
5747 return Val;
5748}
5749
5750
Chris Lattner216be912005-10-24 06:03:58 +00005751/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5752/// try to eliminate the cast by moving the type information into the alloc.
5753Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5754 AllocationInst &AI) {
5755 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005756 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005757
Chris Lattnerac87beb2005-10-24 06:22:12 +00005758 // Remove any uses of AI that are dead.
5759 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5760 std::vector<Instruction*> DeadUsers;
5761 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5762 Instruction *User = cast<Instruction>(*UI++);
5763 if (isInstructionTriviallyDead(User)) {
5764 while (UI != E && *UI == User)
5765 ++UI; // If this instruction uses AI more than once, don't break UI.
5766
5767 // Add operands to the worklist.
5768 AddUsesToWorkList(*User);
5769 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005770 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005771
5772 User->eraseFromParent();
5773 removeFromWorkList(User);
5774 }
5775 }
5776
Chris Lattner216be912005-10-24 06:03:58 +00005777 // Get the type really allocated and the type casted to.
5778 const Type *AllocElTy = AI.getAllocatedType();
5779 const Type *CastElTy = PTy->getElementType();
5780 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005781
Chris Lattner50ee0e42007-01-20 22:35:55 +00005782 unsigned AllocElTyAlign = TD->getTypeAlignmentABI(AllocElTy);
5783 unsigned CastElTyAlign = TD->getTypeAlignmentABI(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005784 if (CastElTyAlign < AllocElTyAlign) return 0;
5785
Chris Lattner46705b22005-10-24 06:35:18 +00005786 // If the allocation has multiple uses, only promote it if we are strictly
5787 // increasing the alignment of the resultant allocation. If we keep it the
5788 // same, we open the door to infinite loops of various kinds.
5789 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5790
Chris Lattner216be912005-10-24 06:03:58 +00005791 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5792 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005793 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005794
Chris Lattner8270c332005-10-29 03:19:53 +00005795 // See if we can satisfy the modulus by pulling a scale out of the array
5796 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005797 unsigned ArraySizeScale, ArrayOffset;
5798 Value *NumElements = // See if the array size is a decomposable linear expr.
5799 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5800
Chris Lattner8270c332005-10-29 03:19:53 +00005801 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5802 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005803 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5804 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005805
Chris Lattner8270c332005-10-29 03:19:53 +00005806 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5807 Value *Amt = 0;
5808 if (Scale == 1) {
5809 Amt = NumElements;
5810 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005811 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005812 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5813 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005814 Amt = ConstantExpr::getMul(
5815 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5816 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005817 else if (Scale != 1) {
5818 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5819 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005820 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005821 }
5822
Chris Lattner8f663e82005-10-29 04:36:15 +00005823 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005824 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005825 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5826 Amt = InsertNewInstBefore(Tmp, AI);
5827 }
5828
Chris Lattner216be912005-10-24 06:03:58 +00005829 std::string Name = AI.getName(); AI.setName("");
5830 AllocationInst *New;
5831 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005832 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005833 else
Nate Begeman848622f2005-11-05 09:21:28 +00005834 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005835 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005836
5837 // If the allocation has multiple uses, insert a cast and change all things
5838 // that used it to use the new cast. This will also hack on CI, but it will
5839 // die soon.
5840 if (!AI.hasOneUse()) {
5841 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005842 // New is the allocation instruction, pointer typed. AI is the original
5843 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5844 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005845 InsertNewInstBefore(NewCast, AI);
5846 AI.replaceAllUsesWith(NewCast);
5847 }
Chris Lattner216be912005-10-24 06:03:58 +00005848 return ReplaceInstUsesWith(CI, New);
5849}
5850
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005851/// CanEvaluateInDifferentType - Return true if we can take the specified value
5852/// and return it without inserting any new casts. This is used by code that
5853/// tries to decide whether promoting or shrinking integer operations to wider
5854/// or smaller types will allow us to eliminate a truncate or extend.
5855static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5856 int &NumCastsRemoved) {
5857 if (isa<Constant>(V)) return true;
5858
5859 Instruction *I = dyn_cast<Instruction>(V);
5860 if (!I || !I->hasOneUse()) return false;
5861
5862 switch (I->getOpcode()) {
5863 case Instruction::And:
5864 case Instruction::Or:
5865 case Instruction::Xor:
5866 // These operators can all arbitrarily be extended or truncated.
5867 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5868 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005869 case Instruction::AShr:
5870 case Instruction::LShr:
5871 case Instruction::Shl:
5872 // If this is just a bitcast changing the sign of the operation, we can
5873 // convert if the operand can be converted.
5874 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5875 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5876 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005877 case Instruction::Trunc:
5878 case Instruction::ZExt:
5879 case Instruction::SExt:
5880 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005881 // If this is a cast from the destination type, we can trivially eliminate
5882 // it, and this will remove a cast overall.
5883 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005884 // If the first operand is itself a cast, and is eliminable, do not count
5885 // this as an eliminable cast. We would prefer to eliminate those two
5886 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005887 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005888 return true;
5889
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005890 ++NumCastsRemoved;
5891 return true;
5892 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005893 break;
5894 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005895 // TODO: Can handle more cases here.
5896 break;
5897 }
5898
5899 return false;
5900}
5901
5902/// EvaluateInDifferentType - Given an expression that
5903/// CanEvaluateInDifferentType returns true for, actually insert the code to
5904/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005905Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5906 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005907 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005908 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005909
5910 // Otherwise, it must be an instruction.
5911 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005912 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005913 switch (I->getOpcode()) {
5914 case Instruction::And:
5915 case Instruction::Or:
5916 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005917 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5918 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005919 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5920 LHS, RHS, I->getName());
5921 break;
5922 }
Chris Lattner960acb02006-11-29 07:18:39 +00005923 case Instruction::AShr:
5924 case Instruction::LShr:
5925 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005926 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005927 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5928 I->getOperand(1), I->getName());
5929 break;
5930 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005931 case Instruction::Trunc:
5932 case Instruction::ZExt:
5933 case Instruction::SExt:
5934 case Instruction::BitCast:
5935 // If the source type of the cast is the type we're trying for then we can
5936 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005937 if (I->getOperand(0)->getType() == Ty)
5938 return I->getOperand(0);
5939
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005940 // Some other kind of cast, which shouldn't happen, so just ..
5941 // FALL THROUGH
5942 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005943 // TODO: Can handle more cases here.
5944 assert(0 && "Unreachable!");
5945 break;
5946 }
5947
5948 return InsertNewInstBefore(Res, *I);
5949}
5950
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005951/// @brief Implement the transforms common to all CastInst visitors.
5952Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005953 Value *Src = CI.getOperand(0);
5954
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005955 // Casting undef to anything results in undef so might as just replace it and
5956 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005957 if (isa<UndefValue>(Src)) // cast undef -> undef
5958 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5959
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005960 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5961 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005962 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005963 if (Instruction::CastOps opc =
5964 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5965 // The first cast (CSrc) is eliminable so we need to fix up or replace
5966 // the second cast (CI). CSrc will then have a good chance of being dead.
5967 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005968 }
5969 }
Chris Lattner03841652004-05-25 04:29:21 +00005970
Chris Lattnerd0d51602003-06-21 23:12:02 +00005971 // If casting the result of a getelementptr instruction with no offset, turn
5972 // this into a cast of the original pointer!
5973 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005974 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005975 bool AllZeroOperands = true;
5976 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5977 if (!isa<Constant>(GEP->getOperand(i)) ||
5978 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5979 AllZeroOperands = false;
5980 break;
5981 }
5982 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005983 // Changing the cast operand is usually not a good idea but it is safe
5984 // here because the pointer operand is being replaced with another
5985 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005986 CI.setOperand(0, GEP->getOperand(0));
5987 return &CI;
5988 }
5989 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005990
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005991 // If we are casting a malloc or alloca to a pointer to a type of the same
5992 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005993 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005994 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5995 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005996
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005997 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005998 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5999 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6000 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006001
6002 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006003 if (isa<PHINode>(Src))
6004 if (Instruction *NV = FoldOpIntoPhi(CI))
6005 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006006
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006007 return 0;
6008}
6009
6010/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6011/// integers. This function implements the common transforms for all those
6012/// cases.
6013/// @brief Implement the transforms common to CastInst with integer operands
6014Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6015 if (Instruction *Result = commonCastTransforms(CI))
6016 return Result;
6017
6018 Value *Src = CI.getOperand(0);
6019 const Type *SrcTy = Src->getType();
6020 const Type *DestTy = CI.getType();
6021 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6022 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6023
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006024 // See if we can simplify any instructions used by the LHS whose sole
6025 // purpose is to compute bits we don't care about.
6026 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006027 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006028 KnownZero, KnownOne))
6029 return &CI;
6030
6031 // If the source isn't an instruction or has more than one use then we
6032 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006033 Instruction *SrcI = dyn_cast<Instruction>(Src);
6034 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006035 return 0;
6036
6037 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006038 int NumCastsRemoved = 0;
6039 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6040 // If this cast is a truncate, evaluting in a different type always
6041 // eliminates the cast, so it is always a win. If this is a noop-cast
6042 // this just removes a noop cast which isn't pointful, but simplifies
6043 // the code. If this is a zero-extension, we need to do an AND to
6044 // maintain the clear top-part of the computation, so we require that
6045 // the input have eliminated at least one cast. If this is a sign
6046 // extension, we insert two new casts (to do the extension) so we
6047 // require that two casts have been eliminated.
6048 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6049 if (!DoXForm) {
6050 switch (CI.getOpcode()) {
6051 case Instruction::Trunc:
6052 DoXForm = true;
6053 break;
6054 case Instruction::ZExt:
6055 DoXForm = NumCastsRemoved >= 1;
6056 break;
6057 case Instruction::SExt:
6058 DoXForm = NumCastsRemoved >= 2;
6059 break;
6060 case Instruction::BitCast:
6061 DoXForm = false;
6062 break;
6063 default:
6064 // All the others use floating point so we shouldn't actually
6065 // get here because of the check above.
6066 assert(!"Unknown cast type .. unreachable");
6067 break;
6068 }
6069 }
6070
6071 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006072 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6073 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006074 assert(Res->getType() == DestTy);
6075 switch (CI.getOpcode()) {
6076 default: assert(0 && "Unknown cast type!");
6077 case Instruction::Trunc:
6078 case Instruction::BitCast:
6079 // Just replace this cast with the result.
6080 return ReplaceInstUsesWith(CI, Res);
6081 case Instruction::ZExt: {
6082 // We need to emit an AND to clear the high bits.
6083 assert(SrcBitSize < DestBitSize && "Not a zext?");
6084 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006085 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006086 if (DestBitSize < 64)
6087 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006088 return BinaryOperator::createAnd(Res, C);
6089 }
6090 case Instruction::SExt:
6091 // We need to emit a cast to truncate, then a cast to sext.
6092 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006093 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6094 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006095 }
6096 }
6097 }
6098
6099 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6100 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6101
6102 switch (SrcI->getOpcode()) {
6103 case Instruction::Add:
6104 case Instruction::Mul:
6105 case Instruction::And:
6106 case Instruction::Or:
6107 case Instruction::Xor:
6108 // If we are discarding information, or just changing the sign,
6109 // rewrite.
6110 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6111 // Don't insert two casts if they cannot be eliminated. We allow
6112 // two casts to be inserted if the sizes are the same. This could
6113 // only be converting signedness, which is a noop.
6114 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006115 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6116 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006117 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006118 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6119 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6120 return BinaryOperator::create(
6121 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006122 }
6123 }
6124
6125 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6126 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6127 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006128 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006129 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006130 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006131 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6132 }
6133 break;
6134 case Instruction::SDiv:
6135 case Instruction::UDiv:
6136 case Instruction::SRem:
6137 case Instruction::URem:
6138 // If we are just changing the sign, rewrite.
6139 if (DestBitSize == SrcBitSize) {
6140 // Don't insert two casts if they cannot be eliminated. We allow
6141 // two casts to be inserted if the sizes are the same. This could
6142 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006143 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6144 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006145 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6146 Op0, DestTy, SrcI);
6147 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6148 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006149 return BinaryOperator::create(
6150 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6151 }
6152 }
6153 break;
6154
6155 case Instruction::Shl:
6156 // Allow changing the sign of the source operand. Do not allow
6157 // changing the size of the shift, UNLESS the shift amount is a
6158 // constant. We must not change variable sized shifts to a smaller
6159 // size, because it is undefined to shift more bits out than exist
6160 // in the value.
6161 if (DestBitSize == SrcBitSize ||
6162 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006163 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6164 Instruction::BitCast : Instruction::Trunc);
6165 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006166 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6167 }
6168 break;
6169 case Instruction::AShr:
6170 // If this is a signed shr, and if all bits shifted in are about to be
6171 // truncated off, turn it into an unsigned shr to allow greater
6172 // simplifications.
6173 if (DestBitSize < SrcBitSize &&
6174 isa<ConstantInt>(Op1)) {
6175 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6176 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6177 // Insert the new logical shift right.
6178 return new ShiftInst(Instruction::LShr, Op0, Op1);
6179 }
6180 }
6181 break;
6182
Reid Spencer266e42b2006-12-23 06:05:41 +00006183 case Instruction::ICmp:
6184 // If we are just checking for a icmp eq of a single bit and casting it
6185 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006186 // cast to integer to avoid the comparison.
6187 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6188 uint64_t Op1CV = Op1C->getZExtValue();
6189 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6190 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6191 // cast (X == 1) to int --> X iff X has only the low bit set.
6192 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6193 // cast (X != 0) to int --> X iff X has only the low bit set.
6194 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6195 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6196 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6197 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6198 // If Op1C some other power of two, convert:
6199 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006200 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006201 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006202
6203 // This only works for EQ and NE
6204 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6205 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6206 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006207
6208 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006209 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006210 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6211 // (X&4) == 2 --> false
6212 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006213 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006214 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006215 return ReplaceInstUsesWith(CI, Res);
6216 }
6217
6218 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6219 Value *In = Op0;
6220 if (ShiftAmt) {
6221 // Perform a logical shr by shiftamt.
6222 // Insert the shift to put the result in the low bit.
6223 In = InsertNewInstBefore(
6224 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006225 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006226 In->getName()+".lobit"), CI);
6227 }
6228
Reid Spencer266e42b2006-12-23 06:05:41 +00006229 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006230 Constant *One = ConstantInt::get(In->getType(), 1);
6231 In = BinaryOperator::createXor(In, One, "tmp");
6232 InsertNewInstBefore(cast<Instruction>(In), CI);
6233 }
6234
6235 if (CI.getType() == In->getType())
6236 return ReplaceInstUsesWith(CI, In);
6237 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006238 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006239 }
6240 }
6241 }
6242 break;
6243 }
6244 return 0;
6245}
6246
6247Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006248 if (Instruction *Result = commonIntCastTransforms(CI))
6249 return Result;
6250
6251 Value *Src = CI.getOperand(0);
6252 const Type *Ty = CI.getType();
6253 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6254
6255 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6256 switch (SrcI->getOpcode()) {
6257 default: break;
6258 case Instruction::LShr:
6259 // We can shrink lshr to something smaller if we know the bits shifted in
6260 // are already zeros.
6261 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6262 unsigned ShAmt = ShAmtV->getZExtValue();
6263
6264 // Get a mask for the bits shifting in.
6265 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006266 Value* SrcIOp0 = SrcI->getOperand(0);
6267 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006268 if (ShAmt >= DestBitWidth) // All zeros.
6269 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6270
6271 // Okay, we can shrink this. Truncate the input, then return a new
6272 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006273 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006274 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6275 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006276 } else { // This is a variable shr.
6277
6278 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6279 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6280 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006281 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006282 Value *One = ConstantInt::get(SrcI->getType(), 1);
6283
6284 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6285 SrcI->getOperand(1),
6286 "tmp"), CI);
6287 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6288 SrcI->getOperand(0),
6289 "tmp"), CI);
6290 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006291 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006292 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006293 }
6294 break;
6295 }
6296 }
6297
6298 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006299}
6300
6301Instruction *InstCombiner::visitZExt(CastInst &CI) {
6302 // If one of the common conversion will work ..
6303 if (Instruction *Result = commonIntCastTransforms(CI))
6304 return Result;
6305
6306 Value *Src = CI.getOperand(0);
6307
6308 // If this is a cast of a cast
6309 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006310 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6311 // types and if the sizes are just right we can convert this into a logical
6312 // 'and' which will be much cheaper than the pair of casts.
6313 if (isa<TruncInst>(CSrc)) {
6314 // Get the sizes of the types involved
6315 Value *A = CSrc->getOperand(0);
6316 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6317 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6318 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6319 // If we're actually extending zero bits and the trunc is a no-op
6320 if (MidSize < DstSize && SrcSize == DstSize) {
6321 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006322 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006323 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6324 Instruction *And =
6325 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6326 // Unfortunately, if the type changed, we need to cast it back.
6327 if (And->getType() != CI.getType()) {
6328 And->setName(CSrc->getName()+".mask");
6329 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006330 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006331 }
6332 return And;
6333 }
6334 }
6335 }
6336
6337 return 0;
6338}
6339
6340Instruction *InstCombiner::visitSExt(CastInst &CI) {
6341 return commonIntCastTransforms(CI);
6342}
6343
6344Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6345 return commonCastTransforms(CI);
6346}
6347
6348Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6349 return commonCastTransforms(CI);
6350}
6351
6352Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006353 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006354}
6355
6356Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006357 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006358}
6359
6360Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6361 return commonCastTransforms(CI);
6362}
6363
6364Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6365 return commonCastTransforms(CI);
6366}
6367
6368Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006369 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006370}
6371
6372Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6373 return commonCastTransforms(CI);
6374}
6375
6376Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6377
6378 // If the operands are integer typed then apply the integer transforms,
6379 // otherwise just apply the common ones.
6380 Value *Src = CI.getOperand(0);
6381 const Type *SrcTy = Src->getType();
6382 const Type *DestTy = CI.getType();
6383
Chris Lattner03c49532007-01-15 02:27:26 +00006384 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006385 if (Instruction *Result = commonIntCastTransforms(CI))
6386 return Result;
6387 } else {
6388 if (Instruction *Result = commonCastTransforms(CI))
6389 return Result;
6390 }
6391
6392
6393 // Get rid of casts from one type to the same type. These are useless and can
6394 // be replaced by the operand.
6395 if (DestTy == Src->getType())
6396 return ReplaceInstUsesWith(CI, Src);
6397
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006398 // If the source and destination are pointers, and this cast is equivalent to
6399 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6400 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006401 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6402 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6403 const Type *DstElTy = DstPTy->getElementType();
6404 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006405
Reid Spencerc635f472006-12-31 05:48:39 +00006406 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006407 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006408 while (SrcElTy != DstElTy &&
6409 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6410 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6411 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006412 ++NumZeros;
6413 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006414
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006415 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006417 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6418 return new GetElementPtrInst(Src, Idxs);
6419 }
6420 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006421 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006422
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006423 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6424 if (SVI->hasOneUse()) {
6425 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6426 // a bitconvert to a vector with the same # elts.
6427 if (isa<PackedType>(DestTy) &&
6428 cast<PackedType>(DestTy)->getNumElements() ==
6429 SVI->getType()->getNumElements()) {
6430 CastInst *Tmp;
6431 // If either of the operands is a cast from CI.getType(), then
6432 // evaluating the shuffle in the casted destination's type will allow
6433 // us to eliminate at least one cast.
6434 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6435 Tmp->getOperand(0)->getType() == DestTy) ||
6436 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6437 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006438 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6439 SVI->getOperand(0), DestTy, &CI);
6440 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6441 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006442 // Return a new shuffle vector. Use the same element ID's, as we
6443 // know the vector types match #elts.
6444 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006445 }
6446 }
6447 }
6448 }
Chris Lattner260ab202002-04-18 17:39:14 +00006449 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006450}
6451
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006452/// GetSelectFoldableOperands - We want to turn code that looks like this:
6453/// %C = or %A, %B
6454/// %D = select %cond, %C, %A
6455/// into:
6456/// %C = select %cond, %B, 0
6457/// %D = or %A, %C
6458///
6459/// Assuming that the specified instruction is an operand to the select, return
6460/// a bitmask indicating which operands of this instruction are foldable if they
6461/// equal the other incoming value of the select.
6462///
6463static unsigned GetSelectFoldableOperands(Instruction *I) {
6464 switch (I->getOpcode()) {
6465 case Instruction::Add:
6466 case Instruction::Mul:
6467 case Instruction::And:
6468 case Instruction::Or:
6469 case Instruction::Xor:
6470 return 3; // Can fold through either operand.
6471 case Instruction::Sub: // Can only fold on the amount subtracted.
6472 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006473 case Instruction::LShr:
6474 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006475 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006476 default:
6477 return 0; // Cannot fold
6478 }
6479}
6480
6481/// GetSelectFoldableConstant - For the same transformation as the previous
6482/// function, return the identity constant that goes into the select.
6483static Constant *GetSelectFoldableConstant(Instruction *I) {
6484 switch (I->getOpcode()) {
6485 default: assert(0 && "This cannot happen!"); abort();
6486 case Instruction::Add:
6487 case Instruction::Sub:
6488 case Instruction::Or:
6489 case Instruction::Xor:
6490 return Constant::getNullValue(I->getType());
6491 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006492 case Instruction::LShr:
6493 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006494 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006495 case Instruction::And:
6496 return ConstantInt::getAllOnesValue(I->getType());
6497 case Instruction::Mul:
6498 return ConstantInt::get(I->getType(), 1);
6499 }
6500}
6501
Chris Lattner411336f2005-01-19 21:50:18 +00006502/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6503/// have the same opcode and only one use each. Try to simplify this.
6504Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6505 Instruction *FI) {
6506 if (TI->getNumOperands() == 1) {
6507 // If this is a non-volatile load or a cast from the same type,
6508 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006509 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006510 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6511 return 0;
6512 } else {
6513 return 0; // unknown unary op.
6514 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006515
Chris Lattner411336f2005-01-19 21:50:18 +00006516 // Fold this by inserting a select from the input values.
6517 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6518 FI->getOperand(0), SI.getName()+".v");
6519 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006520 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6521 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006522 }
6523
Reid Spencer266e42b2006-12-23 06:05:41 +00006524 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006525 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006526 return 0;
6527
6528 // Figure out if the operations have any operands in common.
6529 Value *MatchOp, *OtherOpT, *OtherOpF;
6530 bool MatchIsOpZero;
6531 if (TI->getOperand(0) == FI->getOperand(0)) {
6532 MatchOp = TI->getOperand(0);
6533 OtherOpT = TI->getOperand(1);
6534 OtherOpF = FI->getOperand(1);
6535 MatchIsOpZero = true;
6536 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6537 MatchOp = TI->getOperand(1);
6538 OtherOpT = TI->getOperand(0);
6539 OtherOpF = FI->getOperand(0);
6540 MatchIsOpZero = false;
6541 } else if (!TI->isCommutative()) {
6542 return 0;
6543 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6544 MatchOp = TI->getOperand(0);
6545 OtherOpT = TI->getOperand(1);
6546 OtherOpF = FI->getOperand(0);
6547 MatchIsOpZero = true;
6548 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6549 MatchOp = TI->getOperand(1);
6550 OtherOpT = TI->getOperand(0);
6551 OtherOpF = FI->getOperand(1);
6552 MatchIsOpZero = true;
6553 } else {
6554 return 0;
6555 }
6556
6557 // If we reach here, they do have operations in common.
6558 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6559 OtherOpF, SI.getName()+".v");
6560 InsertNewInstBefore(NewSI, SI);
6561
6562 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6563 if (MatchIsOpZero)
6564 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6565 else
6566 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006567 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006568
6569 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6570 if (MatchIsOpZero)
6571 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6572 else
6573 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006574}
6575
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006576Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006577 Value *CondVal = SI.getCondition();
6578 Value *TrueVal = SI.getTrueValue();
6579 Value *FalseVal = SI.getFalseValue();
6580
6581 // select true, X, Y -> X
6582 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006583 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006584 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006585
6586 // select C, X, X -> X
6587 if (TrueVal == FalseVal)
6588 return ReplaceInstUsesWith(SI, TrueVal);
6589
Chris Lattner81a7a232004-10-16 18:11:37 +00006590 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6591 return ReplaceInstUsesWith(SI, FalseVal);
6592 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6593 return ReplaceInstUsesWith(SI, TrueVal);
6594 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6595 if (isa<Constant>(TrueVal))
6596 return ReplaceInstUsesWith(SI, TrueVal);
6597 else
6598 return ReplaceInstUsesWith(SI, FalseVal);
6599 }
6600
Reid Spencer542964f2007-01-11 18:21:29 +00006601 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006602 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006603 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006604 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006605 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006606 } else {
6607 // Change: A = select B, false, C --> A = and !B, C
6608 Value *NotCond =
6609 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6610 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006611 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006612 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006613 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006614 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006615 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006616 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006617 } else {
6618 // Change: A = select B, C, true --> A = or !B, C
6619 Value *NotCond =
6620 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6621 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006622 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006623 }
6624 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006625 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006626
Chris Lattner183b3362004-04-09 19:05:30 +00006627 // Selecting between two integer constants?
6628 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6629 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6630 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006631 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006632 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006633 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006634 // select C, 0, 1 -> cast !C to int
6635 Value *NotCond =
6636 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006637 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006638 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006639 }
Chris Lattner35167c32004-06-09 07:59:58 +00006640
Reid Spencer266e42b2006-12-23 06:05:41 +00006641 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006642
Reid Spencer266e42b2006-12-23 06:05:41 +00006643 // (x <s 0) ? -1 : 0 -> ashr x, 31
6644 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006645 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6646 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6647 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006648 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006649 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006650 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006651 else {
6652 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006653 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006654 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006655 }
6656
6657 if (CanXForm) {
6658 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006659 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006660 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006661 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006662 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006663 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006664 ShAmt, "ones");
6665 InsertNewInstBefore(SRA, SI);
6666
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006667 // Finally, convert to the type of the select RHS. We figure out
6668 // if this requires a SExt, Trunc or BitCast based on the sizes.
6669 Instruction::CastOps opc = Instruction::BitCast;
6670 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6671 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6672 if (SRASize < SISize)
6673 opc = Instruction::SExt;
6674 else if (SRASize > SISize)
6675 opc = Instruction::Trunc;
6676 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006677 }
6678 }
6679
6680
6681 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006682 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006683 // non-constant value, eliminate this whole mess. This corresponds to
6684 // cases like this: ((X & 27) ? 27 : 0)
6685 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006686 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006687 cast<Constant>(IC->getOperand(1))->isNullValue())
6688 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6689 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006690 isa<ConstantInt>(ICA->getOperand(1)) &&
6691 (ICA->getOperand(1) == TrueValC ||
6692 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006693 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6694 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006695 // know whether we have a icmp_ne or icmp_eq and whether the
6696 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006697 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006698 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006699 Value *V = ICA;
6700 if (ShouldNotVal)
6701 V = InsertNewInstBefore(BinaryOperator::create(
6702 Instruction::Xor, V, ICA->getOperand(1)), SI);
6703 return ReplaceInstUsesWith(SI, V);
6704 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006705 }
Chris Lattner533bc492004-03-30 19:37:13 +00006706 }
Chris Lattner623fba12004-04-10 22:21:27 +00006707
6708 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006709 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6710 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006711 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006712 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006713 return ReplaceInstUsesWith(SI, FalseVal);
6714 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006715 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006716 return ReplaceInstUsesWith(SI, TrueVal);
6717 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6718
Reid Spencer266e42b2006-12-23 06:05:41 +00006719 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006720 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006721 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006722 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006723 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006724 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6725 return ReplaceInstUsesWith(SI, TrueVal);
6726 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6727 }
6728 }
6729
6730 // See if we are selecting two values based on a comparison of the two values.
6731 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6732 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6733 // Transform (X == Y) ? X : Y -> Y
6734 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6735 return ReplaceInstUsesWith(SI, FalseVal);
6736 // Transform (X != Y) ? X : Y -> X
6737 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6738 return ReplaceInstUsesWith(SI, TrueVal);
6739 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6740
6741 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6742 // Transform (X == Y) ? Y : X -> X
6743 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6744 return ReplaceInstUsesWith(SI, FalseVal);
6745 // Transform (X != Y) ? Y : X -> Y
6746 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006747 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006748 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6749 }
6750 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006751
Chris Lattnera04c9042005-01-13 22:52:24 +00006752 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6753 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6754 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006755 Instruction *AddOp = 0, *SubOp = 0;
6756
Chris Lattner411336f2005-01-19 21:50:18 +00006757 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6758 if (TI->getOpcode() == FI->getOpcode())
6759 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6760 return IV;
6761
6762 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6763 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006764 if (TI->getOpcode() == Instruction::Sub &&
6765 FI->getOpcode() == Instruction::Add) {
6766 AddOp = FI; SubOp = TI;
6767 } else if (FI->getOpcode() == Instruction::Sub &&
6768 TI->getOpcode() == Instruction::Add) {
6769 AddOp = TI; SubOp = FI;
6770 }
6771
6772 if (AddOp) {
6773 Value *OtherAddOp = 0;
6774 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6775 OtherAddOp = AddOp->getOperand(1);
6776 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6777 OtherAddOp = AddOp->getOperand(0);
6778 }
6779
6780 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006781 // So at this point we know we have (Y -> OtherAddOp):
6782 // select C, (add X, Y), (sub X, Z)
6783 Value *NegVal; // Compute -Z
6784 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6785 NegVal = ConstantExpr::getNeg(C);
6786 } else {
6787 NegVal = InsertNewInstBefore(
6788 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006789 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006790
6791 Value *NewTrueOp = OtherAddOp;
6792 Value *NewFalseOp = NegVal;
6793 if (AddOp != TI)
6794 std::swap(NewTrueOp, NewFalseOp);
6795 Instruction *NewSel =
6796 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6797
6798 NewSel = InsertNewInstBefore(NewSel, SI);
6799 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006800 }
6801 }
6802 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006803
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006804 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006805 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006806 // See the comment above GetSelectFoldableOperands for a description of the
6807 // transformation we are doing here.
6808 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6809 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6810 !isa<Constant>(FalseVal))
6811 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6812 unsigned OpToFold = 0;
6813 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6814 OpToFold = 1;
6815 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6816 OpToFold = 2;
6817 }
6818
6819 if (OpToFold) {
6820 Constant *C = GetSelectFoldableConstant(TVI);
6821 std::string Name = TVI->getName(); TVI->setName("");
6822 Instruction *NewSel =
6823 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6824 Name);
6825 InsertNewInstBefore(NewSel, SI);
6826 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6827 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6828 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6829 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6830 else {
6831 assert(0 && "Unknown instruction!!");
6832 }
6833 }
6834 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006835
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006836 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6837 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6838 !isa<Constant>(TrueVal))
6839 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6840 unsigned OpToFold = 0;
6841 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6842 OpToFold = 1;
6843 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6844 OpToFold = 2;
6845 }
6846
6847 if (OpToFold) {
6848 Constant *C = GetSelectFoldableConstant(FVI);
6849 std::string Name = FVI->getName(); FVI->setName("");
6850 Instruction *NewSel =
6851 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6852 Name);
6853 InsertNewInstBefore(NewSel, SI);
6854 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6855 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6856 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6857 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6858 else {
6859 assert(0 && "Unknown instruction!!");
6860 }
6861 }
6862 }
6863 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006864
6865 if (BinaryOperator::isNot(CondVal)) {
6866 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6867 SI.setOperand(1, FalseVal);
6868 SI.setOperand(2, TrueVal);
6869 return &SI;
6870 }
6871
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006872 return 0;
6873}
6874
Chris Lattner82f2ef22006-03-06 20:18:44 +00006875/// GetKnownAlignment - If the specified pointer has an alignment that we can
6876/// determine, return it, otherwise return 0.
6877static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6878 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6879 unsigned Align = GV->getAlignment();
6880 if (Align == 0 && TD)
Chris Lattner50ee0e42007-01-20 22:35:55 +00006881 Align = TD->getTypeAlignmentPref(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006882 return Align;
6883 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6884 unsigned Align = AI->getAlignment();
6885 if (Align == 0 && TD) {
6886 if (isa<AllocaInst>(AI))
Chris Lattner50ee0e42007-01-20 22:35:55 +00006887 Align = TD->getTypeAlignmentPref(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006888 else if (isa<MallocInst>(AI)) {
6889 // Malloc returns maximally aligned memory.
Chris Lattner50ee0e42007-01-20 22:35:55 +00006890 Align = TD->getTypeAlignmentABI(AI->getType()->getElementType());
6891 Align =
6892 std::max(Align,
6893 (unsigned)TD->getTypeAlignmentABI(Type::DoubleTy));
6894 Align =
6895 std::max(Align,
6896 (unsigned)TD->getTypeAlignmentABI(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006897 }
6898 }
6899 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006900 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006901 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006902 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006903 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006904 if (isa<PointerType>(CI->getOperand(0)->getType()))
6905 return GetKnownAlignment(CI->getOperand(0), TD);
6906 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006907 } else if (isa<GetElementPtrInst>(V) ||
6908 (isa<ConstantExpr>(V) &&
6909 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6910 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006911 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6912 if (BaseAlignment == 0) return 0;
6913
6914 // If all indexes are zero, it is just the alignment of the base pointer.
6915 bool AllZeroOperands = true;
6916 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6917 if (!isa<Constant>(GEPI->getOperand(i)) ||
6918 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6919 AllZeroOperands = false;
6920 break;
6921 }
6922 if (AllZeroOperands)
6923 return BaseAlignment;
6924
6925 // Otherwise, if the base alignment is >= the alignment we expect for the
6926 // base pointer type, then we know that the resultant pointer is aligned at
6927 // least as much as its type requires.
6928 if (!TD) return 0;
6929
6930 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006931 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6932 if (TD->getTypeAlignmentABI(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006933 <= BaseAlignment) {
6934 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006935 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6936 return TD->getTypeAlignmentABI(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00006937 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006938 return 0;
6939 }
6940 return 0;
6941}
6942
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006943
Chris Lattnerc66b2232006-01-13 20:11:04 +00006944/// visitCallInst - CallInst simplification. This mostly only handles folding
6945/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6946/// the heavy lifting.
6947///
Chris Lattner970c33a2003-06-19 17:00:31 +00006948Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006949 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6950 if (!II) return visitCallSite(&CI);
6951
Chris Lattner51ea1272004-02-28 05:22:00 +00006952 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6953 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006954 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006955 bool Changed = false;
6956
6957 // memmove/cpy/set of zero bytes is a noop.
6958 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6959 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6960
Chris Lattner00648e12004-10-12 04:52:52 +00006961 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006962 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006963 // Replace the instruction with just byte operations. We would
6964 // transform other cases to loads/stores, but we don't know if
6965 // alignment is sufficient.
6966 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006967 }
6968
Chris Lattner00648e12004-10-12 04:52:52 +00006969 // If we have a memmove and the source operation is a constant global,
6970 // then the source and dest pointers can't alias, so we can change this
6971 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006972 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006973 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6974 if (GVSrc->isConstant()) {
6975 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006976 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006977 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006978 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006979 Name = "llvm.memcpy.i32";
6980 else
6981 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00006982 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006983 CI.getCalledFunction()->getFunctionType());
6984 CI.setOperand(0, MemCpy);
6985 Changed = true;
6986 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006987 }
Chris Lattner00648e12004-10-12 04:52:52 +00006988
Chris Lattner82f2ef22006-03-06 20:18:44 +00006989 // If we can determine a pointer alignment that is bigger than currently
6990 // set, update the alignment.
6991 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6992 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6993 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6994 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006995 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006996 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006997 Changed = true;
6998 }
6999 } else if (isa<MemSetInst>(MI)) {
7000 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007001 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007002 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007003 Changed = true;
7004 }
7005 }
7006
Chris Lattnerc66b2232006-01-13 20:11:04 +00007007 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007008 } else {
7009 switch (II->getIntrinsicID()) {
7010 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007011 case Intrinsic::ppc_altivec_lvx:
7012 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007013 case Intrinsic::x86_sse_loadu_ps:
7014 case Intrinsic::x86_sse2_loadu_pd:
7015 case Intrinsic::x86_sse2_loadu_dq:
7016 // Turn PPC lvx -> load if the pointer is known aligned.
7017 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007018 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007019 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007020 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007021 return new LoadInst(Ptr);
7022 }
7023 break;
7024 case Intrinsic::ppc_altivec_stvx:
7025 case Intrinsic::ppc_altivec_stvxl:
7026 // Turn stvx -> store if the pointer is known aligned.
7027 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007028 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007029 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7030 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007031 return new StoreInst(II->getOperand(1), Ptr);
7032 }
7033 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007034 case Intrinsic::x86_sse_storeu_ps:
7035 case Intrinsic::x86_sse2_storeu_pd:
7036 case Intrinsic::x86_sse2_storeu_dq:
7037 case Intrinsic::x86_sse2_storel_dq:
7038 // Turn X86 storeu -> store if the pointer is known aligned.
7039 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7040 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007041 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7042 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007043 return new StoreInst(II->getOperand(2), Ptr);
7044 }
7045 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007046
7047 case Intrinsic::x86_sse_cvttss2si: {
7048 // These intrinsics only demands the 0th element of its input vector. If
7049 // we can simplify the input based on that, do so now.
7050 uint64_t UndefElts;
7051 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7052 UndefElts)) {
7053 II->setOperand(1, V);
7054 return II;
7055 }
7056 break;
7057 }
7058
Chris Lattnere79d2492006-04-06 19:19:17 +00007059 case Intrinsic::ppc_altivec_vperm:
7060 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7061 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7062 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7063
7064 // Check that all of the elements are integer constants or undefs.
7065 bool AllEltsOk = true;
7066 for (unsigned i = 0; i != 16; ++i) {
7067 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7068 !isa<UndefValue>(Mask->getOperand(i))) {
7069 AllEltsOk = false;
7070 break;
7071 }
7072 }
7073
7074 if (AllEltsOk) {
7075 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007076 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7077 II->getOperand(1), Mask->getType(), CI);
7078 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7079 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007080 Value *Result = UndefValue::get(Op0->getType());
7081
7082 // Only extract each element once.
7083 Value *ExtractedElts[32];
7084 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7085
7086 for (unsigned i = 0; i != 16; ++i) {
7087 if (isa<UndefValue>(Mask->getOperand(i)))
7088 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007089 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007090 Idx &= 31; // Match the hardware behavior.
7091
7092 if (ExtractedElts[Idx] == 0) {
7093 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007094 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007095 InsertNewInstBefore(Elt, CI);
7096 ExtractedElts[Idx] = Elt;
7097 }
7098
7099 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007100 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007101 InsertNewInstBefore(cast<Instruction>(Result), CI);
7102 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007103 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007104 }
7105 }
7106 break;
7107
Chris Lattner503221f2006-01-13 21:28:09 +00007108 case Intrinsic::stackrestore: {
7109 // If the save is right next to the restore, remove the restore. This can
7110 // happen when variable allocas are DCE'd.
7111 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7112 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7113 BasicBlock::iterator BI = SS;
7114 if (&*++BI == II)
7115 return EraseInstFromFunction(CI);
7116 }
7117 }
7118
7119 // If the stack restore is in a return/unwind block and if there are no
7120 // allocas or calls between the restore and the return, nuke the restore.
7121 TerminatorInst *TI = II->getParent()->getTerminator();
7122 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7123 BasicBlock::iterator BI = II;
7124 bool CannotRemove = false;
7125 for (++BI; &*BI != TI; ++BI) {
7126 if (isa<AllocaInst>(BI) ||
7127 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7128 CannotRemove = true;
7129 break;
7130 }
7131 }
7132 if (!CannotRemove)
7133 return EraseInstFromFunction(CI);
7134 }
7135 break;
7136 }
7137 }
Chris Lattner00648e12004-10-12 04:52:52 +00007138 }
7139
Chris Lattnerc66b2232006-01-13 20:11:04 +00007140 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007141}
7142
7143// InvokeInst simplification
7144//
7145Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007146 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007147}
7148
Chris Lattneraec3d942003-10-07 22:32:43 +00007149// visitCallSite - Improvements for call and invoke instructions.
7150//
7151Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007152 bool Changed = false;
7153
7154 // If the callee is a constexpr cast of a function, attempt to move the cast
7155 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007156 if (transformConstExprCastCall(CS)) return 0;
7157
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007158 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007159
Chris Lattner61d9d812005-05-13 07:09:09 +00007160 if (Function *CalleeF = dyn_cast<Function>(Callee))
7161 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7162 Instruction *OldCall = CS.getInstruction();
7163 // If the call and callee calling conventions don't match, this call must
7164 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007165 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007166 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007167 if (!OldCall->use_empty())
7168 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7169 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7170 return EraseInstFromFunction(*OldCall);
7171 return 0;
7172 }
7173
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007174 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7175 // This instruction is not reachable, just remove it. We insert a store to
7176 // undef so that we know that this code is not reachable, despite the fact
7177 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007178 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007179 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007180 CS.getInstruction());
7181
7182 if (!CS.getInstruction()->use_empty())
7183 CS.getInstruction()->
7184 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7185
7186 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7187 // Don't break the CFG, insert a dummy cond branch.
7188 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007189 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007190 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007191 return EraseInstFromFunction(*CS.getInstruction());
7192 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007193
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007194 const PointerType *PTy = cast<PointerType>(Callee->getType());
7195 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7196 if (FTy->isVarArg()) {
7197 // See if we can optimize any arguments passed through the varargs area of
7198 // the call.
7199 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7200 E = CS.arg_end(); I != E; ++I)
7201 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7202 // If this cast does not effect the value passed through the varargs
7203 // area, we can eliminate the use of the cast.
7204 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007205 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007206 *I = Op;
7207 Changed = true;
7208 }
7209 }
7210 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007211
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007212 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007213}
7214
Chris Lattner970c33a2003-06-19 17:00:31 +00007215// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7216// attempt to move the cast to the arguments of the call/invoke.
7217//
7218bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7219 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7220 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007221 if (CE->getOpcode() != Instruction::BitCast ||
7222 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007223 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007224 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007225 Instruction *Caller = CS.getInstruction();
7226
7227 // Okay, this is a cast from a function to a different type. Unless doing so
7228 // would cause a type conversion of one of our arguments, change this call to
7229 // be a direct call with arguments casted to the appropriate types.
7230 //
7231 const FunctionType *FT = Callee->getFunctionType();
7232 const Type *OldRetTy = Caller->getType();
7233
Chris Lattner1f7942f2004-01-14 06:06:08 +00007234 // Check to see if we are changing the return type...
7235 if (OldRetTy != FT->getReturnType()) {
Chris Lattner400f9592007-01-06 02:09:32 +00007236 if (Callee->isExternal() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007237 OldRetTy != FT->getReturnType() &&
7238 // Conversion is ok if changing from pointer to int of same size.
7239 !(isa<PointerType>(FT->getReturnType()) &&
7240 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007241 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007242
7243 // If the callsite is an invoke instruction, and the return value is used by
7244 // a PHI node in a successor, we cannot change the return type of the call
7245 // because there is no place to put the cast instruction (without breaking
7246 // the critical edge). Bail out in this case.
7247 if (!Caller->use_empty())
7248 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7249 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7250 UI != E; ++UI)
7251 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7252 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007253 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007254 return false;
7255 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007256
7257 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7258 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007259
Chris Lattner970c33a2003-06-19 17:00:31 +00007260 CallSite::arg_iterator AI = CS.arg_begin();
7261 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7262 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007263 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007264 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007265 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007266 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007267 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007268 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007269 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7270 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7271 && c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007272 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007273 }
7274
7275 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7276 Callee->isExternal())
7277 return false; // Do not delete arguments unless we have a function body...
7278
7279 // Okay, we decided that this is a safe thing to do: go ahead and start
7280 // inserting cast instructions as necessary...
7281 std::vector<Value*> Args;
7282 Args.reserve(NumActualArgs);
7283
7284 AI = CS.arg_begin();
7285 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7286 const Type *ParamTy = FT->getParamType(i);
7287 if ((*AI)->getType() == ParamTy) {
7288 Args.push_back(*AI);
7289 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007290 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007291 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007292 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007293 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007294 }
7295 }
7296
7297 // If the function takes more arguments than the call was taking, add them
7298 // now...
7299 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7300 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7301
7302 // If we are removing arguments to the function, emit an obnoxious warning...
7303 if (FT->getNumParams() < NumActualArgs)
7304 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007305 cerr << "WARNING: While resolving call to function '"
7306 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007307 } else {
7308 // Add all of the arguments in their promoted form to the arg list...
7309 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7310 const Type *PTy = getPromotedType((*AI)->getType());
7311 if (PTy != (*AI)->getType()) {
7312 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007313 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7314 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007315 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007316 InsertNewInstBefore(Cast, *Caller);
7317 Args.push_back(Cast);
7318 } else {
7319 Args.push_back(*AI);
7320 }
7321 }
7322 }
7323
7324 if (FT->getReturnType() == Type::VoidTy)
7325 Caller->setName(""); // Void type should not have a name...
7326
7327 Instruction *NC;
7328 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007329 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007330 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007331 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007332 } else {
7333 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007334 if (cast<CallInst>(Caller)->isTailCall())
7335 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007336 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007337 }
7338
7339 // Insert a cast of the return type as necessary...
7340 Value *NV = NC;
7341 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7342 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007343 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007344 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7345 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007346 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007347
7348 // If this is an invoke instruction, we should insert it after the first
7349 // non-phi, instruction in the normal successor block.
7350 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7351 BasicBlock::iterator I = II->getNormalDest()->begin();
7352 while (isa<PHINode>(I)) ++I;
7353 InsertNewInstBefore(NC, *I);
7354 } else {
7355 // Otherwise, it's a call, just insert cast right after the call instr
7356 InsertNewInstBefore(NC, *Caller);
7357 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007358 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007359 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007360 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007361 }
7362 }
7363
7364 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7365 Caller->replaceAllUsesWith(NV);
7366 Caller->getParent()->getInstList().erase(Caller);
7367 removeFromWorkList(Caller);
7368 return true;
7369}
7370
Chris Lattnercadac0c2006-11-01 04:51:18 +00007371/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7372/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7373/// and a single binop.
7374Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7375 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007376 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007377 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007378 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007379 Value *LHSVal = FirstInst->getOperand(0);
7380 Value *RHSVal = FirstInst->getOperand(1);
7381
7382 const Type *LHSType = LHSVal->getType();
7383 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007384
7385 // Scan to see if all operands are the same opcode, all have one use, and all
7386 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007387 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007388 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007389 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007390 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007391 // types or GEP's with different index types.
7392 I->getOperand(0)->getType() != LHSType ||
7393 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007394 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007395
7396 // If they are CmpInst instructions, check their predicates
7397 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7398 if (cast<CmpInst>(I)->getPredicate() !=
7399 cast<CmpInst>(FirstInst)->getPredicate())
7400 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007401
7402 // Keep track of which operand needs a phi node.
7403 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7404 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007405 }
7406
Chris Lattner4f218d52006-11-08 19:42:28 +00007407 // Otherwise, this is safe to transform, determine if it is profitable.
7408
7409 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7410 // Indexes are often folded into load/store instructions, so we don't want to
7411 // hide them behind a phi.
7412 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7413 return 0;
7414
Chris Lattnercadac0c2006-11-01 04:51:18 +00007415 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007416 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007417 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007418 if (LHSVal == 0) {
7419 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7420 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7421 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007422 InsertNewInstBefore(NewLHS, PN);
7423 LHSVal = NewLHS;
7424 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007425
7426 if (RHSVal == 0) {
7427 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7428 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7429 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007430 InsertNewInstBefore(NewRHS, PN);
7431 RHSVal = NewRHS;
7432 }
7433
Chris Lattnercd62f112006-11-08 19:29:23 +00007434 // Add all operands to the new PHIs.
7435 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7436 if (NewLHS) {
7437 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7438 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7439 }
7440 if (NewRHS) {
7441 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7442 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7443 }
7444 }
7445
Chris Lattnercadac0c2006-11-01 04:51:18 +00007446 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007447 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007448 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7449 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7450 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007451 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7452 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7453 else {
7454 assert(isa<GetElementPtrInst>(FirstInst));
7455 return new GetElementPtrInst(LHSVal, RHSVal);
7456 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007457}
7458
Chris Lattner14f82c72006-11-01 07:13:54 +00007459/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7460/// of the block that defines it. This means that it must be obvious the value
7461/// of the load is not changed from the point of the load to the end of the
7462/// block it is in.
7463static bool isSafeToSinkLoad(LoadInst *L) {
7464 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7465
7466 for (++BBI; BBI != E; ++BBI)
7467 if (BBI->mayWriteToMemory())
7468 return false;
7469 return true;
7470}
7471
Chris Lattner970c33a2003-06-19 17:00:31 +00007472
Chris Lattner7515cab2004-11-14 19:13:23 +00007473// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7474// operator and they all are only used by the PHI, PHI together their
7475// inputs, and do the operation once, to the result of the PHI.
7476Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7477 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7478
7479 // Scan the instruction, looking for input operations that can be folded away.
7480 // If all input operands to the phi are the same instruction (e.g. a cast from
7481 // the same type or "+42") we can pull the operation through the PHI, reducing
7482 // code size and simplifying code.
7483 Constant *ConstantOp = 0;
7484 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007485 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007486 if (isa<CastInst>(FirstInst)) {
7487 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007488 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7489 isa<CmpInst>(FirstInst)) {
7490 // Can fold binop, compare or shift here if the RHS is a constant,
7491 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007492 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007493 if (ConstantOp == 0)
7494 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007495 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7496 isVolatile = LI->isVolatile();
7497 // We can't sink the load if the loaded value could be modified between the
7498 // load and the PHI.
7499 if (LI->getParent() != PN.getIncomingBlock(0) ||
7500 !isSafeToSinkLoad(LI))
7501 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007502 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007503 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007504 return FoldPHIArgBinOpIntoPHI(PN);
7505 // Can't handle general GEPs yet.
7506 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007507 } else {
7508 return 0; // Cannot fold this operation.
7509 }
7510
7511 // Check to see if all arguments are the same operation.
7512 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7513 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7514 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007515 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007516 return 0;
7517 if (CastSrcTy) {
7518 if (I->getOperand(0)->getType() != CastSrcTy)
7519 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007520 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007521 // We can't sink the load if the loaded value could be modified between
7522 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007523 if (LI->isVolatile() != isVolatile ||
7524 LI->getParent() != PN.getIncomingBlock(i) ||
7525 !isSafeToSinkLoad(LI))
7526 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007527 } else if (I->getOperand(1) != ConstantOp) {
7528 return 0;
7529 }
7530 }
7531
7532 // Okay, they are all the same operation. Create a new PHI node of the
7533 // correct type, and PHI together all of the LHS's of the instructions.
7534 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7535 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007536 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007537
7538 Value *InVal = FirstInst->getOperand(0);
7539 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007540
7541 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007542 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7543 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7544 if (NewInVal != InVal)
7545 InVal = 0;
7546 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7547 }
7548
7549 Value *PhiVal;
7550 if (InVal) {
7551 // The new PHI unions all of the same values together. This is really
7552 // common, so we handle it intelligently here for compile-time speed.
7553 PhiVal = InVal;
7554 delete NewPN;
7555 } else {
7556 InsertNewInstBefore(NewPN, PN);
7557 PhiVal = NewPN;
7558 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007559
Chris Lattner7515cab2004-11-14 19:13:23 +00007560 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007561 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7562 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007563 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007564 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007565 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007566 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007567 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7568 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7569 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007570 else
7571 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007572 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007573}
Chris Lattner48a44f72002-05-02 17:06:02 +00007574
Chris Lattner71536432005-01-17 05:10:15 +00007575/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7576/// that is dead.
7577static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7578 if (PN->use_empty()) return true;
7579 if (!PN->hasOneUse()) return false;
7580
7581 // Remember this node, and if we find the cycle, return.
7582 if (!PotentiallyDeadPHIs.insert(PN).second)
7583 return true;
7584
7585 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7586 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007587
Chris Lattner71536432005-01-17 05:10:15 +00007588 return false;
7589}
7590
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007591// PHINode simplification
7592//
Chris Lattner113f4f42002-06-25 16:13:24 +00007593Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007594 // If LCSSA is around, don't mess with Phi nodes
7595 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007596
Owen Andersonae8aa642006-07-10 22:03:18 +00007597 if (Value *V = PN.hasConstantValue())
7598 return ReplaceInstUsesWith(PN, V);
7599
Owen Andersonae8aa642006-07-10 22:03:18 +00007600 // If all PHI operands are the same operation, pull them through the PHI,
7601 // reducing code size.
7602 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7603 PN.getIncomingValue(0)->hasOneUse())
7604 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7605 return Result;
7606
7607 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7608 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7609 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007610 if (PN.hasOneUse()) {
7611 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7612 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007613 std::set<PHINode*> PotentiallyDeadPHIs;
7614 PotentiallyDeadPHIs.insert(&PN);
7615 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7616 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7617 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007618
7619 // If this phi has a single use, and if that use just computes a value for
7620 // the next iteration of a loop, delete the phi. This occurs with unused
7621 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7622 // common case here is good because the only other things that catch this
7623 // are induction variable analysis (sometimes) and ADCE, which is only run
7624 // late.
7625 if (PHIUser->hasOneUse() &&
7626 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7627 PHIUser->use_back() == &PN) {
7628 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7629 }
7630 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007631
Chris Lattner91daeb52003-12-19 05:58:40 +00007632 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007633}
7634
Reid Spencer13bc5d72006-12-12 09:18:51 +00007635static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7636 Instruction *InsertPoint,
7637 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007638 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7639 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007640 // We must cast correctly to the pointer type. Ensure that we
7641 // sign extend the integer value if it is smaller as this is
7642 // used for address computation.
7643 Instruction::CastOps opcode =
7644 (VTySize < PtrSize ? Instruction::SExt :
7645 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7646 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007647}
7648
Chris Lattner48a44f72002-05-02 17:06:02 +00007649
Chris Lattner113f4f42002-06-25 16:13:24 +00007650Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007651 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007652 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007653 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007654 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007655 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007656
Chris Lattner81a7a232004-10-16 18:11:37 +00007657 if (isa<UndefValue>(GEP.getOperand(0)))
7658 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7659
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007660 bool HasZeroPointerIndex = false;
7661 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7662 HasZeroPointerIndex = C->isNullValue();
7663
7664 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007665 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007666
Chris Lattner69193f92004-04-05 01:30:19 +00007667 // Eliminate unneeded casts for indices.
7668 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007669 gep_type_iterator GTI = gep_type_begin(GEP);
7670 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7671 if (isa<SequentialType>(*GTI)) {
7672 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007673 if (CI->getOpcode() == Instruction::ZExt ||
7674 CI->getOpcode() == Instruction::SExt) {
7675 const Type *SrcTy = CI->getOperand(0)->getType();
7676 // We can eliminate a cast from i32 to i64 iff the target
7677 // is a 32-bit pointer target.
7678 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7679 MadeChange = true;
7680 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007681 }
7682 }
7683 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007684 // If we are using a wider index than needed for this platform, shrink it
7685 // to what we need. If the incoming value needs a cast instruction,
7686 // insert it. This explicit cast can make subsequent optimizations more
7687 // obvious.
7688 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007689 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007690 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007691 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007692 MadeChange = true;
7693 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007694 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7695 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007696 GEP.setOperand(i, Op);
7697 MadeChange = true;
7698 }
Chris Lattner69193f92004-04-05 01:30:19 +00007699 }
7700 if (MadeChange) return &GEP;
7701
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007702 // Combine Indices - If the source pointer to this getelementptr instruction
7703 // is a getelementptr instruction, combine the indices of the two
7704 // getelementptr instructions into a single instruction.
7705 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007706 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007707 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007708 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007709
7710 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007711 // Note that if our source is a gep chain itself that we wait for that
7712 // chain to be resolved before we perform this transformation. This
7713 // avoids us creating a TON of code in some cases.
7714 //
7715 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7716 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7717 return 0; // Wait until our source is folded to completion.
7718
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007719 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007720
7721 // Find out whether the last index in the source GEP is a sequential idx.
7722 bool EndsWithSequential = false;
7723 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7724 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007725 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007726
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007727 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007728 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007729 // Replace: gep (gep %P, long B), long A, ...
7730 // With: T = long A+B; gep %P, T, ...
7731 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007732 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007733 if (SO1 == Constant::getNullValue(SO1->getType())) {
7734 Sum = GO1;
7735 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7736 Sum = SO1;
7737 } else {
7738 // If they aren't the same type, convert both to an integer of the
7739 // target's pointer size.
7740 if (SO1->getType() != GO1->getType()) {
7741 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007742 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007743 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007744 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007745 } else {
7746 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007747 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007748 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007749 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007750
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007751 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007752 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007753 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007754 } else {
7755 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007756 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7757 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007758 }
7759 }
7760 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007761 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7762 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7763 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007764 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7765 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007766 }
Chris Lattner69193f92004-04-05 01:30:19 +00007767 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007768
7769 // Recycle the GEP we already have if possible.
7770 if (SrcGEPOperands.size() == 2) {
7771 GEP.setOperand(0, SrcGEPOperands[0]);
7772 GEP.setOperand(1, Sum);
7773 return &GEP;
7774 } else {
7775 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7776 SrcGEPOperands.end()-1);
7777 Indices.push_back(Sum);
7778 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7779 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007780 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007781 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007782 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007783 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007784 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7785 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007786 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7787 }
7788
7789 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007790 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007791
Chris Lattner5f667a62004-05-07 22:09:22 +00007792 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007793 // GEP of global variable. If all of the indices for this GEP are
7794 // constants, we can promote this to a constexpr instead of an instruction.
7795
7796 // Scan for nonconstants...
7797 std::vector<Constant*> Indices;
7798 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7799 for (; I != E && isa<Constant>(*I); ++I)
7800 Indices.push_back(cast<Constant>(*I));
7801
7802 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007803 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007804
7805 // Replace all uses of the GEP with the new constexpr...
7806 return ReplaceInstUsesWith(GEP, CE);
7807 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007808 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007809 if (!isa<PointerType>(X->getType())) {
7810 // Not interesting. Source pointer must be a cast from pointer.
7811 } else if (HasZeroPointerIndex) {
7812 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7813 // into : GEP [10 x ubyte]* X, long 0, ...
7814 //
7815 // This occurs when the program declares an array extern like "int X[];"
7816 //
7817 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7818 const PointerType *XTy = cast<PointerType>(X->getType());
7819 if (const ArrayType *XATy =
7820 dyn_cast<ArrayType>(XTy->getElementType()))
7821 if (const ArrayType *CATy =
7822 dyn_cast<ArrayType>(CPTy->getElementType()))
7823 if (CATy->getElementType() == XATy->getElementType()) {
7824 // At this point, we know that the cast source type is a pointer
7825 // to an array of the same type as the destination pointer
7826 // array. Because the array type is never stepped over (there
7827 // is a leading zero) we can fold the cast into this GEP.
7828 GEP.setOperand(0, X);
7829 return &GEP;
7830 }
7831 } else if (GEP.getNumOperands() == 2) {
7832 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007833 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7834 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007835 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7836 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7837 if (isa<ArrayType>(SrcElTy) &&
7838 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7839 TD->getTypeSize(ResElTy)) {
7840 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007841 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007842 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007843 // V and GEP are both pointer types --> BitCast
7844 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007845 }
Chris Lattner2a893292005-09-13 18:36:04 +00007846
7847 // Transform things like:
7848 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7849 // (where tmp = 8*tmp2) into:
7850 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7851
7852 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007853 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007854 uint64_t ArrayEltSize =
7855 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7856
7857 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7858 // allow either a mul, shift, or constant here.
7859 Value *NewIdx = 0;
7860 ConstantInt *Scale = 0;
7861 if (ArrayEltSize == 1) {
7862 NewIdx = GEP.getOperand(1);
7863 Scale = ConstantInt::get(NewIdx->getType(), 1);
7864 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007865 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007866 Scale = CI;
7867 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7868 if (Inst->getOpcode() == Instruction::Shl &&
7869 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007870 unsigned ShAmt =
7871 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007872 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007873 NewIdx = Inst->getOperand(0);
7874 } else if (Inst->getOpcode() == Instruction::Mul &&
7875 isa<ConstantInt>(Inst->getOperand(1))) {
7876 Scale = cast<ConstantInt>(Inst->getOperand(1));
7877 NewIdx = Inst->getOperand(0);
7878 }
7879 }
7880
7881 // If the index will be to exactly the right offset with the scale taken
7882 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007883 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007884 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007885 Scale = ConstantInt::get(Scale->getType(),
7886 Scale->getZExtValue() / ArrayEltSize);
7887 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007888 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7889 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007890 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7891 NewIdx = InsertNewInstBefore(Sc, GEP);
7892 }
7893
7894 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007895 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007896 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007897 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007898 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7899 // The NewGEP must be pointer typed, so must the old one -> BitCast
7900 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007901 }
7902 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007903 }
Chris Lattnerca081252001-12-14 16:52:21 +00007904 }
7905
Chris Lattnerca081252001-12-14 16:52:21 +00007906 return 0;
7907}
7908
Chris Lattner1085bdf2002-11-04 16:18:53 +00007909Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7910 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7911 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007912 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7913 const Type *NewTy =
7914 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007915 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007916
7917 // Create and insert the replacement instruction...
7918 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007919 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007920 else {
7921 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007922 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007923 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007924
7925 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007926
Chris Lattner1085bdf2002-11-04 16:18:53 +00007927 // Scan to the end of the allocation instructions, to skip over a block of
7928 // allocas if possible...
7929 //
7930 BasicBlock::iterator It = New;
7931 while (isa<AllocationInst>(*It)) ++It;
7932
7933 // Now that I is pointing to the first non-allocation-inst in the block,
7934 // insert our getelementptr instruction...
7935 //
Reid Spencerc635f472006-12-31 05:48:39 +00007936 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007937 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7938 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007939
7940 // Now make everything use the getelementptr instead of the original
7941 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007942 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007943 } else if (isa<UndefValue>(AI.getArraySize())) {
7944 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007945 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007946
7947 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7948 // Note that we only do this for alloca's, because malloc should allocate and
7949 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007950 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007951 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007952 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7953
Chris Lattner1085bdf2002-11-04 16:18:53 +00007954 return 0;
7955}
7956
Chris Lattner8427bff2003-12-07 01:24:23 +00007957Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7958 Value *Op = FI.getOperand(0);
7959
7960 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7961 if (CastInst *CI = dyn_cast<CastInst>(Op))
7962 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7963 FI.setOperand(0, CI->getOperand(0));
7964 return &FI;
7965 }
7966
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007967 // free undef -> unreachable.
7968 if (isa<UndefValue>(Op)) {
7969 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007970 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007971 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007972 return EraseInstFromFunction(FI);
7973 }
7974
Chris Lattnerf3a36602004-02-28 04:57:37 +00007975 // If we have 'free null' delete the instruction. This can happen in stl code
7976 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007977 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007978 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007979
Chris Lattner8427bff2003-12-07 01:24:23 +00007980 return 0;
7981}
7982
7983
Chris Lattner72684fe2005-01-31 05:51:45 +00007984/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007985static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7986 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007987 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007988
7989 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007990 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007991 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007992
Chris Lattner479a9fc2007-01-15 17:55:20 +00007993 if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
7994 isa<PointerType>(DestPTy) || isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007995 // If the source is an array, the code below will not succeed. Check to
7996 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7997 // constants.
7998 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7999 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8000 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008001 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008002 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8003 SrcTy = cast<PointerType>(CastOp->getType());
8004 SrcPTy = SrcTy->getElementType();
8005 }
8006
Chris Lattner479a9fc2007-01-15 17:55:20 +00008007 if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
8008 isa<PointerType>(SrcPTy) || isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008009 // Do not allow turning this into a load of an integer, which is then
8010 // casted to a pointer, this pessimizes pointer analysis a lot.
8011 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008012 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008013 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008014
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008015 // Okay, we are casting from one integer or pointer type to another of
8016 // the same size. Instead of casting the pointer before the load, cast
8017 // the result of the loaded value.
8018 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8019 CI->getName(),
8020 LI.isVolatile()),LI);
8021 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008022 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008023 }
Chris Lattner35e24772004-07-13 01:49:43 +00008024 }
8025 }
8026 return 0;
8027}
8028
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008029/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008030/// from this value cannot trap. If it is not obviously safe to load from the
8031/// specified pointer, we do a quick local scan of the basic block containing
8032/// ScanFrom, to determine if the address is already accessed.
8033static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8034 // If it is an alloca or global variable, it is always safe to load from.
8035 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8036
8037 // Otherwise, be a little bit agressive by scanning the local block where we
8038 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008039 // from/to. If so, the previous load or store would have already trapped,
8040 // so there is no harm doing an extra load (also, CSE will later eliminate
8041 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008042 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8043
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008044 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008045 --BBI;
8046
8047 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8048 if (LI->getOperand(0) == V) return true;
8049 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8050 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008051
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008052 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008053 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008054}
8055
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008056Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8057 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008058
Chris Lattnera9d84e32005-05-01 04:24:53 +00008059 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008060 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008061 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8062 return Res;
8063
8064 // None of the following transforms are legal for volatile loads.
8065 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008066
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008067 if (&LI.getParent()->front() != &LI) {
8068 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008069 // If the instruction immediately before this is a store to the same
8070 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008071 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8072 if (SI->getOperand(1) == LI.getOperand(0))
8073 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008074 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8075 if (LIB->getOperand(0) == LI.getOperand(0))
8076 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008077 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008078
8079 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8080 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8081 isa<UndefValue>(GEPI->getOperand(0))) {
8082 // Insert a new store to null instruction before the load to indicate
8083 // that this code is not reachable. We do this instead of inserting
8084 // an unreachable instruction directly because we cannot modify the
8085 // CFG.
8086 new StoreInst(UndefValue::get(LI.getType()),
8087 Constant::getNullValue(Op->getType()), &LI);
8088 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8089 }
8090
Chris Lattner81a7a232004-10-16 18:11:37 +00008091 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008092 // load null/undef -> undef
8093 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008094 // Insert a new store to null instruction before the load to indicate that
8095 // this code is not reachable. We do this instead of inserting an
8096 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008097 new StoreInst(UndefValue::get(LI.getType()),
8098 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008099 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008100 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008101
Chris Lattner81a7a232004-10-16 18:11:37 +00008102 // Instcombine load (constant global) into the value loaded.
8103 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8104 if (GV->isConstant() && !GV->isExternal())
8105 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008106
Chris Lattner81a7a232004-10-16 18:11:37 +00008107 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8108 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8109 if (CE->getOpcode() == Instruction::GetElementPtr) {
8110 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8111 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008112 if (Constant *V =
8113 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008114 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008115 if (CE->getOperand(0)->isNullValue()) {
8116 // Insert a new store to null instruction before the load to indicate
8117 // that this code is not reachable. We do this instead of inserting
8118 // an unreachable instruction directly because we cannot modify the
8119 // CFG.
8120 new StoreInst(UndefValue::get(LI.getType()),
8121 Constant::getNullValue(Op->getType()), &LI);
8122 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8123 }
8124
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008125 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008126 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8127 return Res;
8128 }
8129 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008130
Chris Lattnera9d84e32005-05-01 04:24:53 +00008131 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008132 // Change select and PHI nodes to select values instead of addresses: this
8133 // helps alias analysis out a lot, allows many others simplifications, and
8134 // exposes redundancy in the code.
8135 //
8136 // Note that we cannot do the transformation unless we know that the
8137 // introduced loads cannot trap! Something like this is valid as long as
8138 // the condition is always false: load (select bool %C, int* null, int* %G),
8139 // but it would not be valid if we transformed it to load from null
8140 // unconditionally.
8141 //
8142 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8143 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008144 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8145 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008146 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008147 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008148 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008149 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008150 return new SelectInst(SI->getCondition(), V1, V2);
8151 }
8152
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008153 // load (select (cond, null, P)) -> load P
8154 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8155 if (C->isNullValue()) {
8156 LI.setOperand(0, SI->getOperand(2));
8157 return &LI;
8158 }
8159
8160 // load (select (cond, P, null)) -> load P
8161 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8162 if (C->isNullValue()) {
8163 LI.setOperand(0, SI->getOperand(1));
8164 return &LI;
8165 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008166 }
8167 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008168 return 0;
8169}
8170
Reid Spencere928a152007-01-19 21:20:31 +00008171/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008172/// when possible.
8173static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8174 User *CI = cast<User>(SI.getOperand(1));
8175 Value *CastOp = CI->getOperand(0);
8176
8177 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8178 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8179 const Type *SrcPTy = SrcTy->getElementType();
8180
Chris Lattner479a9fc2007-01-15 17:55:20 +00008181 if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
8182 isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008183 // If the source is an array, the code below will not succeed. Check to
8184 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8185 // constants.
8186 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8187 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8188 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008189 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008190 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8191 SrcTy = cast<PointerType>(CastOp->getType());
8192 SrcPTy = SrcTy->getElementType();
8193 }
8194
Chris Lattner479a9fc2007-01-15 17:55:20 +00008195 if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
8196 isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008197 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008198 IC.getTargetData().getTypeSize(DestPTy)) {
8199
8200 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008201 // the same size. Instead of casting the pointer before
8202 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008203 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008204 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008205 Instruction::CastOps opcode = Instruction::BitCast;
8206 const Type* CastSrcTy = SIOp0->getType();
8207 const Type* CastDstTy = SrcPTy;
8208 if (isa<PointerType>(CastDstTy)) {
8209 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008210 opcode = Instruction::IntToPtr;
Reid Spencerc050af92007-01-18 18:54:33 +00008211 } else if (const IntegerType* DITy = dyn_cast<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008212 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008213 opcode = Instruction::PtrToInt;
Reid Spencerc050af92007-01-18 18:54:33 +00008214 else if (const IntegerType* SITy = dyn_cast<IntegerType>(CastSrcTy))
Reid Spencere928a152007-01-19 21:20:31 +00008215 if (SITy->getBitWidth() != DITy->getBitWidth())
8216 return 0; // Don't do this transform on unequal bit widths.
8217 // else, BitCast is fine
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008218 }
8219 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008220 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008221 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008222 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008223 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8224 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008225 return new StoreInst(NewCast, CastOp);
8226 }
8227 }
8228 }
8229 return 0;
8230}
8231
Chris Lattner31f486c2005-01-31 05:36:43 +00008232Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8233 Value *Val = SI.getOperand(0);
8234 Value *Ptr = SI.getOperand(1);
8235
8236 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008237 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008238 ++NumCombined;
8239 return 0;
8240 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008241
8242 // If the RHS is an alloca with a single use, zapify the store, making the
8243 // alloca dead.
8244 if (Ptr->hasOneUse()) {
8245 if (isa<AllocaInst>(Ptr)) {
8246 EraseInstFromFunction(SI);
8247 ++NumCombined;
8248 return 0;
8249 }
8250
8251 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8252 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8253 GEP->getOperand(0)->hasOneUse()) {
8254 EraseInstFromFunction(SI);
8255 ++NumCombined;
8256 return 0;
8257 }
8258 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008259
Chris Lattner5997cf92006-02-08 03:25:32 +00008260 // Do really simple DSE, to catch cases where there are several consequtive
8261 // stores to the same location, separated by a few arithmetic operations. This
8262 // situation often occurs with bitfield accesses.
8263 BasicBlock::iterator BBI = &SI;
8264 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8265 --ScanInsts) {
8266 --BBI;
8267
8268 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8269 // Prev store isn't volatile, and stores to the same location?
8270 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8271 ++NumDeadStore;
8272 ++BBI;
8273 EraseInstFromFunction(*PrevSI);
8274 continue;
8275 }
8276 break;
8277 }
8278
Chris Lattnerdab43b22006-05-26 19:19:20 +00008279 // If this is a load, we have to stop. However, if the loaded value is from
8280 // the pointer we're loading and is producing the pointer we're storing,
8281 // then *this* store is dead (X = load P; store X -> P).
8282 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8283 if (LI == Val && LI->getOperand(0) == Ptr) {
8284 EraseInstFromFunction(SI);
8285 ++NumCombined;
8286 return 0;
8287 }
8288 // Otherwise, this is a load from some other location. Stores before it
8289 // may not be dead.
8290 break;
8291 }
8292
Chris Lattner5997cf92006-02-08 03:25:32 +00008293 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008294 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008295 break;
8296 }
8297
8298
8299 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008300
8301 // store X, null -> turns into 'unreachable' in SimplifyCFG
8302 if (isa<ConstantPointerNull>(Ptr)) {
8303 if (!isa<UndefValue>(Val)) {
8304 SI.setOperand(0, UndefValue::get(Val->getType()));
8305 if (Instruction *U = dyn_cast<Instruction>(Val))
8306 WorkList.push_back(U); // Dropped a use.
8307 ++NumCombined;
8308 }
8309 return 0; // Do not modify these!
8310 }
8311
8312 // store undef, Ptr -> noop
8313 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008314 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008315 ++NumCombined;
8316 return 0;
8317 }
8318
Chris Lattner72684fe2005-01-31 05:51:45 +00008319 // If the pointer destination is a cast, see if we can fold the cast into the
8320 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008321 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008322 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8323 return Res;
8324 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008325 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008326 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8327 return Res;
8328
Chris Lattner219175c2005-09-12 23:23:25 +00008329
8330 // If this store is the last instruction in the basic block, and if the block
8331 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008332 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008333 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8334 if (BI->isUnconditional()) {
8335 // Check to see if the successor block has exactly two incoming edges. If
8336 // so, see if the other predecessor contains a store to the same location.
8337 // if so, insert a PHI node (if needed) and move the stores down.
8338 BasicBlock *Dest = BI->getSuccessor(0);
8339
8340 pred_iterator PI = pred_begin(Dest);
8341 BasicBlock *Other = 0;
8342 if (*PI != BI->getParent())
8343 Other = *PI;
8344 ++PI;
8345 if (PI != pred_end(Dest)) {
8346 if (*PI != BI->getParent())
8347 if (Other)
8348 Other = 0;
8349 else
8350 Other = *PI;
8351 if (++PI != pred_end(Dest))
8352 Other = 0;
8353 }
8354 if (Other) { // If only one other pred...
8355 BBI = Other->getTerminator();
8356 // Make sure this other block ends in an unconditional branch and that
8357 // there is an instruction before the branch.
8358 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8359 BBI != Other->begin()) {
8360 --BBI;
8361 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8362
8363 // If this instruction is a store to the same location.
8364 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8365 // Okay, we know we can perform this transformation. Insert a PHI
8366 // node now if we need it.
8367 Value *MergedVal = OtherStore->getOperand(0);
8368 if (MergedVal != SI.getOperand(0)) {
8369 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8370 PN->reserveOperandSpace(2);
8371 PN->addIncoming(SI.getOperand(0), SI.getParent());
8372 PN->addIncoming(OtherStore->getOperand(0), Other);
8373 MergedVal = InsertNewInstBefore(PN, Dest->front());
8374 }
8375
8376 // Advance to a place where it is safe to insert the new store and
8377 // insert it.
8378 BBI = Dest->begin();
8379 while (isa<PHINode>(BBI)) ++BBI;
8380 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8381 OtherStore->isVolatile()), *BBI);
8382
8383 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008384 EraseInstFromFunction(SI);
8385 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008386 ++NumCombined;
8387 return 0;
8388 }
8389 }
8390 }
8391 }
8392
Chris Lattner31f486c2005-01-31 05:36:43 +00008393 return 0;
8394}
8395
8396
Chris Lattner9eef8a72003-06-04 04:46:00 +00008397Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8398 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008399 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008400 BasicBlock *TrueDest;
8401 BasicBlock *FalseDest;
8402 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8403 !isa<Constant>(X)) {
8404 // Swap Destinations and condition...
8405 BI.setCondition(X);
8406 BI.setSuccessor(0, FalseDest);
8407 BI.setSuccessor(1, TrueDest);
8408 return &BI;
8409 }
8410
Reid Spencer266e42b2006-12-23 06:05:41 +00008411 // Cannonicalize fcmp_one -> fcmp_oeq
8412 FCmpInst::Predicate FPred; Value *Y;
8413 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8414 TrueDest, FalseDest)))
8415 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8416 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8417 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008418 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008419 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8420 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8421 // Swap Destinations and condition...
8422 BI.setCondition(NewSCC);
8423 BI.setSuccessor(0, FalseDest);
8424 BI.setSuccessor(1, TrueDest);
8425 removeFromWorkList(I);
8426 I->getParent()->getInstList().erase(I);
8427 WorkList.push_back(cast<Instruction>(NewSCC));
8428 return &BI;
8429 }
8430
8431 // Cannonicalize icmp_ne -> icmp_eq
8432 ICmpInst::Predicate IPred;
8433 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8434 TrueDest, FalseDest)))
8435 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8436 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8437 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8438 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8439 std::string Name = I->getName(); I->setName("");
8440 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8441 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008442 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008443 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008444 BI.setSuccessor(0, FalseDest);
8445 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008446 removeFromWorkList(I);
8447 I->getParent()->getInstList().erase(I);
8448 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008449 return &BI;
8450 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008451
Chris Lattner9eef8a72003-06-04 04:46:00 +00008452 return 0;
8453}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008454
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008455Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8456 Value *Cond = SI.getCondition();
8457 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8458 if (I->getOpcode() == Instruction::Add)
8459 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8460 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8461 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008462 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008463 AddRHS));
8464 SI.setOperand(0, I->getOperand(0));
8465 WorkList.push_back(I);
8466 return &SI;
8467 }
8468 }
8469 return 0;
8470}
8471
Chris Lattner6bc98652006-03-05 00:22:33 +00008472/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8473/// is to leave as a vector operation.
8474static bool CheapToScalarize(Value *V, bool isConstant) {
8475 if (isa<ConstantAggregateZero>(V))
8476 return true;
8477 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8478 if (isConstant) return true;
8479 // If all elts are the same, we can extract.
8480 Constant *Op0 = C->getOperand(0);
8481 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8482 if (C->getOperand(i) != Op0)
8483 return false;
8484 return true;
8485 }
8486 Instruction *I = dyn_cast<Instruction>(V);
8487 if (!I) return false;
8488
8489 // Insert element gets simplified to the inserted element or is deleted if
8490 // this is constant idx extract element and its a constant idx insertelt.
8491 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8492 isa<ConstantInt>(I->getOperand(2)))
8493 return true;
8494 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8495 return true;
8496 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8497 if (BO->hasOneUse() &&
8498 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8499 CheapToScalarize(BO->getOperand(1), isConstant)))
8500 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008501 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8502 if (CI->hasOneUse() &&
8503 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8504 CheapToScalarize(CI->getOperand(1), isConstant)))
8505 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008506
8507 return false;
8508}
8509
Chris Lattner12249be2006-05-25 23:48:38 +00008510/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8511/// elements into values that are larger than the #elts in the input.
8512static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8513 unsigned NElts = SVI->getType()->getNumElements();
8514 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8515 return std::vector<unsigned>(NElts, 0);
8516 if (isa<UndefValue>(SVI->getOperand(2)))
8517 return std::vector<unsigned>(NElts, 2*NElts);
8518
8519 std::vector<unsigned> Result;
8520 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8521 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8522 if (isa<UndefValue>(CP->getOperand(i)))
8523 Result.push_back(NElts*2); // undef -> 8
8524 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008525 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008526 return Result;
8527}
8528
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008529/// FindScalarElement - Given a vector and an element number, see if the scalar
8530/// value is already around as a register, for example if it were inserted then
8531/// extracted from the vector.
8532static Value *FindScalarElement(Value *V, unsigned EltNo) {
8533 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8534 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008535 unsigned Width = PTy->getNumElements();
8536 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008537 return UndefValue::get(PTy->getElementType());
8538
8539 if (isa<UndefValue>(V))
8540 return UndefValue::get(PTy->getElementType());
8541 else if (isa<ConstantAggregateZero>(V))
8542 return Constant::getNullValue(PTy->getElementType());
8543 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8544 return CP->getOperand(EltNo);
8545 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8546 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008547 if (!isa<ConstantInt>(III->getOperand(2)))
8548 return 0;
8549 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008550
8551 // If this is an insert to the element we are looking for, return the
8552 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008553 if (EltNo == IIElt)
8554 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008555
8556 // Otherwise, the insertelement doesn't modify the value, recurse on its
8557 // vector input.
8558 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008559 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008560 unsigned InEl = getShuffleMask(SVI)[EltNo];
8561 if (InEl < Width)
8562 return FindScalarElement(SVI->getOperand(0), InEl);
8563 else if (InEl < Width*2)
8564 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8565 else
8566 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008567 }
8568
8569 // Otherwise, we don't know.
8570 return 0;
8571}
8572
Robert Bocchinoa8352962006-01-13 22:48:06 +00008573Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008574
Chris Lattner92346c32006-03-31 18:25:14 +00008575 // If packed val is undef, replace extract with scalar undef.
8576 if (isa<UndefValue>(EI.getOperand(0)))
8577 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8578
8579 // If packed val is constant 0, replace extract with scalar 0.
8580 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8581 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8582
Robert Bocchinoa8352962006-01-13 22:48:06 +00008583 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8584 // If packed val is constant with uniform operands, replace EI
8585 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008586 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008587 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008588 if (C->getOperand(i) != op0) {
8589 op0 = 0;
8590 break;
8591 }
8592 if (op0)
8593 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008594 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008595
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008596 // If extracting a specified index from the vector, see if we can recursively
8597 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008598 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008599 // This instruction only demands the single element from the input vector.
8600 // If the input vector has a single use, simplify it based on this use
8601 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008602 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008603 if (EI.getOperand(0)->hasOneUse()) {
8604 uint64_t UndefElts;
8605 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008606 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008607 UndefElts)) {
8608 EI.setOperand(0, V);
8609 return &EI;
8610 }
8611 }
8612
Reid Spencere0fc4df2006-10-20 07:07:24 +00008613 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008614 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008615 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008616
Chris Lattner83f65782006-05-25 22:53:38 +00008617 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008618 if (I->hasOneUse()) {
8619 // Push extractelement into predecessor operation if legal and
8620 // profitable to do so
8621 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008622 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8623 if (CheapToScalarize(BO, isConstantElt)) {
8624 ExtractElementInst *newEI0 =
8625 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8626 EI.getName()+".lhs");
8627 ExtractElementInst *newEI1 =
8628 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8629 EI.getName()+".rhs");
8630 InsertNewInstBefore(newEI0, EI);
8631 InsertNewInstBefore(newEI1, EI);
8632 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8633 }
Reid Spencerde46e482006-11-02 20:25:50 +00008634 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008635 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008636 PointerType::get(EI.getType()), EI);
8637 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008638 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008639 InsertNewInstBefore(GEP, EI);
8640 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008641 }
8642 }
8643 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8644 // Extracting the inserted element?
8645 if (IE->getOperand(2) == EI.getOperand(1))
8646 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8647 // If the inserted and extracted elements are constants, they must not
8648 // be the same value, extract from the pre-inserted value instead.
8649 if (isa<Constant>(IE->getOperand(2)) &&
8650 isa<Constant>(EI.getOperand(1))) {
8651 AddUsesToWorkList(EI);
8652 EI.setOperand(0, IE->getOperand(0));
8653 return &EI;
8654 }
8655 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8656 // If this is extracting an element from a shufflevector, figure out where
8657 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008658 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8659 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008660 Value *Src;
8661 if (SrcIdx < SVI->getType()->getNumElements())
8662 Src = SVI->getOperand(0);
8663 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8664 SrcIdx -= SVI->getType()->getNumElements();
8665 Src = SVI->getOperand(1);
8666 } else {
8667 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008668 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008669 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008670 }
8671 }
Chris Lattner83f65782006-05-25 22:53:38 +00008672 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008673 return 0;
8674}
8675
Chris Lattner90951862006-04-16 00:51:47 +00008676/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8677/// elements from either LHS or RHS, return the shuffle mask and true.
8678/// Otherwise, return false.
8679static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8680 std::vector<Constant*> &Mask) {
8681 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8682 "Invalid CollectSingleShuffleElements");
8683 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8684
8685 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008686 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008687 return true;
8688 } else if (V == LHS) {
8689 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008690 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008691 return true;
8692 } else if (V == RHS) {
8693 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008694 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008695 return true;
8696 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8697 // If this is an insert of an extract from some other vector, include it.
8698 Value *VecOp = IEI->getOperand(0);
8699 Value *ScalarOp = IEI->getOperand(1);
8700 Value *IdxOp = IEI->getOperand(2);
8701
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008702 if (!isa<ConstantInt>(IdxOp))
8703 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008704 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008705
8706 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8707 // Okay, we can handle this if the vector we are insertinting into is
8708 // transitively ok.
8709 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8710 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008711 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008712 return true;
8713 }
8714 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8715 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008716 EI->getOperand(0)->getType() == V->getType()) {
8717 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008718 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008719
8720 // This must be extracting from either LHS or RHS.
8721 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8722 // Okay, we can handle this if the vector we are insertinting into is
8723 // transitively ok.
8724 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8725 // If so, update the mask to reflect the inserted value.
8726 if (EI->getOperand(0) == LHS) {
8727 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008728 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008729 } else {
8730 assert(EI->getOperand(0) == RHS);
8731 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008732 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008733
8734 }
8735 return true;
8736 }
8737 }
8738 }
8739 }
8740 }
8741 // TODO: Handle shufflevector here!
8742
8743 return false;
8744}
8745
8746/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8747/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8748/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008749static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008750 Value *&RHS) {
8751 assert(isa<PackedType>(V->getType()) &&
8752 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008753 "Invalid shuffle!");
8754 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8755
8756 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008757 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008758 return V;
8759 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008760 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008761 return V;
8762 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8763 // If this is an insert of an extract from some other vector, include it.
8764 Value *VecOp = IEI->getOperand(0);
8765 Value *ScalarOp = IEI->getOperand(1);
8766 Value *IdxOp = IEI->getOperand(2);
8767
8768 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8769 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8770 EI->getOperand(0)->getType() == V->getType()) {
8771 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008772 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8773 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008774
8775 // Either the extracted from or inserted into vector must be RHSVec,
8776 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008777 if (EI->getOperand(0) == RHS || RHS == 0) {
8778 RHS = EI->getOperand(0);
8779 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008780 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008781 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008782 return V;
8783 }
8784
Chris Lattner90951862006-04-16 00:51:47 +00008785 if (VecOp == RHS) {
8786 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008787 // Everything but the extracted element is replaced with the RHS.
8788 for (unsigned i = 0; i != NumElts; ++i) {
8789 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008790 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008791 }
8792 return V;
8793 }
Chris Lattner90951862006-04-16 00:51:47 +00008794
8795 // If this insertelement is a chain that comes from exactly these two
8796 // vectors, return the vector and the effective shuffle.
8797 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8798 return EI->getOperand(0);
8799
Chris Lattner39fac442006-04-15 01:39:45 +00008800 }
8801 }
8802 }
Chris Lattner90951862006-04-16 00:51:47 +00008803 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008804
8805 // Otherwise, can't do anything fancy. Return an identity vector.
8806 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008807 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008808 return V;
8809}
8810
8811Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8812 Value *VecOp = IE.getOperand(0);
8813 Value *ScalarOp = IE.getOperand(1);
8814 Value *IdxOp = IE.getOperand(2);
8815
8816 // If the inserted element was extracted from some other vector, and if the
8817 // indexes are constant, try to turn this into a shufflevector operation.
8818 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8819 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8820 EI->getOperand(0)->getType() == IE.getType()) {
8821 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008822 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8823 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008824
8825 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8826 return ReplaceInstUsesWith(IE, VecOp);
8827
8828 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8829 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8830
8831 // If we are extracting a value from a vector, then inserting it right
8832 // back into the same place, just use the input vector.
8833 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8834 return ReplaceInstUsesWith(IE, VecOp);
8835
8836 // We could theoretically do this for ANY input. However, doing so could
8837 // turn chains of insertelement instructions into a chain of shufflevector
8838 // instructions, and right now we do not merge shufflevectors. As such,
8839 // only do this in a situation where it is clear that there is benefit.
8840 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8841 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8842 // the values of VecOp, except then one read from EIOp0.
8843 // Build a new shuffle mask.
8844 std::vector<Constant*> Mask;
8845 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008846 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008847 else {
8848 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008849 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008850 NumVectorElts));
8851 }
Reid Spencerc635f472006-12-31 05:48:39 +00008852 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008853 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8854 ConstantPacked::get(Mask));
8855 }
8856
8857 // If this insertelement isn't used by some other insertelement, turn it
8858 // (and any insertelements it points to), into one big shuffle.
8859 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8860 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008861 Value *RHS = 0;
8862 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8863 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8864 // We now have a shuffle of LHS, RHS, Mask.
8865 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008866 }
8867 }
8868 }
8869
8870 return 0;
8871}
8872
8873
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008874Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8875 Value *LHS = SVI.getOperand(0);
8876 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008877 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008878
8879 bool MadeChange = false;
8880
Chris Lattner2deeaea2006-10-05 06:55:50 +00008881 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008882 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008883 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8884
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008885 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008886 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008887 if (isa<UndefValue>(SVI.getOperand(1))) {
8888 // Scan to see if there are any references to the RHS. If so, replace them
8889 // with undef element refs and set MadeChange to true.
8890 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8891 if (Mask[i] >= e && Mask[i] != 2*e) {
8892 Mask[i] = 2*e;
8893 MadeChange = true;
8894 }
8895 }
8896
8897 if (MadeChange) {
8898 // Remap any references to RHS to use LHS.
8899 std::vector<Constant*> Elts;
8900 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8901 if (Mask[i] == 2*e)
8902 Elts.push_back(UndefValue::get(Type::Int32Ty));
8903 else
8904 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8905 }
8906 SVI.setOperand(2, ConstantPacked::get(Elts));
8907 }
8908 }
Chris Lattner39fac442006-04-15 01:39:45 +00008909
Chris Lattner12249be2006-05-25 23:48:38 +00008910 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8911 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8912 if (LHS == RHS || isa<UndefValue>(LHS)) {
8913 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008914 // shuffle(undef,undef,mask) -> undef.
8915 return ReplaceInstUsesWith(SVI, LHS);
8916 }
8917
Chris Lattner12249be2006-05-25 23:48:38 +00008918 // Remap any references to RHS to use LHS.
8919 std::vector<Constant*> Elts;
8920 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008921 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008922 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008923 else {
8924 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8925 (Mask[i] < e && isa<UndefValue>(LHS)))
8926 Mask[i] = 2*e; // Turn into undef.
8927 else
8928 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008929 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008930 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008931 }
Chris Lattner12249be2006-05-25 23:48:38 +00008932 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008933 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008934 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008935 LHS = SVI.getOperand(0);
8936 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008937 MadeChange = true;
8938 }
8939
Chris Lattner0e477162006-05-26 00:29:06 +00008940 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008941 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008942
Chris Lattner12249be2006-05-25 23:48:38 +00008943 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8944 if (Mask[i] >= e*2) continue; // Ignore undef values.
8945 // Is this an identity shuffle of the LHS value?
8946 isLHSID &= (Mask[i] == i);
8947
8948 // Is this an identity shuffle of the RHS value?
8949 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008950 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008951
Chris Lattner12249be2006-05-25 23:48:38 +00008952 // Eliminate identity shuffles.
8953 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8954 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008955
Chris Lattner0e477162006-05-26 00:29:06 +00008956 // If the LHS is a shufflevector itself, see if we can combine it with this
8957 // one without producing an unusual shuffle. Here we are really conservative:
8958 // we are absolutely afraid of producing a shuffle mask not in the input
8959 // program, because the code gen may not be smart enough to turn a merged
8960 // shuffle into two specific shuffles: it may produce worse code. As such,
8961 // we only merge two shuffles if the result is one of the two input shuffle
8962 // masks. In this case, merging the shuffles just removes one instruction,
8963 // which we know is safe. This is good for things like turning:
8964 // (splat(splat)) -> splat.
8965 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8966 if (isa<UndefValue>(RHS)) {
8967 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8968
8969 std::vector<unsigned> NewMask;
8970 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8971 if (Mask[i] >= 2*e)
8972 NewMask.push_back(2*e);
8973 else
8974 NewMask.push_back(LHSMask[Mask[i]]);
8975
8976 // If the result mask is equal to the src shuffle or this shuffle mask, do
8977 // the replacement.
8978 if (NewMask == LHSMask || NewMask == Mask) {
8979 std::vector<Constant*> Elts;
8980 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8981 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008982 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008983 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008984 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008985 }
8986 }
8987 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8988 LHSSVI->getOperand(1),
8989 ConstantPacked::get(Elts));
8990 }
8991 }
8992 }
8993
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008994 return MadeChange ? &SVI : 0;
8995}
8996
8997
Robert Bocchinoa8352962006-01-13 22:48:06 +00008998
Chris Lattner99f48c62002-09-02 04:59:56 +00008999void InstCombiner::removeFromWorkList(Instruction *I) {
9000 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9001 WorkList.end());
9002}
9003
Chris Lattner39c98bb2004-12-08 23:43:58 +00009004
9005/// TryToSinkInstruction - Try to move the specified instruction from its
9006/// current block into the beginning of DestBlock, which can only happen if it's
9007/// safe to move the instruction past all of the instructions between it and the
9008/// end of its block.
9009static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9010 assert(I->hasOneUse() && "Invariants didn't hold!");
9011
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009012 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9013 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009014
Chris Lattner39c98bb2004-12-08 23:43:58 +00009015 // Do not sink alloca instructions out of the entry block.
9016 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9017 return false;
9018
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009019 // We can only sink load instructions if there is nothing between the load and
9020 // the end of block that could change the value.
9021 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009022 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9023 Scan != E; ++Scan)
9024 if (Scan->mayWriteToMemory())
9025 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009026 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009027
9028 BasicBlock::iterator InsertPos = DestBlock->begin();
9029 while (isa<PHINode>(InsertPos)) ++InsertPos;
9030
Chris Lattner9f269e42005-08-08 19:11:57 +00009031 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009032 ++NumSunkInst;
9033 return true;
9034}
9035
Chris Lattner1443bc52006-05-11 17:11:52 +00009036/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00009037/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00009038/// if possible.
9039static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9040 if (!TD) return CE;
9041
9042 Constant *Ptr = CE->getOperand(0);
9043 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9044 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9045 // If this is a constant expr gep that is effectively computing an
9046 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9047 bool isFoldableGEP = true;
9048 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9049 if (!isa<ConstantInt>(CE->getOperand(i)))
9050 isFoldableGEP = false;
9051 if (isFoldableGEP) {
9052 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9053 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00009054 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009055 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009056 }
9057 }
9058
9059 return CE;
9060}
9061
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009062
9063/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9064/// all reachable code to the worklist.
9065///
9066/// This has a couple of tricks to make the code faster and more powerful. In
9067/// particular, we constant fold and DCE instructions as we go, to avoid adding
9068/// them to the worklist (this significantly speeds up instcombine on code where
9069/// many instructions are dead or constant). Additionally, if we find a branch
9070/// whose condition is a known constant, we only visit the reachable successors.
9071///
9072static void AddReachableCodeToWorklist(BasicBlock *BB,
9073 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009074 std::vector<Instruction*> &WorkList,
9075 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009076 // We have now visited this block! If we've already been here, bail out.
9077 if (!Visited.insert(BB).second) return;
9078
9079 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9080 Instruction *Inst = BBI++;
9081
9082 // DCE instruction if trivially dead.
9083 if (isInstructionTriviallyDead(Inst)) {
9084 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009085 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009086 Inst->eraseFromParent();
9087 continue;
9088 }
9089
9090 // ConstantProp instruction if trivially constant.
9091 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009092 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9093 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009094 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009095 Inst->replaceAllUsesWith(C);
9096 ++NumConstProp;
9097 Inst->eraseFromParent();
9098 continue;
9099 }
9100
9101 WorkList.push_back(Inst);
9102 }
9103
9104 // Recursively visit successors. If this is a branch or switch on a constant,
9105 // only visit the reachable successor.
9106 TerminatorInst *TI = BB->getTerminator();
9107 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009108 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009109 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009110 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9111 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009112 return;
9113 }
9114 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9115 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9116 // See if this is an explicit destination.
9117 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9118 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009119 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009120 return;
9121 }
9122
9123 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009124 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009125 return;
9126 }
9127 }
9128
9129 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009130 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009131}
9132
Chris Lattner113f4f42002-06-25 16:13:24 +00009133bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009134 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009135 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009136
Chris Lattner4ed40f72005-07-07 20:40:38 +00009137 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009138 // Do a depth-first traversal of the function, populate the worklist with
9139 // the reachable instructions. Ignore blocks that are not reachable. Keep
9140 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009141 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009142 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009143
Chris Lattner4ed40f72005-07-07 20:40:38 +00009144 // Do a quick scan over the function. If we find any blocks that are
9145 // unreachable, remove any instructions inside of them. This prevents
9146 // the instcombine code from having to deal with some bad special cases.
9147 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9148 if (!Visited.count(BB)) {
9149 Instruction *Term = BB->getTerminator();
9150 while (Term != BB->begin()) { // Remove instrs bottom-up
9151 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009152
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009153 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009154 ++NumDeadInst;
9155
9156 if (!I->use_empty())
9157 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9158 I->eraseFromParent();
9159 }
9160 }
9161 }
Chris Lattnerca081252001-12-14 16:52:21 +00009162
9163 while (!WorkList.empty()) {
9164 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9165 WorkList.pop_back();
9166
Chris Lattner1443bc52006-05-11 17:11:52 +00009167 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009168 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009169 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009170 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009171 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009172 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009173
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009174 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009175
9176 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009177 removeFromWorkList(I);
9178 continue;
9179 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009180
Chris Lattner1443bc52006-05-11 17:11:52 +00009181 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009182 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009183 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9184 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009185 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009186
Chris Lattner1443bc52006-05-11 17:11:52 +00009187 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009188 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009189 ReplaceInstUsesWith(*I, C);
9190
Chris Lattner99f48c62002-09-02 04:59:56 +00009191 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009192 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009193 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009194 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009195 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009196
Chris Lattner39c98bb2004-12-08 23:43:58 +00009197 // See if we can trivially sink this instruction to a successor basic block.
9198 if (I->hasOneUse()) {
9199 BasicBlock *BB = I->getParent();
9200 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9201 if (UserParent != BB) {
9202 bool UserIsSuccessor = false;
9203 // See if the user is one of our successors.
9204 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9205 if (*SI == UserParent) {
9206 UserIsSuccessor = true;
9207 break;
9208 }
9209
9210 // If the user is one of our immediate successors, and if that successor
9211 // only has us as a predecessors (we'd have to split the critical edge
9212 // otherwise), we can keep going.
9213 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9214 next(pred_begin(UserParent)) == pred_end(UserParent))
9215 // Okay, the CFG is simple enough, try to sink this instruction.
9216 Changed |= TryToSinkInstruction(I, UserParent);
9217 }
9218 }
9219
Chris Lattnerca081252001-12-14 16:52:21 +00009220 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009221 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009222 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009223 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009224 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009225 DOUT << "IC: Old = " << *I
9226 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009227
Chris Lattner396dbfe2004-06-09 05:08:07 +00009228 // Everything uses the new instruction now.
9229 I->replaceAllUsesWith(Result);
9230
9231 // Push the new instruction and any users onto the worklist.
9232 WorkList.push_back(Result);
9233 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009234
9235 // Move the name to the new instruction first...
9236 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009237 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009238
9239 // Insert the new instruction into the basic block...
9240 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009241 BasicBlock::iterator InsertPos = I;
9242
9243 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9244 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9245 ++InsertPos;
9246
9247 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009248
Chris Lattner63d75af2004-05-01 23:27:23 +00009249 // Make sure that we reprocess all operands now that we reduced their
9250 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009251 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9252 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9253 WorkList.push_back(OpI);
9254
Chris Lattner396dbfe2004-06-09 05:08:07 +00009255 // Instructions can end up on the worklist more than once. Make sure
9256 // we do not process an instruction that has been deleted.
9257 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009258
9259 // Erase the old instruction.
9260 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009261 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009262 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009263
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009264 // If the instruction was modified, it's possible that it is now dead.
9265 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009266 if (isInstructionTriviallyDead(I)) {
9267 // Make sure we process all operands now that we are reducing their
9268 // use counts.
9269 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9270 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9271 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009272
Chris Lattner63d75af2004-05-01 23:27:23 +00009273 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009274 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009275 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009276 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009277 } else {
9278 WorkList.push_back(Result);
9279 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009280 }
Chris Lattner053c0932002-05-14 15:24:07 +00009281 }
Chris Lattner260ab202002-04-18 17:39:14 +00009282 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009283 }
9284 }
9285
Chris Lattner260ab202002-04-18 17:39:14 +00009286 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009287}
9288
Brian Gaeke38b79e82004-07-27 17:43:21 +00009289FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009290 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009291}
Brian Gaeke960707c2003-11-11 22:41:34 +00009292