blob: 92259a33d1e9fdc8635a2c375118dd3904342f84 [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 Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencer755d0e72007-03-26 17:44:01 +000059#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000062
Chris Lattner79a42ac2006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000068
Chris Lattner79a42ac2006-12-19 21:40:18 +000069namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattner260ab202002-04-18 17:39:14 +0000103
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000104
Chris Lattner51ea1272004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000113 }
114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000122 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000142
Chris Lattner260ab202002-04-18 17:39:14 +0000143 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000147
Chris Lattnerf12cc842002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000152 }
153
Chris Lattner69193f92004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattner260ab202002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnera74deaf2007-04-03 17:43:25 +0000186 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
187 Instruction *LHS,
188 ConstantInt *RHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000189
Reid Spencer266e42b2006-12-23 06:05:41 +0000190 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
191 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000192 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000193 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000194 Instruction *commonCastTransforms(CastInst &CI);
195 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattner74ff60f2007-04-11 06:57:46 +0000196 Instruction *visitTrunc(TruncInst &CI);
197 Instruction *visitZExt(ZExtInst &CI);
198 Instruction *visitSExt(SExtInst &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000199 Instruction *visitFPTrunc(CastInst &CI);
200 Instruction *visitFPExt(CastInst &CI);
201 Instruction *visitFPToUI(CastInst &CI);
202 Instruction *visitFPToSI(CastInst &CI);
203 Instruction *visitUIToFP(CastInst &CI);
204 Instruction *visitSIToFP(CastInst &CI);
205 Instruction *visitPtrToInt(CastInst &CI);
206 Instruction *visitIntToPtr(CastInst &CI);
207 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000208 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
209 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000210 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000211 Instruction *visitCallInst(CallInst &CI);
212 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000213 Instruction *visitPHINode(PHINode &PN);
214 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000215 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000216 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000217 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000218 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000219 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000220 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000221 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000222 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000223 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000224
225 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000226 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000227
Chris Lattner970c33a2003-06-19 17:00:31 +0000228 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000229 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000230 bool transformConstExprCastCall(CallSite CS);
231
Chris Lattner69193f92004-04-05 01:30:19 +0000232 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000233 // InsertNewInstBefore - insert an instruction New before instruction Old
234 // in the program. Add the new instruction to the worklist.
235 //
Chris Lattner623826c2004-09-28 21:48:02 +0000236 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000237 assert(New && New->getParent() == 0 &&
238 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000239 BasicBlock *BB = Old.getParent();
240 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000241 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000242 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000243 }
244
Chris Lattner7e794272004-09-24 15:21:34 +0000245 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
246 /// This also adds the cast to the worklist. Finally, this returns the
247 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000248 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
249 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000250 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000251
Chris Lattnere79d2492006-04-06 19:19:17 +0000252 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000253 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000254
Reid Spencer13bc5d72006-12-12 09:18:51 +0000255 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000256 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000257 return C;
258 }
259
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000260 // ReplaceInstUsesWith - This method is to be used when an instruction is
261 // found to be dead, replacable with another preexisting expression. Here
262 // we add all uses of I to the worklist, replace all uses of I with the new
263 // value, then return I, so that the inst combiner will know that I was
264 // modified.
265 //
266 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000267 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000268 if (&I != V) {
269 I.replaceAllUsesWith(V);
270 return &I;
271 } else {
272 // If we are replacing the instruction with itself, this must be in a
273 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000274 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000275 return &I;
276 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000277 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000278
Chris Lattner2590e512006-02-07 06:56:34 +0000279 // UpdateValueUsesWith - This method is to be used when an value is
280 // found to be replacable with another preexisting expression or was
281 // updated. Here we add all uses of I to the worklist, replace all uses of
282 // I with the new value (unless the instruction was just updated), then
283 // return true, so that the inst combiner will know that I was modified.
284 //
285 bool UpdateValueUsesWith(Value *Old, Value *New) {
286 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
287 if (Old != New)
288 Old->replaceAllUsesWith(New);
289 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000290 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000291 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000292 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000293 return true;
294 }
295
Chris Lattner51ea1272004-02-28 05:22:00 +0000296 // EraseInstFromFunction - When dealing with an instruction that has side
297 // effects or produces a void value, we can't rely on DCE to delete the
298 // instruction. Instead, visit methods should return the value returned by
299 // this function.
300 Instruction *EraseInstFromFunction(Instruction &I) {
301 assert(I.use_empty() && "Cannot erase instruction that is used!");
302 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000303 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000304 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000305 return 0; // Don't do anything with FI
306 }
307
Chris Lattner3ac7c262003-08-13 20:16:26 +0000308 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000309 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
310 /// InsertBefore instruction. This is specialized a bit to avoid inserting
311 /// casts that are known to not do anything...
312 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000313 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
314 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000315 Instruction *InsertBefore);
316
Reid Spencer266e42b2006-12-23 06:05:41 +0000317 /// SimplifyCommutative - This performs a few simplifications for
318 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000319 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000320
Reid Spencer266e42b2006-12-23 06:05:41 +0000321 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
322 /// most-complex to least-complex order.
323 bool SimplifyCompare(CmpInst &I);
324
Reid Spencer959a21d2007-03-23 21:24:59 +0000325 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
326 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000327 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
328 APInt& KnownZero, APInt& KnownOne,
329 unsigned Depth = 0);
330
Chris Lattner2deeaea2006-10-05 06:55:50 +0000331 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
332 uint64_t &UndefElts, unsigned Depth = 0);
333
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000334 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
335 // PHI node as operand #0, see if we can fold the instruction into the PHI
336 // (which is only possible if all operands to the PHI are constants).
337 Instruction *FoldOpIntoPhi(Instruction &I);
338
Chris Lattner7515cab2004-11-14 19:13:23 +0000339 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
340 // operator and they all are only used by the PHI, PHI together their
341 // inputs, and do the operation once, to the result of the PHI.
342 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000343 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
344
345
Zhou Sheng75b871f2007-01-11 12:24:14 +0000346 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
347 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000348
Zhou Sheng75b871f2007-01-11 12:24:14 +0000349 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000350 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000351 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000352 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000353 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000354 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner14a251b2007-04-15 00:07:55 +0000355 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000356
Reid Spencer74a528b2006-12-13 18:21:21 +0000357 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000358 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000359
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000360 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000361}
362
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000363// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000364// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000365static unsigned getComplexity(Value *V) {
366 if (isa<Instruction>(V)) {
367 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000368 return 3;
369 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000370 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000371 if (isa<Argument>(V)) return 3;
372 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000373}
Chris Lattner260ab202002-04-18 17:39:14 +0000374
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375// isOnlyUse - Return true if this instruction will be deleted if we stop using
376// it.
377static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000378 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000379}
380
Chris Lattnere79e8542004-02-23 06:38:22 +0000381// getPromotedType - Return the specified type promoted as it would be to pass
382// though a va_arg area...
383static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000384 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
385 if (ITy->getBitWidth() < 32)
386 return Type::Int32Ty;
387 } else if (Ty == Type::FloatTy)
388 return Type::DoubleTy;
389 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000390}
391
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000392/// getBitCastOperand - If the specified operand is a CastInst or a constant
393/// expression bitcast, return the operand value, otherwise return null.
394static Value *getBitCastOperand(Value *V) {
395 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000396 return I->getOperand(0);
397 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000398 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000399 return CE->getOperand(0);
400 return 0;
401}
402
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000403/// This function is a wrapper around CastInst::isEliminableCastPair. It
404/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000405static Instruction::CastOps
406isEliminableCastPair(
407 const CastInst *CI, ///< The first cast instruction
408 unsigned opcode, ///< The opcode of the second cast instruction
409 const Type *DstTy, ///< The target type for the second cast instruction
410 TargetData *TD ///< The target data for pointer size
411) {
412
413 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
414 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000415
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000416 // Get the opcodes of the two Cast instructions
417 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
418 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000419
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000420 return Instruction::CastOps(
421 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
422 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000423}
424
425/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
426/// in any code being generated. It does not require codegen if V is simple
427/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000428static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
429 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000430 if (V->getType() == Ty || isa<Constant>(V)) return false;
431
Chris Lattner99155be2006-05-25 23:24:33 +0000432 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000433 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000434 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000435 return false;
436 return true;
437}
438
439/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
440/// InsertBefore instruction. This is specialized a bit to avoid inserting
441/// casts that are known to not do anything...
442///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000443Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
444 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445 Instruction *InsertBefore) {
446 if (V->getType() == DestTy) return V;
447 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000448 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000449
Reid Spencer13bc5d72006-12-12 09:18:51 +0000450 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000451}
452
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000453// SimplifyCommutative - This performs a few simplifications for commutative
454// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000455//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456// 1. Order operands such that they are listed from right (least complex) to
457// left (most complex). This puts constants before unary operators before
458// binary operators.
459//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000460// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
461// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000462//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000463bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000464 bool Changed = false;
465 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
466 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000467
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000468 if (!I.isAssociative()) return Changed;
469 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000470 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
471 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
472 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000473 Constant *Folded = ConstantExpr::get(I.getOpcode(),
474 cast<Constant>(I.getOperand(1)),
475 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000476 I.setOperand(0, Op->getOperand(0));
477 I.setOperand(1, Folded);
478 return true;
479 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
480 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
481 isOnlyUse(Op) && isOnlyUse(Op1)) {
482 Constant *C1 = cast<Constant>(Op->getOperand(1));
483 Constant *C2 = cast<Constant>(Op1->getOperand(1));
484
485 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000486 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
488 Op1->getOperand(0),
489 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000490 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000491 I.setOperand(0, New);
492 I.setOperand(1, Folded);
493 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000494 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000495 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000496 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000497}
Chris Lattnerca081252001-12-14 16:52:21 +0000498
Reid Spencer266e42b2006-12-23 06:05:41 +0000499/// SimplifyCompare - For a CmpInst this function just orders the operands
500/// so that theyare listed from right (least complex) to left (most complex).
501/// This puts constants before unary operators before binary operators.
502bool InstCombiner::SimplifyCompare(CmpInst &I) {
503 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
504 return false;
505 I.swapOperands();
506 // Compare instructions are not associative so there's nothing else we can do.
507 return true;
508}
509
Chris Lattnerbb74e222003-03-10 23:06:50 +0000510// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
511// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000512//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000513static inline Value *dyn_castNegVal(Value *V) {
514 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000515 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516
Chris Lattner9ad0d552004-12-14 20:08:06 +0000517 // Constants can be considered to be negated values if they can be folded.
518 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
519 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000520 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000521}
522
Chris Lattnerbb74e222003-03-10 23:06:50 +0000523static inline Value *dyn_castNotVal(Value *V) {
524 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000525 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000526
527 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000528 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000529 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000530 return 0;
531}
532
Chris Lattner7fb29e12003-03-11 00:12:48 +0000533// dyn_castFoldableMul - If this value is a multiply that can be folded into
534// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000535// non-constant operand of the multiply, and set CST to point to the multiplier.
536// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000539 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000541 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000542 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000543 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000544 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000545 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000546 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000547 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000548 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000549 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000550 return I->getOperand(0);
551 }
552 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000553 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000554}
Chris Lattner31ae8632002-08-14 17:51:49 +0000555
Chris Lattner0798af32005-01-13 20:14:25 +0000556/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
557/// expression, return it.
558static User *dyn_castGetElementPtr(Value *V) {
559 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
560 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
561 if (CE->getOpcode() == Instruction::GetElementPtr)
562 return cast<User>(V);
563 return false;
564}
565
Reid Spencer80263aa2007-03-25 05:33:51 +0000566/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000567static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000568 APInt Val(C->getValue());
569 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000570}
Reid Spencer80263aa2007-03-25 05:33:51 +0000571/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000572static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000573 APInt Val(C->getValue());
574 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000575}
576/// Add - Add two ConstantInts together
577static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
578 return ConstantInt::get(C1->getValue() + C2->getValue());
579}
580/// And - Bitwise AND two ConstantInts together
581static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
582 return ConstantInt::get(C1->getValue() & C2->getValue());
583}
584/// Subtract - Subtract one ConstantInt from another
585static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
586 return ConstantInt::get(C1->getValue() - C2->getValue());
587}
588/// Multiply - Multiply two ConstantInts together
589static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
590 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000591}
592
Chris Lattner4534dd592006-02-09 07:38:58 +0000593/// ComputeMaskedBits - Determine which of the bits specified in Mask are
594/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000595/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
596/// processing.
597/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
598/// we cannot optimize based on the assumption that it is zero without changing
599/// it to be an explicit zero. If we don't change it to zero, other code could
600/// optimized based on the contradictory assumption that it is non-zero.
601/// Because instcombine aggressively folds operations with undef args anyway,
602/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000603static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000604 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000605 assert(V && "No Value?");
606 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000607 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000608 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000609 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000610 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000611 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000612 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
613 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000614 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000615 KnownZero = ~KnownOne & Mask;
616 return;
617 }
618
Reid Spenceraa696402007-03-08 01:46:38 +0000619 if (Depth == 6 || Mask == 0)
620 return; // Limit search depth.
621
622 Instruction *I = dyn_cast<Instruction>(V);
623 if (!I) return;
624
Zhou Shengaf4341d2007-03-13 02:23:10 +0000625 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000626 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000627
628 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000629 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000630 // If either the LHS or the RHS are Zero, the result is zero.
631 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000632 APInt Mask2(Mask & ~KnownZero);
633 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000634 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
635 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
636
637 // Output known-1 bits are only known if set in both the LHS & RHS.
638 KnownOne &= KnownOne2;
639 // Output known-0 are known to be clear if zero in either the LHS | RHS.
640 KnownZero |= KnownZero2;
641 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000642 }
643 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000644 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000645 APInt Mask2(Mask & ~KnownOne);
646 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000647 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
648 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
649
650 // Output known-0 bits are only known if clear in both the LHS & RHS.
651 KnownZero &= KnownZero2;
652 // Output known-1 are known to be set if set in either the LHS | RHS.
653 KnownOne |= KnownOne2;
654 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000655 }
Reid Spenceraa696402007-03-08 01:46:38 +0000656 case Instruction::Xor: {
657 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
658 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
659 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
660 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
661
662 // Output known-0 bits are known if clear or set in both the LHS & RHS.
663 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
664 // Output known-1 are known to be set if set in only one of the LHS, RHS.
665 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
666 KnownZero = KnownZeroOut;
667 return;
668 }
669 case Instruction::Select:
670 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
671 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
673 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
674
675 // Only known if known in both the LHS and RHS.
676 KnownOne &= KnownOne2;
677 KnownZero &= KnownZero2;
678 return;
679 case Instruction::FPTrunc:
680 case Instruction::FPExt:
681 case Instruction::FPToUI:
682 case Instruction::FPToSI:
683 case Instruction::SIToFP:
684 case Instruction::PtrToInt:
685 case Instruction::UIToFP:
686 case Instruction::IntToPtr:
687 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000688 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000689 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000690 uint32_t SrcBitWidth =
691 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000692 APInt MaskIn(Mask);
693 MaskIn.zext(SrcBitWidth);
694 KnownZero.zext(SrcBitWidth);
695 KnownOne.zext(SrcBitWidth);
696 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000697 KnownZero.trunc(BitWidth);
698 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000699 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000700 }
Reid Spenceraa696402007-03-08 01:46:38 +0000701 case Instruction::BitCast: {
702 const Type *SrcTy = I->getOperand(0)->getType();
703 if (SrcTy->isInteger()) {
704 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
705 return;
706 }
707 break;
708 }
709 case Instruction::ZExt: {
710 // Compute the bits in the result that are not present in the input.
711 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000712 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000713
Zhou Sheng57e3f732007-03-28 02:19:03 +0000714 APInt MaskIn(Mask);
715 MaskIn.trunc(SrcBitWidth);
716 KnownZero.trunc(SrcBitWidth);
717 KnownOne.trunc(SrcBitWidth);
718 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000721 KnownZero.zext(BitWidth);
722 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000723 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000724 return;
725 }
726 case Instruction::SExt: {
727 // Compute the bits in the result that are not present in the input.
728 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000729 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000730
Zhou Sheng57e3f732007-03-28 02:19:03 +0000731 APInt MaskIn(Mask);
732 MaskIn.trunc(SrcBitWidth);
733 KnownZero.trunc(SrcBitWidth);
734 KnownOne.trunc(SrcBitWidth);
735 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000736 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000737 KnownZero.zext(BitWidth);
738 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000739
740 // If the sign bit of the input is known set or clear, then we know the
741 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000742 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000743 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000744 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000745 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000746 return;
747 }
748 case Instruction::Shl:
749 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
750 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +0000751 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencerd8aad612007-03-25 02:03:12 +0000752 APInt Mask2(Mask.lshr(ShiftAmt));
753 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000754 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000755 KnownZero <<= ShiftAmt;
756 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000757 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000758 return;
759 }
760 break;
761 case Instruction::LShr:
762 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
763 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
764 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000765 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000766
767 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000768 APInt Mask2(Mask.shl(ShiftAmt));
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000770 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
771 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
772 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000773 // high bits known zero.
774 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000775 return;
776 }
777 break;
778 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000779 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000780 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
781 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000782 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000783
784 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000785 APInt Mask2(Mask.shl(ShiftAmt));
786 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000787 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
788 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
789 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
790
Zhou Sheng57e3f732007-03-28 02:19:03 +0000791 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
792 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000793 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000794 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000795 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000796 return;
797 }
798 break;
799 }
800}
801
Reid Spencerbb5741f2007-03-08 01:52:58 +0000802/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
803/// this predicate to simplify operations downstream. Mask is known to be zero
804/// for bits that V cannot have.
805static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000806 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000807 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
808 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
809 return (KnownZero & Mask) == Mask;
810}
811
Chris Lattner0157e7f2006-02-11 09:31:47 +0000812/// ShrinkDemandedConstant - Check to see if the specified operand of the
813/// specified instruction is a constant integer. If so, check to see if there
814/// are any bits set in the constant that are not demanded. If so, shrink the
815/// constant and return true.
816static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000817 APInt Demanded) {
818 assert(I && "No instruction?");
819 assert(OpNo < I->getNumOperands() && "Operand index too large");
820
821 // If the operand is not a constant integer, nothing to do.
822 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
823 if (!OpC) return false;
824
825 // If there are no bits set that aren't demanded, nothing to do.
826 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
827 if ((~Demanded & OpC->getValue()) == 0)
828 return false;
829
830 // This instruction is producing bits that are not demanded. Shrink the RHS.
831 Demanded &= OpC->getValue();
832 I->setOperand(OpNo, ConstantInt::get(Demanded));
833 return true;
834}
835
Chris Lattneree0f2802006-02-12 02:07:56 +0000836// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
837// set of known zero and one bits, compute the maximum and minimum values that
838// could have the specified known zero and known one bits, returning them in
839// min/max.
840static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000841 const APInt& KnownZero,
842 const APInt& KnownOne,
843 APInt& Min, APInt& Max) {
844 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
845 assert(KnownZero.getBitWidth() == BitWidth &&
846 KnownOne.getBitWidth() == BitWidth &&
847 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
848 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000849 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000850
Chris Lattneree0f2802006-02-12 02:07:56 +0000851 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
852 // bit if it is unknown.
853 Min = KnownOne;
854 Max = KnownOne|UnknownBits;
855
Zhou Shengc2d33092007-03-28 05:15:57 +0000856 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000857 Min.set(BitWidth-1);
858 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000859 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000860}
861
862// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
863// a set of known zero and one bits, compute the maximum and minimum values that
864// could have the specified known zero and known one bits, returning them in
865// min/max.
866static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000867 const APInt& KnownZero,
868 const APInt& KnownOne,
869 APInt& Min,
870 APInt& Max) {
871 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
872 assert(KnownZero.getBitWidth() == BitWidth &&
873 KnownOne.getBitWidth() == BitWidth &&
874 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
875 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000876 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000877
878 // The minimum value is when the unknown bits are all zeros.
879 Min = KnownOne;
880 // The maximum value is when the unknown bits are all ones.
881 Max = KnownOne|UnknownBits;
882}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883
Reid Spencer1791f232007-03-12 17:25:59 +0000884/// SimplifyDemandedBits - This function attempts to replace V with a simpler
885/// value based on the demanded bits. When this function is called, it is known
886/// that only the bits set in DemandedMask of the result of V are ever used
887/// downstream. Consequently, depending on the mask and V, it may be possible
888/// to replace V with a constant or one of its operands. In such cases, this
889/// function does the replacement and returns true. In all other cases, it
890/// returns false after analyzing the expression and setting KnownOne and known
891/// to be one in the expression. KnownZero contains all the bits that are known
892/// to be zero in the expression. These are provided to potentially allow the
893/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
894/// the expression. KnownOne and KnownZero always follow the invariant that
895/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
896/// the bits in KnownOne and KnownZero may only be accurate for those bits set
897/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
898/// and KnownOne must all be the same.
899bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
900 APInt& KnownZero, APInt& KnownOne,
901 unsigned Depth) {
902 assert(V != 0 && "Null pointer of Value???");
903 assert(Depth <= 6 && "Limit Search Depth");
904 uint32_t BitWidth = DemandedMask.getBitWidth();
905 const IntegerType *VTy = cast<IntegerType>(V->getType());
906 assert(VTy->getBitWidth() == BitWidth &&
907 KnownZero.getBitWidth() == BitWidth &&
908 KnownOne.getBitWidth() == BitWidth &&
909 "Value *V, DemandedMask, KnownZero and KnownOne \
910 must have same BitWidth");
911 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
912 // We know all of the bits for a constant!
913 KnownOne = CI->getValue() & DemandedMask;
914 KnownZero = ~KnownOne & DemandedMask;
915 return false;
916 }
917
Zhou Shengb9128442007-03-14 03:21:24 +0000918 KnownZero.clear();
919 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000920 if (!V->hasOneUse()) { // Other users may use these bits.
921 if (Depth != 0) { // Not at the root.
922 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
923 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
924 return false;
925 }
926 // If this is the root being simplified, allow it to have multiple uses,
927 // just set the DemandedMask to all bits.
928 DemandedMask = APInt::getAllOnesValue(BitWidth);
929 } else if (DemandedMask == 0) { // Not demanding any bits from V.
930 if (V != UndefValue::get(VTy))
931 return UpdateValueUsesWith(V, UndefValue::get(VTy));
932 return false;
933 } else if (Depth == 6) { // Limit search depth.
934 return false;
935 }
936
937 Instruction *I = dyn_cast<Instruction>(V);
938 if (!I) return false; // Only analyze instructions.
939
Reid Spencer1791f232007-03-12 17:25:59 +0000940 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
941 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
942 switch (I->getOpcode()) {
943 default: break;
944 case Instruction::And:
945 // If either the LHS or the RHS are Zero, the result is zero.
946 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
947 RHSKnownZero, RHSKnownOne, Depth+1))
948 return true;
949 assert((RHSKnownZero & RHSKnownOne) == 0 &&
950 "Bits known to be one AND zero?");
951
952 // If something is known zero on the RHS, the bits aren't demanded on the
953 // LHS.
954 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
955 LHSKnownZero, LHSKnownOne, Depth+1))
956 return true;
957 assert((LHSKnownZero & LHSKnownOne) == 0 &&
958 "Bits known to be one AND zero?");
959
960 // If all of the demanded bits are known 1 on one side, return the other.
961 // These bits cannot contribute to the result of the 'and'.
962 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
963 (DemandedMask & ~LHSKnownZero))
964 return UpdateValueUsesWith(I, I->getOperand(0));
965 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
966 (DemandedMask & ~RHSKnownZero))
967 return UpdateValueUsesWith(I, I->getOperand(1));
968
969 // If all of the demanded bits in the inputs are known zeros, return zero.
970 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
971 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
972
973 // If the RHS is a constant, see if we can simplify it.
974 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
975 return UpdateValueUsesWith(I, I);
976
977 // Output known-1 bits are only known if set in both the LHS & RHS.
978 RHSKnownOne &= LHSKnownOne;
979 // Output known-0 are known to be clear if zero in either the LHS | RHS.
980 RHSKnownZero |= LHSKnownZero;
981 break;
982 case Instruction::Or:
983 // If either the LHS or the RHS are One, the result is One.
984 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
985 RHSKnownZero, RHSKnownOne, Depth+1))
986 return true;
987 assert((RHSKnownZero & RHSKnownOne) == 0 &&
988 "Bits known to be one AND zero?");
989 // If something is known one on the RHS, the bits aren't demanded on the
990 // LHS.
991 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
992 LHSKnownZero, LHSKnownOne, Depth+1))
993 return true;
994 assert((LHSKnownZero & LHSKnownOne) == 0 &&
995 "Bits known to be one AND zero?");
996
997 // If all of the demanded bits are known zero on one side, return the other.
998 // These bits cannot contribute to the result of the 'or'.
999 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1000 (DemandedMask & ~LHSKnownOne))
1001 return UpdateValueUsesWith(I, I->getOperand(0));
1002 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1003 (DemandedMask & ~RHSKnownOne))
1004 return UpdateValueUsesWith(I, I->getOperand(1));
1005
1006 // If all of the potentially set bits on one side are known to be set on
1007 // the other side, just use the 'other' side.
1008 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1009 (DemandedMask & (~RHSKnownZero)))
1010 return UpdateValueUsesWith(I, I->getOperand(0));
1011 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1012 (DemandedMask & (~LHSKnownZero)))
1013 return UpdateValueUsesWith(I, I->getOperand(1));
1014
1015 // If the RHS is a constant, see if we can simplify it.
1016 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1017 return UpdateValueUsesWith(I, I);
1018
1019 // Output known-0 bits are only known if clear in both the LHS & RHS.
1020 RHSKnownZero &= LHSKnownZero;
1021 // Output known-1 are known to be set if set in either the LHS | RHS.
1022 RHSKnownOne |= LHSKnownOne;
1023 break;
1024 case Instruction::Xor: {
1025 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1026 RHSKnownZero, RHSKnownOne, Depth+1))
1027 return true;
1028 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1029 "Bits known to be one AND zero?");
1030 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1031 LHSKnownZero, LHSKnownOne, Depth+1))
1032 return true;
1033 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1034 "Bits known to be one AND zero?");
1035
1036 // If all of the demanded bits are known zero on one side, return the other.
1037 // These bits cannot contribute to the result of the 'xor'.
1038 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1039 return UpdateValueUsesWith(I, I->getOperand(0));
1040 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1041 return UpdateValueUsesWith(I, I->getOperand(1));
1042
1043 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1044 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1045 (RHSKnownOne & LHSKnownOne);
1046 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1047 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1048 (RHSKnownOne & LHSKnownZero);
1049
1050 // If all of the demanded bits are known to be zero on one side or the
1051 // other, turn this into an *inclusive* or.
1052 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1053 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1054 Instruction *Or =
1055 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1056 I->getName());
1057 InsertNewInstBefore(Or, *I);
1058 return UpdateValueUsesWith(I, Or);
1059 }
1060
1061 // If all of the demanded bits on one side are known, and all of the set
1062 // bits on that side are also known to be set on the other side, turn this
1063 // into an AND, as we know the bits will be cleared.
1064 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1065 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1066 // all known
1067 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1068 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1069 Instruction *And =
1070 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1071 InsertNewInstBefore(And, *I);
1072 return UpdateValueUsesWith(I, And);
1073 }
1074 }
1075
1076 // If the RHS is a constant, see if we can simplify it.
1077 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1078 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1079 return UpdateValueUsesWith(I, I);
1080
1081 RHSKnownZero = KnownZeroOut;
1082 RHSKnownOne = KnownOneOut;
1083 break;
1084 }
1085 case Instruction::Select:
1086 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1087 RHSKnownZero, RHSKnownOne, Depth+1))
1088 return true;
1089 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1090 LHSKnownZero, LHSKnownOne, Depth+1))
1091 return true;
1092 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1093 "Bits known to be one AND zero?");
1094 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1095 "Bits known to be one AND zero?");
1096
1097 // If the operands are constants, see if we can simplify them.
1098 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1099 return UpdateValueUsesWith(I, I);
1100 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1101 return UpdateValueUsesWith(I, I);
1102
1103 // Only known if known in both the LHS and RHS.
1104 RHSKnownOne &= LHSKnownOne;
1105 RHSKnownZero &= LHSKnownZero;
1106 break;
1107 case Instruction::Trunc: {
1108 uint32_t truncBf =
1109 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +00001110 DemandedMask.zext(truncBf);
1111 RHSKnownZero.zext(truncBf);
1112 RHSKnownOne.zext(truncBf);
1113 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1114 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001115 return true;
1116 DemandedMask.trunc(BitWidth);
1117 RHSKnownZero.trunc(BitWidth);
1118 RHSKnownOne.trunc(BitWidth);
1119 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1120 "Bits known to be one AND zero?");
1121 break;
1122 }
1123 case Instruction::BitCast:
1124 if (!I->getOperand(0)->getType()->isInteger())
1125 return false;
1126
1127 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1))
1129 return true;
1130 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1131 "Bits known to be one AND zero?");
1132 break;
1133 case Instruction::ZExt: {
1134 // Compute the bits in the result that are not present in the input.
1135 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001136 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001137
Zhou Sheng444af492007-03-29 04:45:55 +00001138 DemandedMask.trunc(SrcBitWidth);
1139 RHSKnownZero.trunc(SrcBitWidth);
1140 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001143 return true;
1144 DemandedMask.zext(BitWidth);
1145 RHSKnownZero.zext(BitWidth);
1146 RHSKnownOne.zext(BitWidth);
1147 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1148 "Bits known to be one AND zero?");
1149 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001150 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001151 break;
1152 }
1153 case Instruction::SExt: {
1154 // Compute the bits in the result that are not present in the input.
1155 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001156 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001157
Reid Spencer1791f232007-03-12 17:25:59 +00001158 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001159 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001160
Zhou Shenga4475572007-03-29 02:26:30 +00001161 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001162 // If any of the sign extended bits are demanded, we know that the sign
1163 // bit is demanded.
1164 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001165 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001166
Zhou Sheng444af492007-03-29 04:45:55 +00001167 InputDemandedBits.trunc(SrcBitWidth);
1168 RHSKnownZero.trunc(SrcBitWidth);
1169 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001170 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1171 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001172 return true;
1173 InputDemandedBits.zext(BitWidth);
1174 RHSKnownZero.zext(BitWidth);
1175 RHSKnownOne.zext(BitWidth);
1176 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1177 "Bits known to be one AND zero?");
1178
1179 // If the sign bit of the input is known set or clear, then we know the
1180 // top bits of the result.
1181
1182 // If the input sign bit is known zero, or if the NewBits are not demanded
1183 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001184 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001185 {
1186 // Convert to ZExt cast
1187 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1188 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001189 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001190 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001191 }
1192 break;
1193 }
1194 case Instruction::Add: {
1195 // Figure out what the input bits are. If the top bits of the and result
1196 // are not demanded, then the add doesn't demand them from its input
1197 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001198 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001199
1200 // If there is a constant on the RHS, there are a variety of xformations
1201 // we can do.
1202 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1203 // If null, this should be simplified elsewhere. Some of the xforms here
1204 // won't work if the RHS is zero.
1205 if (RHS->isZero())
1206 break;
1207
1208 // If the top bit of the output is demanded, demand everything from the
1209 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001210 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001211
1212 // Find information about known zero/one bits in the input.
1213 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1214 LHSKnownZero, LHSKnownOne, Depth+1))
1215 return true;
1216
1217 // If the RHS of the add has bits set that can't affect the input, reduce
1218 // the constant.
1219 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1220 return UpdateValueUsesWith(I, I);
1221
1222 // Avoid excess work.
1223 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1224 break;
1225
1226 // Turn it into OR if input bits are zero.
1227 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1228 Instruction *Or =
1229 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1230 I->getName());
1231 InsertNewInstBefore(Or, *I);
1232 return UpdateValueUsesWith(I, Or);
1233 }
1234
1235 // We can say something about the output known-zero and known-one bits,
1236 // depending on potential carries from the input constant and the
1237 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1238 // bits set and the RHS constant is 0x01001, then we know we have a known
1239 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1240
1241 // To compute this, we first compute the potential carry bits. These are
1242 // the bits which may be modified. I'm not aware of a better way to do
1243 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001244 const APInt& RHSVal = RHS->getValue();
1245 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001246
1247 // Now that we know which bits have carries, compute the known-1/0 sets.
1248
1249 // Bits are known one if they are known zero in one operand and one in the
1250 // other, and there is no input carry.
1251 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1252 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1253
1254 // Bits are known zero if they are known zero in both operands and there
1255 // is no input carry.
1256 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1257 } else {
1258 // If the high-bits of this ADD are not demanded, then it does not demand
1259 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001260 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001261 // Right fill the mask of bits for this ADD to demand the most
1262 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001263 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001264 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1265 LHSKnownZero, LHSKnownOne, Depth+1))
1266 return true;
1267 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1268 LHSKnownZero, LHSKnownOne, Depth+1))
1269 return true;
1270 }
1271 }
1272 break;
1273 }
1274 case Instruction::Sub:
1275 // If the high-bits of this SUB are not demanded, then it does not demand
1276 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001277 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001278 // Right fill the mask of bits for this SUB to demand the most
1279 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001280 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001281 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001282 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1283 LHSKnownZero, LHSKnownOne, Depth+1))
1284 return true;
1285 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1286 LHSKnownZero, LHSKnownOne, Depth+1))
1287 return true;
1288 }
1289 break;
1290 case Instruction::Shl:
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001292 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001293 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1294 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
1296 return true;
1297 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1298 "Bits known to be one AND zero?");
1299 RHSKnownZero <<= ShiftAmt;
1300 RHSKnownOne <<= ShiftAmt;
1301 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001302 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001303 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001304 }
1305 break;
1306 case Instruction::LShr:
1307 // For a logical shift right
1308 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001309 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001310
Reid Spencer1791f232007-03-12 17:25:59 +00001311 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001312 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1313 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001314 RHSKnownZero, RHSKnownOne, Depth+1))
1315 return true;
1316 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1317 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001318 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1319 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001320 if (ShiftAmt) {
1321 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001322 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001323 RHSKnownZero |= HighBits; // high bits known zero.
1324 }
Reid Spencer1791f232007-03-12 17:25:59 +00001325 }
1326 break;
1327 case Instruction::AShr:
1328 // If this is an arithmetic shift right and only the low-bit is set, we can
1329 // always convert this into a logical shr, even if the shift amount is
1330 // variable. The low bit of the shift cannot be an input sign bit unless
1331 // the shift amount is >= the size of the datatype, which is undefined.
1332 if (DemandedMask == 1) {
1333 // Perform the logical shift right.
1334 Value *NewVal = BinaryOperator::createLShr(
1335 I->getOperand(0), I->getOperand(1), I->getName());
1336 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1337 return UpdateValueUsesWith(I, NewVal);
1338 }
1339
1340 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001341 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001342
Reid Spencer1791f232007-03-12 17:25:59 +00001343 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001344 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001345 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001346 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001347 RHSKnownZero, RHSKnownOne, Depth+1))
1348 return true;
1349 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1350 "Bits known to be one AND zero?");
1351 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001352 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001353 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1354 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1355
1356 // Handle the sign bits.
1357 APInt SignBit(APInt::getSignBit(BitWidth));
1358 // Adjust to where it is now in the mask.
1359 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1360
1361 // If the input sign bit is known to be zero, or if none of the top bits
1362 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001363 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001364 (HighBits & ~DemandedMask) == HighBits) {
1365 // Perform the logical shift right.
1366 Value *NewVal = BinaryOperator::createLShr(
1367 I->getOperand(0), SA, I->getName());
1368 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1369 return UpdateValueUsesWith(I, NewVal);
1370 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1371 RHSKnownOne |= HighBits;
1372 }
1373 }
1374 break;
1375 }
1376
1377 // If the client is only demanding bits that we know, return the known
1378 // constant.
1379 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1380 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1381 return false;
1382}
1383
Chris Lattner2deeaea2006-10-05 06:55:50 +00001384
1385/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1386/// 64 or fewer elements. DemandedElts contains the set of elements that are
1387/// actually used by the caller. This method analyzes which elements of the
1388/// operand are undef and returns that information in UndefElts.
1389///
1390/// If the information about demanded elements can be used to simplify the
1391/// operation, the operation is simplified, then the resultant value is
1392/// returned. This returns null if no change was made.
1393Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1394 uint64_t &UndefElts,
1395 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001396 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001397 assert(VWidth <= 64 && "Vector too wide to analyze!");
1398 uint64_t EltMask = ~0ULL >> (64-VWidth);
1399 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1400 "Invalid DemandedElts!");
1401
1402 if (isa<UndefValue>(V)) {
1403 // If the entire vector is undefined, just return this info.
1404 UndefElts = EltMask;
1405 return 0;
1406 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1407 UndefElts = EltMask;
1408 return UndefValue::get(V->getType());
1409 }
1410
1411 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001412 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1413 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001414 Constant *Undef = UndefValue::get(EltTy);
1415
1416 std::vector<Constant*> Elts;
1417 for (unsigned i = 0; i != VWidth; ++i)
1418 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1419 Elts.push_back(Undef);
1420 UndefElts |= (1ULL << i);
1421 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1422 Elts.push_back(Undef);
1423 UndefElts |= (1ULL << i);
1424 } else { // Otherwise, defined.
1425 Elts.push_back(CP->getOperand(i));
1426 }
1427
1428 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001429 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001430 return NewCP != CP ? NewCP : 0;
1431 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001432 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001433 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001434 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001435 Constant *Zero = Constant::getNullValue(EltTy);
1436 Constant *Undef = UndefValue::get(EltTy);
1437 std::vector<Constant*> Elts;
1438 for (unsigned i = 0; i != VWidth; ++i)
1439 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1440 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001441 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001442 }
1443
1444 if (!V->hasOneUse()) { // Other users may use these bits.
1445 if (Depth != 0) { // Not at the root.
1446 // TODO: Just compute the UndefElts information recursively.
1447 return false;
1448 }
1449 return false;
1450 } else if (Depth == 10) { // Limit search depth.
1451 return false;
1452 }
1453
1454 Instruction *I = dyn_cast<Instruction>(V);
1455 if (!I) return false; // Only analyze instructions.
1456
1457 bool MadeChange = false;
1458 uint64_t UndefElts2;
1459 Value *TmpV;
1460 switch (I->getOpcode()) {
1461 default: break;
1462
1463 case Instruction::InsertElement: {
1464 // If this is a variable index, we don't know which element it overwrites.
1465 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001466 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001467 if (Idx == 0) {
1468 // Note that we can't propagate undef elt info, because we don't know
1469 // which elt is getting updated.
1470 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1471 UndefElts2, Depth+1);
1472 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1473 break;
1474 }
1475
1476 // If this is inserting an element that isn't demanded, remove this
1477 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001478 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001479 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1480 return AddSoonDeadInstToWorklist(*I, 0);
1481
1482 // Otherwise, the element inserted overwrites whatever was there, so the
1483 // input demanded set is simpler than the output set.
1484 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1485 DemandedElts & ~(1ULL << IdxNo),
1486 UndefElts, Depth+1);
1487 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1488
1489 // The inserted element is defined.
1490 UndefElts |= 1ULL << IdxNo;
1491 break;
1492 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001493 case Instruction::BitCast: {
1494 // Packed->packed casts only.
1495 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1496 if (!VTy) break;
1497 unsigned InVWidth = VTy->getNumElements();
1498 uint64_t InputDemandedElts = 0;
1499 unsigned Ratio;
1500
1501 if (VWidth == InVWidth) {
1502 // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1503 // elements as are demanded of us.
1504 Ratio = 1;
1505 InputDemandedElts = DemandedElts;
1506 } else if (VWidth > InVWidth) {
1507 // Untested so far.
1508 break;
1509
1510 // If there are more elements in the result than there are in the source,
1511 // then an input element is live if any of the corresponding output
1512 // elements are live.
1513 Ratio = VWidth/InVWidth;
1514 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1515 if (DemandedElts & (1ULL << OutIdx))
1516 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1517 }
1518 } else {
1519 // Untested so far.
1520 break;
1521
1522 // If there are more elements in the source than there are in the result,
1523 // then an input element is live if the corresponding output element is
1524 // live.
1525 Ratio = InVWidth/VWidth;
1526 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1527 if (DemandedElts & (1ULL << InIdx/Ratio))
1528 InputDemandedElts |= 1ULL << InIdx;
1529 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001530
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001531 // div/rem demand all inputs, because they don't want divide by zero.
1532 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1533 UndefElts2, Depth+1);
1534 if (TmpV) {
1535 I->setOperand(0, TmpV);
1536 MadeChange = true;
1537 }
1538
1539 UndefElts = UndefElts2;
1540 if (VWidth > InVWidth) {
1541 assert(0 && "Unimp");
1542 // If there are more elements in the result than there are in the source,
1543 // then an output element is undef if the corresponding input element is
1544 // undef.
1545 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1546 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1547 UndefElts |= 1ULL << OutIdx;
1548 } else if (VWidth < InVWidth) {
1549 assert(0 && "Unimp");
1550 // If there are more elements in the source than there are in the result,
1551 // then a result element is undef if all of the corresponding input
1552 // elements are undef.
1553 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1554 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1555 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1556 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1557 }
1558 break;
1559 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001560 case Instruction::And:
1561 case Instruction::Or:
1562 case Instruction::Xor:
1563 case Instruction::Add:
1564 case Instruction::Sub:
1565 case Instruction::Mul:
1566 // div/rem demand all inputs, because they don't want divide by zero.
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1568 UndefElts, Depth+1);
1569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1571 UndefElts2, Depth+1);
1572 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1573
1574 // Output elements are undefined if both are undefined. Consider things
1575 // like undef&0. The result is known zero, not undef.
1576 UndefElts &= UndefElts2;
1577 break;
1578
1579 case Instruction::Call: {
1580 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1581 if (!II) break;
1582 switch (II->getIntrinsicID()) {
1583 default: break;
1584
1585 // Binary vector operations that work column-wise. A dest element is a
1586 // function of the corresponding input elements from the two inputs.
1587 case Intrinsic::x86_sse_sub_ss:
1588 case Intrinsic::x86_sse_mul_ss:
1589 case Intrinsic::x86_sse_min_ss:
1590 case Intrinsic::x86_sse_max_ss:
1591 case Intrinsic::x86_sse2_sub_sd:
1592 case Intrinsic::x86_sse2_mul_sd:
1593 case Intrinsic::x86_sse2_min_sd:
1594 case Intrinsic::x86_sse2_max_sd:
1595 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1596 UndefElts, Depth+1);
1597 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1598 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1599 UndefElts2, Depth+1);
1600 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1601
1602 // If only the low elt is demanded and this is a scalarizable intrinsic,
1603 // scalarize it now.
1604 if (DemandedElts == 1) {
1605 switch (II->getIntrinsicID()) {
1606 default: break;
1607 case Intrinsic::x86_sse_sub_ss:
1608 case Intrinsic::x86_sse_mul_ss:
1609 case Intrinsic::x86_sse2_sub_sd:
1610 case Intrinsic::x86_sse2_mul_sd:
1611 // TODO: Lower MIN/MAX/ABS/etc
1612 Value *LHS = II->getOperand(1);
1613 Value *RHS = II->getOperand(2);
1614 // Extract the element as scalars.
1615 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1616 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1617
1618 switch (II->getIntrinsicID()) {
1619 default: assert(0 && "Case stmts out of sync!");
1620 case Intrinsic::x86_sse_sub_ss:
1621 case Intrinsic::x86_sse2_sub_sd:
1622 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1623 II->getName()), *II);
1624 break;
1625 case Intrinsic::x86_sse_mul_ss:
1626 case Intrinsic::x86_sse2_mul_sd:
1627 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1628 II->getName()), *II);
1629 break;
1630 }
1631
1632 Instruction *New =
1633 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1634 II->getName());
1635 InsertNewInstBefore(New, *II);
1636 AddSoonDeadInstToWorklist(*II, 0);
1637 return New;
1638 }
1639 }
1640
1641 // Output elements are undefined if both are undefined. Consider things
1642 // like undef&0. The result is known zero, not undef.
1643 UndefElts &= UndefElts2;
1644 break;
1645 }
1646 break;
1647 }
1648 }
1649 return MadeChange ? I : 0;
1650}
1651
Reid Spencer266e42b2006-12-23 06:05:41 +00001652/// @returns true if the specified compare instruction is
1653/// true when both operands are equal...
1654/// @brief Determine if the ICmpInst returns true if both operands are equal
1655static bool isTrueWhenEqual(ICmpInst &ICI) {
1656 ICmpInst::Predicate pred = ICI.getPredicate();
1657 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1658 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1659 pred == ICmpInst::ICMP_SLE;
1660}
1661
Chris Lattnerb8b97502003-08-13 19:01:45 +00001662/// AssociativeOpt - Perform an optimization on an associative operator. This
1663/// function is designed to check a chain of associative operators for a
1664/// potential to apply a certain optimization. Since the optimization may be
1665/// applicable if the expression was reassociated, this checks the chain, then
1666/// reassociates the expression as necessary to expose the optimization
1667/// opportunity. This makes use of a special Functor, which must define
1668/// 'shouldApply' and 'apply' methods.
1669///
1670template<typename Functor>
1671Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1672 unsigned Opcode = Root.getOpcode();
1673 Value *LHS = Root.getOperand(0);
1674
1675 // Quick check, see if the immediate LHS matches...
1676 if (F.shouldApply(LHS))
1677 return F.apply(Root);
1678
1679 // Otherwise, if the LHS is not of the same opcode as the root, return.
1680 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001681 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001682 // Should we apply this transform to the RHS?
1683 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1684
1685 // If not to the RHS, check to see if we should apply to the LHS...
1686 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1687 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1688 ShouldApply = true;
1689 }
1690
1691 // If the functor wants to apply the optimization to the RHS of LHSI,
1692 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1693 if (ShouldApply) {
1694 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001695
Chris Lattnerb8b97502003-08-13 19:01:45 +00001696 // Now all of the instructions are in the current basic block, go ahead
1697 // and perform the reassociation.
1698 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1699
1700 // First move the selected RHS to the LHS of the root...
1701 Root.setOperand(0, LHSI->getOperand(1));
1702
1703 // Make what used to be the LHS of the root be the user of the root...
1704 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001705 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001706 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1707 return 0;
1708 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001709 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001710 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001711 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1712 BasicBlock::iterator ARI = &Root; ++ARI;
1713 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1714 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001715
1716 // Now propagate the ExtraOperand down the chain of instructions until we
1717 // get to LHSI.
1718 while (TmpLHSI != LHSI) {
1719 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001720 // Move the instruction to immediately before the chain we are
1721 // constructing to avoid breaking dominance properties.
1722 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1723 BB->getInstList().insert(ARI, NextLHSI);
1724 ARI = NextLHSI;
1725
Chris Lattnerb8b97502003-08-13 19:01:45 +00001726 Value *NextOp = NextLHSI->getOperand(1);
1727 NextLHSI->setOperand(1, ExtraOperand);
1728 TmpLHSI = NextLHSI;
1729 ExtraOperand = NextOp;
1730 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001731
Chris Lattnerb8b97502003-08-13 19:01:45 +00001732 // Now that the instructions are reassociated, have the functor perform
1733 // the transformation...
1734 return F.apply(Root);
1735 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001736
Chris Lattnerb8b97502003-08-13 19:01:45 +00001737 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1738 }
1739 return 0;
1740}
1741
1742
1743// AddRHS - Implements: X + X --> X << 1
1744struct AddRHS {
1745 Value *RHS;
1746 AddRHS(Value *rhs) : RHS(rhs) {}
1747 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1748 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001749 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001750 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001751 }
1752};
1753
1754// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1755// iff C1&C2 == 0
1756struct AddMaskingAnd {
1757 Constant *C2;
1758 AddMaskingAnd(Constant *c) : C2(c) {}
1759 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001760 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001761 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001762 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001763 }
1764 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001765 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001766 }
1767};
1768
Chris Lattner86102b82005-01-01 16:22:27 +00001769static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001770 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001771 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001772 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001773 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001774
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001775 return IC->InsertNewInstBefore(CastInst::create(
1776 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001777 }
1778
Chris Lattner183b3362004-04-09 19:05:30 +00001779 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001780 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1781 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001782
Chris Lattner183b3362004-04-09 19:05:30 +00001783 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1784 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001785 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1786 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001787 }
1788
1789 Value *Op0 = SO, *Op1 = ConstOperand;
1790 if (!ConstIsRHS)
1791 std::swap(Op0, Op1);
1792 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001793 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1794 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001795 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1796 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1797 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001798 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001799 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001800 abort();
1801 }
Chris Lattner86102b82005-01-01 16:22:27 +00001802 return IC->InsertNewInstBefore(New, I);
1803}
1804
1805// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1806// constant as the other operand, try to fold the binary operator into the
1807// select arguments. This also works for Cast instructions, which obviously do
1808// not have a second operand.
1809static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1810 InstCombiner *IC) {
1811 // Don't modify shared select instructions
1812 if (!SI->hasOneUse()) return 0;
1813 Value *TV = SI->getOperand(1);
1814 Value *FV = SI->getOperand(2);
1815
1816 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001817 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001818 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001819
Chris Lattner86102b82005-01-01 16:22:27 +00001820 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1821 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1822
1823 return new SelectInst(SI->getCondition(), SelectTrueVal,
1824 SelectFalseVal);
1825 }
1826 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001827}
1828
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001829
1830/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1831/// node as operand #0, see if we can fold the instruction into the PHI (which
1832/// is only possible if all operands to the PHI are constants).
1833Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1834 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001835 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001836 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001837
Chris Lattner04689872006-09-09 22:02:56 +00001838 // Check to see if all of the operands of the PHI are constants. If there is
1839 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001840 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001841 BasicBlock *NonConstBB = 0;
1842 for (unsigned i = 0; i != NumPHIValues; ++i)
1843 if (!isa<Constant>(PN->getIncomingValue(i))) {
1844 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001845 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001846 NonConstBB = PN->getIncomingBlock(i);
1847
1848 // If the incoming non-constant value is in I's block, we have an infinite
1849 // loop.
1850 if (NonConstBB == I.getParent())
1851 return 0;
1852 }
1853
1854 // If there is exactly one non-constant value, we can insert a copy of the
1855 // operation in that block. However, if this is a critical edge, we would be
1856 // inserting the computation one some other paths (e.g. inside a loop). Only
1857 // do this if the pred block is unconditionally branching into the phi block.
1858 if (NonConstBB) {
1859 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1860 if (!BI || !BI->isUnconditional()) return 0;
1861 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001862
1863 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001864 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001865 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001866 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001867 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001868
1869 // Next, add all of the operands to the PHI.
1870 if (I.getNumOperands() == 2) {
1871 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001872 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001873 Value *InV;
1874 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001875 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1876 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1877 else
1878 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001879 } else {
1880 assert(PN->getIncomingBlock(i) == NonConstBB);
1881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1882 InV = BinaryOperator::create(BO->getOpcode(),
1883 PN->getIncomingValue(i), C, "phitmp",
1884 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001885 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1886 InV = CmpInst::create(CI->getOpcode(),
1887 CI->getPredicate(),
1888 PN->getIncomingValue(i), C, "phitmp",
1889 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001890 else
1891 assert(0 && "Unknown binop!");
1892
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001893 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001894 }
1895 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001896 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001897 } else {
1898 CastInst *CI = cast<CastInst>(&I);
1899 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001900 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001901 Value *InV;
1902 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001903 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001904 } else {
1905 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001906 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1907 I.getType(), "phitmp",
1908 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001909 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001910 }
1911 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001912 }
1913 }
1914 return ReplaceInstUsesWith(I, NewPN);
1915}
1916
Chris Lattner113f4f42002-06-25 16:13:24 +00001917Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001918 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001919 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001920
Chris Lattnercf4a9962004-04-10 22:01:55 +00001921 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001922 // X + undef -> undef
1923 if (isa<UndefValue>(RHS))
1924 return ReplaceInstUsesWith(I, RHS);
1925
Chris Lattnercf4a9962004-04-10 22:01:55 +00001926 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001927 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001928 if (RHSC->isNullValue())
1929 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001930 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1931 if (CFP->isExactlyValue(-0.0))
1932 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001934
Chris Lattnercf4a9962004-04-10 22:01:55 +00001935 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001936 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001937 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00001938 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00001939 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001940 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001941
1942 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1943 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001944 if (!isa<VectorType>(I.getType())) {
1945 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1946 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1947 KnownZero, KnownOne))
1948 return &I;
1949 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001950 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001951
1952 if (isa<PHINode>(LHS))
1953 if (Instruction *NV = FoldOpIntoPhi(I))
1954 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001955
Chris Lattner330628a2006-01-06 17:59:59 +00001956 ConstantInt *XorRHS = 0;
1957 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001958 if (isa<ConstantInt>(RHSC) &&
1959 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00001960 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001961 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00001962
Zhou Sheng56cda952007-04-02 08:20:41 +00001963 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00001964 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1965 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001966 do {
1967 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001968 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1969 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001970 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1971 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001972 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00001973 if (!MaskedValueIsZero(XorLHS,
1974 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001975 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001976 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001977 }
1978 }
1979 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001980 C0080Val = APIntOps::lshr(C0080Val, Size);
1981 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1982 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001983
Reid Spencera5c18bf2007-03-28 01:36:16 +00001984 // FIXME: This shouldn't be necessary. When the backends can handle types
1985 // with funny bit widths then this whole cascade of if statements should
1986 // be removed. It is just here to get the size of the "middle" type back
1987 // up to something that the back ends can handle.
1988 const Type *MiddleType = 0;
1989 switch (Size) {
1990 default: break;
1991 case 32: MiddleType = Type::Int32Ty; break;
1992 case 16: MiddleType = Type::Int16Ty; break;
1993 case 8: MiddleType = Type::Int8Ty; break;
1994 }
1995 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001996 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001997 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001998 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001999 }
2000 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002001 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002002
Chris Lattnerb8b97502003-08-13 19:01:45 +00002003 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002004 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002005 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002006
2007 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2008 if (RHSI->getOpcode() == Instruction::Sub)
2009 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2010 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2011 }
2012 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2013 if (LHSI->getOpcode() == Instruction::Sub)
2014 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2015 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2016 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002017 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002018
Chris Lattner147e9752002-05-08 22:46:53 +00002019 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002020 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002021 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002022
2023 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002024 if (!isa<Constant>(RHS))
2025 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002026 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002027
Misha Brukmanb1c93172005-04-21 23:48:37 +00002028
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002029 ConstantInt *C2;
2030 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2031 if (X == RHS) // X*C + X --> X * (C+1)
2032 return BinaryOperator::createMul(RHS, AddOne(C2));
2033
2034 // X*C1 + X*C2 --> X * (C1+C2)
2035 ConstantInt *C1;
2036 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00002037 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002038 }
2039
2040 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002041 if (dyn_castFoldableMul(RHS, C2) == LHS)
2042 return BinaryOperator::createMul(LHS, AddOne(C2));
2043
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002044 // X + ~X --> -1 since ~X = -X-1
2045 if (dyn_castNotVal(LHS) == RHS ||
2046 dyn_castNotVal(RHS) == LHS)
2047 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2048
Chris Lattner57c8d992003-02-18 19:57:07 +00002049
Chris Lattnerb8b97502003-08-13 19:01:45 +00002050 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002051 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002052 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2053 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002054
Chris Lattnerb9cde762003-10-02 15:11:26 +00002055 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002056 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002057 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2058 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002059
Chris Lattnerbff91d92004-10-08 05:07:56 +00002060 // (X & FF00) + xx00 -> (X+xx00) & FF00
2061 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002062 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002063 if (Anded == CRHS) {
2064 // See if all bits from the first bit set in the Add RHS up are included
2065 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002066 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002067
2068 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002069 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002070
2071 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002072 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002073
Chris Lattnerbff91d92004-10-08 05:07:56 +00002074 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2075 // Okay, the xform is safe. Insert the new add pronto.
2076 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2077 LHS->getName()), I);
2078 return BinaryOperator::createAnd(NewAdd, C2);
2079 }
2080 }
2081 }
2082
Chris Lattnerd4252a72004-07-30 07:50:03 +00002083 // Try to fold constant add into select arguments.
2084 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002085 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002086 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002087 }
2088
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002089 // add (cast *A to intptrtype) B ->
2090 // cast (GEP (cast *A to sbyte*) B) ->
2091 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002092 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002093 CastInst *CI = dyn_cast<CastInst>(LHS);
2094 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002095 if (!CI) {
2096 CI = dyn_cast<CastInst>(RHS);
2097 Other = LHS;
2098 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002099 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002100 (CI->getType()->getPrimitiveSizeInBits() ==
2101 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002102 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002103 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002104 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002105 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002106 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002107 }
2108 }
2109
Chris Lattner113f4f42002-06-25 16:13:24 +00002110 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002111}
2112
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002113// isSignBit - Return true if the value represented by the constant only has the
2114// highest order bit set.
2115static bool isSignBit(ConstantInt *CI) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002116 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002117 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002118}
2119
Chris Lattner113f4f42002-06-25 16:13:24 +00002120Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002122
Chris Lattnere6794492002-08-12 21:17:25 +00002123 if (Op0 == Op1) // sub X, X -> 0
2124 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002125
Chris Lattnere6794492002-08-12 21:17:25 +00002126 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002127 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002128 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002129
Chris Lattner81a7a232004-10-16 18:11:37 +00002130 if (isa<UndefValue>(Op0))
2131 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2132 if (isa<UndefValue>(Op1))
2133 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2134
Chris Lattner8f2f5982003-11-05 01:06:05 +00002135 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2136 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002137 if (C->isAllOnesValue())
2138 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002139
Chris Lattner8f2f5982003-11-05 01:06:05 +00002140 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002141 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002142 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002143 return BinaryOperator::createAdd(X, AddOne(C));
2144
Chris Lattner27df1db2007-01-15 07:02:54 +00002145 // -(X >>u 31) -> (X >>s 31)
2146 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002147 if (C->isZero()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002148 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002149 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002150 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002151 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002152 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002153 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002154 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002155 return BinaryOperator::create(Instruction::AShr,
2156 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002157 }
2158 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002159 }
2160 else if (SI->getOpcode() == Instruction::AShr) {
2161 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2162 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002163 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002164 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002165 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002166 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002167 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002168 }
2169 }
2170 }
Chris Lattner022167f2004-03-13 00:11:49 +00002171 }
Chris Lattner183b3362004-04-09 19:05:30 +00002172
2173 // Try to fold constant sub into select arguments.
2174 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002175 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002176 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002177
2178 if (isa<PHINode>(Op0))
2179 if (Instruction *NV = FoldOpIntoPhi(I))
2180 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002181 }
2182
Chris Lattnera9be4492005-04-07 16:15:25 +00002183 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2184 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002185 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002186 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002187 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002188 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002189 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002190 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2191 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2192 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002193 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002194 Op1I->getOperand(0));
2195 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002196 }
2197
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002198 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002199 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2200 // is not used by anyone else...
2201 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002202 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002203 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002204 // Swap the two operands of the subexpr...
2205 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2206 Op1I->setOperand(0, IIOp1);
2207 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002208
Chris Lattner3082c5a2003-02-18 19:28:33 +00002209 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002210 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002211 }
2212
2213 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2214 //
2215 if (Op1I->getOpcode() == Instruction::And &&
2216 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2217 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2218
Chris Lattner396dbfe2004-06-09 05:08:07 +00002219 Value *NewNot =
2220 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002221 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002222 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002223
Reid Spencer3c514952006-10-16 23:08:08 +00002224 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002225 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002226 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002227 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002228 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002229 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002230 ConstantExpr::getNeg(DivRHS));
2231
Chris Lattner57c8d992003-02-18 19:57:07 +00002232 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002233 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002234 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002235 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002236 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002237 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002238 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002239 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002240
Chris Lattner7a002fe2006-12-02 00:13:08 +00002241 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002242 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2243 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002244 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2245 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2246 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2247 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002248 } else if (Op0I->getOpcode() == Instruction::Sub) {
2249 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2250 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002251 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002252
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002253 ConstantInt *C1;
2254 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002255 if (X == Op1) // X*C - X --> X * (C-1)
2256 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002257
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002258 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2259 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002260 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002261 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002262 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002263}
2264
Reid Spencer266e42b2006-12-23 06:05:41 +00002265/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002266/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002267static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2268 switch (pred) {
2269 case ICmpInst::ICMP_SLT:
2270 // True if LHS s< RHS and RHS == 0
2271 return RHS->isNullValue();
2272 case ICmpInst::ICMP_SLE:
2273 // True if LHS s<= RHS and RHS == -1
2274 return RHS->isAllOnesValue();
2275 case ICmpInst::ICMP_UGE:
2276 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002277 return RHS->getValue() ==
2278 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002279 case ICmpInst::ICMP_UGT:
2280 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002281 return RHS->getValue() ==
2282 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002283 default:
2284 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002285 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002286}
2287
Chris Lattner113f4f42002-06-25 16:13:24 +00002288Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002289 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002290 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002291
Chris Lattner81a7a232004-10-16 18:11:37 +00002292 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2294
Chris Lattnere6794492002-08-12 21:17:25 +00002295 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002296 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2297 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002298
2299 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002300 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002301 if (SI->getOpcode() == Instruction::Shl)
2302 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002303 return BinaryOperator::createMul(SI->getOperand(0),
2304 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002305
Chris Lattnercce81be2003-09-11 22:24:54 +00002306 if (CI->isNullValue())
2307 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2308 if (CI->equalsInt(1)) // X * 1 == X
2309 return ReplaceInstUsesWith(I, Op0);
2310 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002311 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002312
Zhou Sheng4961cf12007-03-29 01:57:21 +00002313 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002314 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002315 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002316 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002317 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002318 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002319 if (Op1F->isNullValue())
2320 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002321
Chris Lattner3082c5a2003-02-18 19:28:33 +00002322 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2323 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2324 if (Op1F->getValue() == 1.0)
2325 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2326 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002327
2328 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2329 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2330 isa<ConstantInt>(Op0I->getOperand(1))) {
2331 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2332 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2333 Op1, "tmp");
2334 InsertNewInstBefore(Add, I);
2335 Value *C1C2 = ConstantExpr::getMul(Op1,
2336 cast<Constant>(Op0I->getOperand(1)));
2337 return BinaryOperator::createAdd(Add, C1C2);
2338
2339 }
Chris Lattner183b3362004-04-09 19:05:30 +00002340
2341 // Try to fold constant mul into select arguments.
2342 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002343 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002344 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002345
2346 if (isa<PHINode>(Op0))
2347 if (Instruction *NV = FoldOpIntoPhi(I))
2348 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002349 }
2350
Chris Lattner934a64cf2003-03-10 23:23:04 +00002351 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2352 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002353 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002354
Chris Lattner2635b522004-02-23 05:39:21 +00002355 // If one of the operands of the multiply is a cast from a boolean value, then
2356 // we know the bool is either zero or one, so this is a 'masking' multiply.
2357 // See if we can simplify things based on how the boolean was originally
2358 // formed.
2359 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002360 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002361 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002362 BoolCast = CI;
2363 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002364 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002365 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002366 BoolCast = CI;
2367 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002368 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002369 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2370 const Type *SCOpTy = SCIOp0->getType();
2371
Reid Spencer266e42b2006-12-23 06:05:41 +00002372 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002373 // multiply into a shift/and combination.
2374 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002375 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002376 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002377 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002378 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002379 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002380 InsertNewInstBefore(
2381 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002382 BoolCast->getOperand(0)->getName()+
2383 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002384
2385 // If the multiply type is not the same as the source type, sign extend
2386 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002387 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002388 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2389 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002390 Instruction::CastOps opcode =
2391 (SrcBits == DstBits ? Instruction::BitCast :
2392 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2393 V = InsertCastBefore(opcode, V, I.getType(), I);
2394 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002395
Chris Lattner2635b522004-02-23 05:39:21 +00002396 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002397 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002398 }
2399 }
2400 }
2401
Chris Lattner113f4f42002-06-25 16:13:24 +00002402 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002403}
2404
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002405/// This function implements the transforms on div instructions that work
2406/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2407/// used by the visitors to those instructions.
2408/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002409Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002410 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002411
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002412 // undef / X -> 0
2413 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002415
2416 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002417 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002418 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002419
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002420 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002421 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2422 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002423 // same basic block, then we replace the select with Y, and the condition
2424 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002425 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002426 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002427 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2428 if (ST->isNullValue()) {
2429 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2430 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002431 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002432 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2433 I.setOperand(1, SI->getOperand(2));
2434 else
2435 UpdateValueUsesWith(SI, SI->getOperand(2));
2436 return &I;
2437 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002438
Chris Lattnerd79dc792006-09-09 20:26:32 +00002439 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2440 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2441 if (ST->isNullValue()) {
2442 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2443 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002444 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002445 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2446 I.setOperand(1, SI->getOperand(1));
2447 else
2448 UpdateValueUsesWith(SI, SI->getOperand(1));
2449 return &I;
2450 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002451 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002452
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002453 return 0;
2454}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002455
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002456/// This function implements the transforms common to both integer division
2457/// instructions (udiv and sdiv). It is called by the visitors to those integer
2458/// division instructions.
2459/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002460Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2462
2463 if (Instruction *Common = commonDivTransforms(I))
2464 return Common;
2465
2466 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2467 // div X, 1 == X
2468 if (RHS->equalsInt(1))
2469 return ReplaceInstUsesWith(I, Op0);
2470
2471 // (X / C1) / C2 -> X / (C1*C2)
2472 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2473 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2474 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2475 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002476 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002477 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002478
Reid Spencer6d392062007-03-23 20:05:17 +00002479 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002480 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2482 return R;
2483 if (isa<PHINode>(Op0))
2484 if (Instruction *NV = FoldOpIntoPhi(I))
2485 return NV;
2486 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002487 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002488
Chris Lattner3082c5a2003-02-18 19:28:33 +00002489 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002490 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002491 if (LHS->equalsInt(0))
2492 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2493
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002494 return 0;
2495}
2496
2497Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2498 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2499
2500 // Handle the integer div common cases
2501 if (Instruction *Common = commonIDivTransforms(I))
2502 return Common;
2503
2504 // X udiv C^2 -> X >> C
2505 // Check to see if this is an unsigned division with an exact power of 2,
2506 // if so, convert to a right shift.
2507 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002508 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002509 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002510 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002511 }
2512
2513 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002514 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002515 if (RHSI->getOpcode() == Instruction::Shl &&
2516 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002517 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002518 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002519 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002520 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002521 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002522 Constant *C2V = ConstantInt::get(NTy, C2);
2523 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002524 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002525 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002526 }
2527 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002528 }
2529
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002530 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2531 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002532 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002533 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002534 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002535 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002536 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002537 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002538 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002539 // Construct the "on true" case of the select
2540 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2541 Instruction *TSI = BinaryOperator::createLShr(
2542 Op0, TC, SI->getName()+".t");
2543 TSI = InsertNewInstBefore(TSI, I);
2544
2545 // Construct the "on false" case of the select
2546 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2547 Instruction *FSI = BinaryOperator::createLShr(
2548 Op0, FC, SI->getName()+".f");
2549 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002550
Reid Spencer3939b1a2007-03-05 23:36:13 +00002551 // construct the select instruction and return it.
2552 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002553 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002554 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002555 return 0;
2556}
2557
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002558Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2559 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2560
2561 // Handle the integer div common cases
2562 if (Instruction *Common = commonIDivTransforms(I))
2563 return Common;
2564
2565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2566 // sdiv X, -1 == -X
2567 if (RHS->isAllOnesValue())
2568 return BinaryOperator::createNeg(Op0);
2569
2570 // -X/C -> X/-C
2571 if (Value *LHSNeg = dyn_castNegVal(Op0))
2572 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2573 }
2574
2575 // If the sign bits of both operands are zero (i.e. we can prove they are
2576 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002577 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002578 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002579 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2580 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2581 }
2582 }
2583
2584 return 0;
2585}
2586
2587Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2588 return commonDivTransforms(I);
2589}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002590
Chris Lattner85dda9a2006-03-02 06:50:58 +00002591/// GetFactor - If we can prove that the specified value is at least a multiple
2592/// of some factor, return that factor.
2593static Constant *GetFactor(Value *V) {
2594 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2595 return CI;
2596
2597 // Unless we can be tricky, we know this is a multiple of 1.
2598 Constant *Result = ConstantInt::get(V->getType(), 1);
2599
2600 Instruction *I = dyn_cast<Instruction>(V);
2601 if (!I) return Result;
2602
2603 if (I->getOpcode() == Instruction::Mul) {
2604 // Handle multiplies by a constant, etc.
2605 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2606 GetFactor(I->getOperand(1)));
2607 } else if (I->getOpcode() == Instruction::Shl) {
2608 // (X<<C) -> X * (1 << C)
2609 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2610 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2611 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2612 }
2613 } else if (I->getOpcode() == Instruction::And) {
2614 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2615 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002616 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002617 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2618 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002619 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002620 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002621 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002622 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002623 if (!CI->isIntegerCast())
2624 return Result;
2625 Value *Op = CI->getOperand(0);
2626 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002627 }
2628 return Result;
2629}
2630
Reid Spencer7eb55b32006-11-02 01:53:59 +00002631/// This function implements the transforms on rem instructions that work
2632/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2633/// is used by the visitors to those instructions.
2634/// @brief Transforms common to all three rem instructions
2635Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002636 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002637
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002638 // 0 % X == 0, we don't need to preserve faults!
2639 if (Constant *LHS = dyn_cast<Constant>(Op0))
2640 if (LHS->isNullValue())
2641 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2642
2643 if (isa<UndefValue>(Op0)) // undef % X -> 0
2644 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2645 if (isa<UndefValue>(Op1))
2646 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002647
2648 // Handle cases involving: rem X, (select Cond, Y, Z)
2649 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2650 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2651 // the same basic block, then we replace the select with Y, and the
2652 // condition of the select with false (if the cond value is in the same
2653 // BB). If the select has uses other than the div, this allows them to be
2654 // simplified also.
2655 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2656 if (ST->isNullValue()) {
2657 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2658 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002659 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002660 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2661 I.setOperand(1, SI->getOperand(2));
2662 else
2663 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002664 return &I;
2665 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002666 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2667 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2668 if (ST->isNullValue()) {
2669 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2670 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002671 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002672 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2673 I.setOperand(1, SI->getOperand(1));
2674 else
2675 UpdateValueUsesWith(SI, SI->getOperand(1));
2676 return &I;
2677 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002678 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002679
Reid Spencer7eb55b32006-11-02 01:53:59 +00002680 return 0;
2681}
2682
2683/// This function implements the transforms common to both integer remainder
2684/// instructions (urem and srem). It is called by the visitors to those integer
2685/// remainder instructions.
2686/// @brief Common integer remainder transforms
2687Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2689
2690 if (Instruction *common = commonRemTransforms(I))
2691 return common;
2692
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002693 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002694 // X % 0 == undef, we don't need to preserve faults!
2695 if (RHS->equalsInt(0))
2696 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2697
Chris Lattner3082c5a2003-02-18 19:28:33 +00002698 if (RHS->equalsInt(1)) // X % 1 == 0
2699 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2700
Chris Lattnerb70f1412006-02-28 05:49:21 +00002701 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2702 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2703 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2704 return R;
2705 } else if (isa<PHINode>(Op0I)) {
2706 if (Instruction *NV = FoldOpIntoPhi(I))
2707 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002708 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002709 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2710 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002712 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002713 }
2714
Reid Spencer7eb55b32006-11-02 01:53:59 +00002715 return 0;
2716}
2717
2718Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2720
2721 if (Instruction *common = commonIRemTransforms(I))
2722 return common;
2723
2724 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2725 // X urem C^2 -> X and C
2726 // Check to see if this is an unsigned remainder with an exact power of 2,
2727 // if so, convert to a bitwise and.
2728 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002729 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002730 return BinaryOperator::createAnd(Op0, SubOne(C));
2731 }
2732
Chris Lattner2e90b732006-02-05 07:54:04 +00002733 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002734 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2735 if (RHSI->getOpcode() == Instruction::Shl &&
2736 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002737 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002738 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2739 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2740 "tmp"), I);
2741 return BinaryOperator::createAnd(Op0, Add);
2742 }
2743 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002744 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002745
Reid Spencer7eb55b32006-11-02 01:53:59 +00002746 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2747 // where C1&C2 are powers of two.
2748 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2749 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2750 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2751 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002752 if ((STO->getValue().isPowerOf2()) &&
2753 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002754 Value *TrueAnd = InsertNewInstBefore(
2755 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2756 Value *FalseAnd = InsertNewInstBefore(
2757 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2758 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2759 }
2760 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002761 }
2762
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002763 return 0;
2764}
2765
Reid Spencer7eb55b32006-11-02 01:53:59 +00002766Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2768
2769 if (Instruction *common = commonIRemTransforms(I))
2770 return common;
2771
2772 if (Value *RHSNeg = dyn_castNegVal(Op1))
2773 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002774 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002775 // X % -Y -> X % Y
2776 AddUsesToWorkList(I);
2777 I.setOperand(1, RHSNeg);
2778 return &I;
2779 }
2780
2781 // If the top bits of both operands are zero (i.e. we can prove they are
2782 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002783 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002784 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2785 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2786 return BinaryOperator::createURem(Op0, Op1, I.getName());
2787 }
2788
2789 return 0;
2790}
2791
2792Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002793 return commonRemTransforms(I);
2794}
2795
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002796// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002797static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002798 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002799 if (isSigned) {
2800 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002801 APInt Val(APInt::getSignedMaxValue(TypeBits));
2802 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002803 }
Reid Spenceref599b02007-03-19 21:10:28 +00002804 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002805}
2806
2807// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002808static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2809 if (isSigned) {
2810 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002811 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2812 APInt Val(APInt::getSignedMinValue(TypeBits));
2813 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002814 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002815 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002816}
2817
Chris Lattner35167c32004-06-09 07:59:58 +00002818// isOneBitSet - Return true if there is exactly one bit set in the specified
2819// constant.
2820static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002821 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002822}
2823
Chris Lattner8fc5af42004-09-23 21:46:38 +00002824// isHighOnes - Return true if the constant is of the form 1+0+.
2825// This is the same as lowones(~X).
2826static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002827 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002828}
2829
Reid Spencer266e42b2006-12-23 06:05:41 +00002830/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002831/// are carefully arranged to allow folding of expressions such as:
2832///
2833/// (A < B) | (A > B) --> (A != B)
2834///
Reid Spencer266e42b2006-12-23 06:05:41 +00002835/// Note that this is only valid if the first and second predicates have the
2836/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002837///
Reid Spencer266e42b2006-12-23 06:05:41 +00002838/// Three bits are used to represent the condition, as follows:
2839/// 0 A > B
2840/// 1 A == B
2841/// 2 A < B
2842///
2843/// <=> Value Definition
2844/// 000 0 Always false
2845/// 001 1 A > B
2846/// 010 2 A == B
2847/// 011 3 A >= B
2848/// 100 4 A < B
2849/// 101 5 A != B
2850/// 110 6 A <= B
2851/// 111 7 Always true
2852///
2853static unsigned getICmpCode(const ICmpInst *ICI) {
2854 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002855 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002856 case ICmpInst::ICMP_UGT: return 1; // 001
2857 case ICmpInst::ICMP_SGT: return 1; // 001
2858 case ICmpInst::ICMP_EQ: return 2; // 010
2859 case ICmpInst::ICMP_UGE: return 3; // 011
2860 case ICmpInst::ICMP_SGE: return 3; // 011
2861 case ICmpInst::ICMP_ULT: return 4; // 100
2862 case ICmpInst::ICMP_SLT: return 4; // 100
2863 case ICmpInst::ICMP_NE: return 5; // 101
2864 case ICmpInst::ICMP_ULE: return 6; // 110
2865 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002866 // True -> 7
2867 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002868 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002869 return 0;
2870 }
2871}
2872
Reid Spencer266e42b2006-12-23 06:05:41 +00002873/// getICmpValue - This is the complement of getICmpCode, which turns an
2874/// opcode and two operands into either a constant true or false, or a brand
2875/// new /// ICmp instruction. The sign is passed in to determine which kind
2876/// of predicate to use in new icmp instructions.
2877static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2878 switch (code) {
2879 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002880 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002881 case 1:
2882 if (sign)
2883 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2884 else
2885 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2886 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2887 case 3:
2888 if (sign)
2889 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2890 else
2891 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2892 case 4:
2893 if (sign)
2894 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2895 else
2896 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2897 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2898 case 6:
2899 if (sign)
2900 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2901 else
2902 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002903 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002904 }
2905}
2906
Reid Spencer266e42b2006-12-23 06:05:41 +00002907static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2908 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2909 (ICmpInst::isSignedPredicate(p1) &&
2910 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2911 (ICmpInst::isSignedPredicate(p2) &&
2912 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2913}
2914
2915namespace {
2916// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2917struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002918 InstCombiner &IC;
2919 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002920 ICmpInst::Predicate pred;
2921 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2922 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2923 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002924 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002925 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2926 if (PredicatesFoldable(pred, ICI->getPredicate()))
2927 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2928 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002929 return false;
2930 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002931 Instruction *apply(Instruction &Log) const {
2932 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2933 if (ICI->getOperand(0) != LHS) {
2934 assert(ICI->getOperand(1) == LHS);
2935 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002936 }
2937
Chris Lattnerd1bce952007-03-13 14:27:42 +00002938 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002939 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002940 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002941 unsigned Code;
2942 switch (Log.getOpcode()) {
2943 case Instruction::And: Code = LHSCode & RHSCode; break;
2944 case Instruction::Or: Code = LHSCode | RHSCode; break;
2945 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002946 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002947 }
2948
Chris Lattnerd1bce952007-03-13 14:27:42 +00002949 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2950 ICmpInst::isSignedPredicate(ICI->getPredicate());
2951
2952 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002953 if (Instruction *I = dyn_cast<Instruction>(RV))
2954 return I;
2955 // Otherwise, it's a constant boolean value...
2956 return IC.ReplaceInstUsesWith(Log, RV);
2957 }
2958};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002959} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002960
Chris Lattnerba1cb382003-09-19 17:17:26 +00002961// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2962// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002963// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002964Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002965 ConstantInt *OpRHS,
2966 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002967 BinaryOperator &TheAnd) {
2968 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002969 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002970 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002971 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002972
Chris Lattnerba1cb382003-09-19 17:17:26 +00002973 switch (Op->getOpcode()) {
2974 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002975 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002976 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002977 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002978 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002979 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002980 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002981 }
2982 break;
2983 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002984 if (Together == AndRHS) // (X | C) & C --> C
2985 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002986
Chris Lattner86102b82005-01-01 16:22:27 +00002987 if (Op->hasOneUse() && Together != OpRHS) {
2988 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002989 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002990 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002991 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002992 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002993 }
2994 break;
2995 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002996 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002997 // Adding a one to a single bit bit-field should be turned into an XOR
2998 // of the bit. First thing to check is to see if this AND is with a
2999 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003000 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003001
3002 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003003 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003004 // Ok, at this point, we know that we are masking the result of the
3005 // ADD down to exactly one bit. If the constant we are adding has
3006 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003007 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003008
Chris Lattnerba1cb382003-09-19 17:17:26 +00003009 // Check to see if any bits below the one bit set in AndRHSV are set.
3010 if ((AddRHS & (AndRHSV-1)) == 0) {
3011 // If not, the only thing that can effect the output of the AND is
3012 // the bit specified by AndRHSV. If that bit is set, the effect of
3013 // the XOR is to toggle the bit. If it is clear, then the ADD has
3014 // no effect.
3015 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3016 TheAnd.setOperand(0, X);
3017 return &TheAnd;
3018 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003019 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003020 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003021 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003022 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003023 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003024 }
3025 }
3026 }
3027 }
3028 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003029
3030 case Instruction::Shl: {
3031 // We know that the AND will not produce any of the bits shifted in, so if
3032 // the anded constant includes them, clear them now!
3033 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003034 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003035 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003036 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3037 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003038
Zhou Shengb3a80b12007-03-29 08:15:12 +00003039 if (CI->getValue() == ShlMask) {
3040 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003041 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3042 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003043 TheAnd.setOperand(1, CI);
3044 return &TheAnd;
3045 }
3046 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003047 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003048 case Instruction::LShr:
3049 {
Chris Lattner2da29172003-09-19 19:05:02 +00003050 // We know that the AND will not produce any of the bits shifted in, so if
3051 // the anded constant includes them, clear them now! This only applies to
3052 // unsigned shifts, because a signed shr may bring in set bits!
3053 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003054 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003055 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003056 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3057 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003058
Zhou Shengb3a80b12007-03-29 08:15:12 +00003059 if (CI->getValue() == ShrMask) {
3060 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003061 return ReplaceInstUsesWith(TheAnd, Op);
3062 } else if (CI != AndRHS) {
3063 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3064 return &TheAnd;
3065 }
3066 break;
3067 }
3068 case Instruction::AShr:
3069 // Signed shr.
3070 // See if this is shifting in some sign extension, then masking it out
3071 // with an and.
3072 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003073 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003074 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003075 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3076 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003077 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003078 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003079 // Make the argument unsigned.
3080 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003081 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003082 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003083 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003084 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003085 }
Chris Lattner2da29172003-09-19 19:05:02 +00003086 }
3087 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003088 }
3089 return 0;
3090}
3091
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003092
Chris Lattner6862fbd2004-09-29 17:40:11 +00003093/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3094/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003095/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3096/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003097/// insert new instructions.
3098Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003099 bool isSigned, bool Inside,
3100 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003101 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003102 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003103 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003104
Chris Lattner6862fbd2004-09-29 17:40:11 +00003105 if (Inside) {
3106 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003107 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003108
Reid Spencer266e42b2006-12-23 06:05:41 +00003109 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003110 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003111 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003112 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3113 return new ICmpInst(pred, V, Hi);
3114 }
3115
3116 // Emit V-Lo <u Hi-Lo
3117 Constant *NegLo = ConstantExpr::getNeg(Lo);
3118 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003119 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003120 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3121 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003122 }
3123
3124 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003125 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003126
Reid Spencerf4071162007-03-21 23:19:50 +00003127 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003128 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003129 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003130 ICmpInst::Predicate pred = (isSigned ?
3131 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3132 return new ICmpInst(pred, V, Hi);
3133 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003134
Reid Spencerf4071162007-03-21 23:19:50 +00003135 // Emit V-Lo >u Hi-1-Lo
3136 // Note that Hi has already had one subtracted from it, above.
3137 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003138 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003139 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003140 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3141 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003142}
3143
Chris Lattnerb4b25302005-09-18 07:22:02 +00003144// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3145// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3146// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3147// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003148static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003149 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003150 uint32_t BitWidth = Val->getType()->getBitWidth();
3151 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003152
3153 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003154 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003155 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003156 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003157 return true;
3158}
3159
Chris Lattnerb4b25302005-09-18 07:22:02 +00003160/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3161/// where isSub determines whether the operator is a sub. If we can fold one of
3162/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003163///
3164/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3165/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3166/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3167///
3168/// return (A +/- B).
3169///
3170Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003171 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003172 Instruction &I) {
3173 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3174 if (!LHSI || LHSI->getNumOperands() != 2 ||
3175 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3176
3177 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3178
3179 switch (LHSI->getOpcode()) {
3180 default: return 0;
3181 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003182 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003183 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003184 if ((Mask->getValue().countLeadingZeros() +
3185 Mask->getValue().countPopulation()) ==
3186 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003187 break;
3188
3189 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3190 // part, we don't need any explicit masks to take them out of A. If that
3191 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003192 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003193 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003194 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003195 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003196 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003197 break;
3198 }
3199 }
Chris Lattneraf517572005-09-18 04:24:45 +00003200 return 0;
3201 case Instruction::Or:
3202 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003203 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003204 if ((Mask->getValue().countLeadingZeros() +
3205 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003206 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003207 break;
3208 return 0;
3209 }
3210
3211 Instruction *New;
3212 if (isSub)
3213 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3214 else
3215 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3216 return InsertNewInstBefore(New, I);
3217}
3218
Chris Lattner113f4f42002-06-25 16:13:24 +00003219Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003220 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003222
Chris Lattner81a7a232004-10-16 18:11:37 +00003223 if (isa<UndefValue>(Op1)) // X & undef -> 0
3224 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3225
Chris Lattner86102b82005-01-01 16:22:27 +00003226 // and X, X = X
3227 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003228 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003229
Chris Lattner5b2edb12006-02-12 08:02:11 +00003230 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003231 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003232 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003233 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3234 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3235 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003236 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003237 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003238 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003239 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003240 if (CP->isAllOnesValue())
3241 return ReplaceInstUsesWith(I, I.getOperand(0));
3242 }
3243 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003244
Zhou Sheng75b871f2007-01-11 12:24:14 +00003245 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003246 const APInt& AndRHSMask = AndRHS->getValue();
3247 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003248
Chris Lattnerba1cb382003-09-19 17:17:26 +00003249 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003250 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003251 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003252 Value *Op0LHS = Op0I->getOperand(0);
3253 Value *Op0RHS = Op0I->getOperand(1);
3254 switch (Op0I->getOpcode()) {
3255 case Instruction::Xor:
3256 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003257 // If the mask is only needed on one incoming arm, push it up.
3258 if (Op0I->hasOneUse()) {
3259 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3260 // Not masking anything out for the LHS, move to RHS.
3261 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3262 Op0RHS->getName()+".masked");
3263 InsertNewInstBefore(NewRHS, I);
3264 return BinaryOperator::create(
3265 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003266 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003267 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003268 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3269 // Not masking anything out for the RHS, move to LHS.
3270 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3271 Op0LHS->getName()+".masked");
3272 InsertNewInstBefore(NewLHS, I);
3273 return BinaryOperator::create(
3274 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3275 }
3276 }
3277
Chris Lattner86102b82005-01-01 16:22:27 +00003278 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003279 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003280 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3281 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3282 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3283 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3284 return BinaryOperator::createAnd(V, AndRHS);
3285 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3286 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003287 break;
3288
3289 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003290 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3291 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3292 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3293 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3294 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003295 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003296 }
3297
Chris Lattner16464b32003-07-23 19:25:52 +00003298 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003299 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003300 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003301 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003302 // If this is an integer truncation or change from signed-to-unsigned, and
3303 // if the source is an and/or with immediate, transform it. This
3304 // frequently occurs for bitfield accesses.
3305 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003306 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003307 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003308 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003309 if (CastOp->getOpcode() == Instruction::And) {
3310 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003311 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3312 // This will fold the two constants together, which may allow
3313 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003314 Instruction *NewCast = CastInst::createTruncOrBitCast(
3315 CastOp->getOperand(0), I.getType(),
3316 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003317 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003318 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003319 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003320 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003321 return BinaryOperator::createAnd(NewCast, C3);
3322 } else if (CastOp->getOpcode() == Instruction::Or) {
3323 // Change: and (cast (or X, C1) to T), C2
3324 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003325 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003326 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3327 return ReplaceInstUsesWith(I, AndRHS);
3328 }
3329 }
Chris Lattner33217db2003-07-23 19:36:21 +00003330 }
Chris Lattner183b3362004-04-09 19:05:30 +00003331
3332 // Try to fold constant and into select arguments.
3333 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003334 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003335 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003336 if (isa<PHINode>(Op0))
3337 if (Instruction *NV = FoldOpIntoPhi(I))
3338 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003339 }
3340
Chris Lattnerbb74e222003-03-10 23:06:50 +00003341 Value *Op0NotVal = dyn_castNotVal(Op0);
3342 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003343
Chris Lattner023a4832004-06-18 06:07:51 +00003344 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3345 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3346
Misha Brukman9c003d82004-07-30 12:50:08 +00003347 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003348 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003349 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3350 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003351 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003352 return BinaryOperator::createNot(Or);
3353 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003354
3355 {
3356 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003357 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3358 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3359 return ReplaceInstUsesWith(I, Op1);
3360 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3361 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3362 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003363
3364 if (Op0->hasOneUse() &&
3365 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3366 if (A == Op1) { // (A^B)&A -> A&(A^B)
3367 I.swapOperands(); // Simplify below
3368 std::swap(Op0, Op1);
3369 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3370 cast<BinaryOperator>(Op0)->swapOperands();
3371 I.swapOperands(); // Simplify below
3372 std::swap(Op0, Op1);
3373 }
3374 }
3375 if (Op1->hasOneUse() &&
3376 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3377 if (B == Op0) { // B&(A^B) -> B&(B^A)
3378 cast<BinaryOperator>(Op1)->swapOperands();
3379 std::swap(A, B);
3380 }
3381 if (A == Op0) { // A&(A^B) -> A & ~B
3382 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3383 InsertNewInstBefore(NotB, I);
3384 return BinaryOperator::createAnd(A, NotB);
3385 }
3386 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003387 }
3388
Reid Spencer266e42b2006-12-23 06:05:41 +00003389 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3390 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3391 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003392 return R;
3393
Chris Lattner623826c2004-09-28 21:48:02 +00003394 Value *LHSVal, *RHSVal;
3395 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003396 ICmpInst::Predicate LHSCC, RHSCC;
3397 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3398 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3399 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3400 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3401 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3402 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3403 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3404 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003405 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003406 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3407 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3408 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3409 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003410 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003411 std::swap(LHS, RHS);
3412 std::swap(LHSCst, RHSCst);
3413 std::swap(LHSCC, RHSCC);
3414 }
3415
Reid Spencer266e42b2006-12-23 06:05:41 +00003416 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003417 // comparing a value against two constants and and'ing the result
3418 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003419 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3420 // (from the FoldICmpLogical check above), that the two constants
3421 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003422 assert(LHSCst != RHSCst && "Compares not folded above?");
3423
3424 switch (LHSCC) {
3425 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003426 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003427 switch (RHSCC) {
3428 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003429 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3430 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3431 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003432 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003433 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3434 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3435 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003436 return ReplaceInstUsesWith(I, LHS);
3437 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003438 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003439 switch (RHSCC) {
3440 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003441 case ICmpInst::ICMP_ULT:
3442 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3443 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3444 break; // (X != 13 & X u< 15) -> no change
3445 case ICmpInst::ICMP_SLT:
3446 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3447 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3448 break; // (X != 13 & X s< 15) -> no change
3449 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3450 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3451 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003452 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003453 case ICmpInst::ICMP_NE:
3454 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003455 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3456 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3457 LHSVal->getName()+".off");
3458 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003459 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3460 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003461 }
3462 break; // (X != 13 & X != 15) -> no change
3463 }
3464 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003465 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003466 switch (RHSCC) {
3467 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003468 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3469 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003470 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003471 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3472 break;
3473 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3474 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003475 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003476 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3477 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003478 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003479 break;
3480 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003481 switch (RHSCC) {
3482 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003483 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3484 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003485 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003486 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3487 break;
3488 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3489 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003490 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003491 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3492 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003493 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003494 break;
3495 case ICmpInst::ICMP_UGT:
3496 switch (RHSCC) {
3497 default: assert(0 && "Unknown integer condition code!");
3498 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3499 return ReplaceInstUsesWith(I, LHS);
3500 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3501 return ReplaceInstUsesWith(I, RHS);
3502 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3503 break;
3504 case ICmpInst::ICMP_NE:
3505 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3506 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3507 break; // (X u> 13 & X != 15) -> no change
3508 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3509 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3510 true, I);
3511 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3512 break;
3513 }
3514 break;
3515 case ICmpInst::ICMP_SGT:
3516 switch (RHSCC) {
3517 default: assert(0 && "Unknown integer condition code!");
3518 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3519 return ReplaceInstUsesWith(I, LHS);
3520 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3521 return ReplaceInstUsesWith(I, RHS);
3522 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3523 break;
3524 case ICmpInst::ICMP_NE:
3525 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3526 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3527 break; // (X s> 13 & X != 15) -> no change
3528 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3529 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3530 true, I);
3531 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3532 break;
3533 }
3534 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003535 }
3536 }
3537 }
3538
Chris Lattner3af10532006-05-05 06:39:07 +00003539 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003540 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3541 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3542 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3543 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003544 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003545 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003546 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3547 I.getType(), TD) &&
3548 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3549 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003550 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3551 Op1C->getOperand(0),
3552 I.getName());
3553 InsertNewInstBefore(NewOp, I);
3554 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3555 }
Chris Lattner3af10532006-05-05 06:39:07 +00003556 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003557
3558 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003559 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3560 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3561 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003562 SI0->getOperand(1) == SI1->getOperand(1) &&
3563 (SI0->hasOneUse() || SI1->hasOneUse())) {
3564 Instruction *NewOp =
3565 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3566 SI1->getOperand(0),
3567 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003568 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3569 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003570 }
Chris Lattner3af10532006-05-05 06:39:07 +00003571 }
3572
Chris Lattner113f4f42002-06-25 16:13:24 +00003573 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003574}
3575
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003576/// CollectBSwapParts - Look to see if the specified value defines a single byte
3577/// in the result. If it does, and if the specified byte hasn't been filled in
3578/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003579static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003580 Instruction *I = dyn_cast<Instruction>(V);
3581 if (I == 0) return true;
3582
3583 // If this is an or instruction, it is an inner node of the bswap.
3584 if (I->getOpcode() == Instruction::Or)
3585 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3586 CollectBSwapParts(I->getOperand(1), ByteValues);
3587
Zhou Shengb25806f2007-03-30 09:29:48 +00003588 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003589 // If this is a shift by a constant int, and it is "24", then its operand
3590 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003591 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003592 // Not shifting the entire input by N-1 bytes?
Zhou Shengb25806f2007-03-30 09:29:48 +00003593 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003594 8*(ByteValues.size()-1))
3595 return true;
3596
3597 unsigned DestNo;
3598 if (I->getOpcode() == Instruction::Shl) {
3599 // X << 24 defines the top byte with the lowest of the input bytes.
3600 DestNo = ByteValues.size()-1;
3601 } else {
3602 // X >>u 24 defines the low byte with the highest of the input bytes.
3603 DestNo = 0;
3604 }
3605
3606 // If the destination byte value is already defined, the values are or'd
3607 // together, which isn't a bswap (unless it's an or of the same bits).
3608 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3609 return true;
3610 ByteValues[DestNo] = I->getOperand(0);
3611 return false;
3612 }
3613
3614 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3615 // don't have this.
3616 Value *Shift = 0, *ShiftLHS = 0;
3617 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3618 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3619 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3620 return true;
3621 Instruction *SI = cast<Instruction>(Shift);
3622
3623 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Shengb25806f2007-03-30 09:29:48 +00003624 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3625 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003626 return true;
3627
3628 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3629 unsigned DestByte;
Zhou Shengb25806f2007-03-30 09:29:48 +00003630 if (AndAmt->getValue().getActiveBits() > 64)
3631 return true;
3632 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003633 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Shengb25806f2007-03-30 09:29:48 +00003634 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003635 break;
3636 // Unknown mask for bswap.
3637 if (DestByte == ByteValues.size()) return true;
3638
Reid Spencere0fc4df2006-10-20 07:07:24 +00003639 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003640 unsigned SrcByte;
3641 if (SI->getOpcode() == Instruction::Shl)
3642 SrcByte = DestByte - ShiftBytes;
3643 else
3644 SrcByte = DestByte + ShiftBytes;
3645
3646 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3647 if (SrcByte != ByteValues.size()-DestByte-1)
3648 return true;
3649
3650 // If the destination byte value is already defined, the values are or'd
3651 // together, which isn't a bswap (unless it's an or of the same bits).
3652 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3653 return true;
3654 ByteValues[DestByte] = SI->getOperand(0);
3655 return false;
3656}
3657
3658/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3659/// If so, insert the new bswap intrinsic and return it.
3660Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003661 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3662 if (!ITy || ITy->getBitWidth() % 16)
3663 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003664
3665 /// ByteValues - For each byte of the result, we keep track of which value
3666 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003667 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003668 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003669
3670 // Try to find all the pieces corresponding to the bswap.
3671 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3672 CollectBSwapParts(I.getOperand(1), ByteValues))
3673 return 0;
3674
3675 // Check to see if all of the bytes come from the same value.
3676 Value *V = ByteValues[0];
3677 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3678
3679 // Check to make sure that all of the bytes come from the same value.
3680 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3681 if (ByteValues[i] != V)
3682 return 0;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003683 const Type *Tys[] = { ITy, ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003684 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003685 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003686 return new CallInst(F, V);
3687}
3688
3689
Chris Lattner113f4f42002-06-25 16:13:24 +00003690Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003691 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003692 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003693
Chris Lattner3a8248f2007-03-24 23:56:43 +00003694 if (isa<UndefValue>(Op1)) // X | undef -> -1
3695 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003696
Chris Lattner5b2edb12006-02-12 08:02:11 +00003697 // or X, X = X
3698 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003699 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003700
Chris Lattner5b2edb12006-02-12 08:02:11 +00003701 // See if we can simplify any instructions used by the instruction whose sole
3702 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003703 if (!isa<VectorType>(I.getType())) {
3704 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3705 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3706 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3707 KnownZero, KnownOne))
3708 return &I;
3709 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003710
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003711 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003713 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003714 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3715 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003716 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003717 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003718 Or->takeName(Op0);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003719 return BinaryOperator::createAnd(Or,
3720 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003721 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003722
Chris Lattnerd4252a72004-07-30 07:50:03 +00003723 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3724 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003725 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003726 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003727 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003728 return BinaryOperator::createXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003729 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003730 }
Chris Lattner183b3362004-04-09 19:05:30 +00003731
3732 // Try to fold constant and into select arguments.
3733 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003734 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003735 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003736 if (isa<PHINode>(Op0))
3737 if (Instruction *NV = FoldOpIntoPhi(I))
3738 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003739 }
3740
Chris Lattner330628a2006-01-06 17:59:59 +00003741 Value *A = 0, *B = 0;
3742 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003743
3744 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3745 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3746 return ReplaceInstUsesWith(I, Op1);
3747 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3748 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3749 return ReplaceInstUsesWith(I, Op0);
3750
Chris Lattnerb7845d62006-07-10 20:25:24 +00003751 // (A | B) | C and A | (B | C) -> bswap if possible.
3752 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003753 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003754 match(Op1, m_Or(m_Value(), m_Value())) ||
3755 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3756 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003757 if (Instruction *BSwap = MatchBSwap(I))
3758 return BSwap;
3759 }
3760
Chris Lattnerb62f5082005-05-09 04:58:36 +00003761 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3762 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003763 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003764 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3765 InsertNewInstBefore(NOr, I);
3766 NOr->takeName(Op0);
3767 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003768 }
3769
3770 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3771 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003772 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003773 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3774 InsertNewInstBefore(NOr, I);
3775 NOr->takeName(Op0);
3776 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003777 }
3778
Chris Lattner1150df92007-04-08 07:47:01 +00003779 // (A & C)|(B & D)
3780 Value *C, *D;
3781 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3782 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner7621a032007-04-08 07:55:22 +00003783 Value *V1 = 0, *V2 = 0, *V3 = 0;
3784 C1 = dyn_cast<ConstantInt>(C);
3785 C2 = dyn_cast<ConstantInt>(D);
3786 if (C1 && C2) { // (A & C1)|(B & C2)
3787 // If we have: ((V + N) & C1) | (V & C2)
3788 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3789 // replace with V+N.
3790 if (C1->getValue() == ~C2->getValue()) {
3791 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3792 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3793 // Add commutes, try both ways.
3794 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3795 return ReplaceInstUsesWith(I, A);
3796 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3797 return ReplaceInstUsesWith(I, A);
3798 }
3799 // Or commutes, try both ways.
3800 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3801 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3802 // Add commutes, try both ways.
3803 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3804 return ReplaceInstUsesWith(I, B);
3805 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3806 return ReplaceInstUsesWith(I, B);
3807 }
3808 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00003809 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00003810 }
3811
Chris Lattner1150df92007-04-08 07:47:01 +00003812 // Check to see if we have any common things being and'ed. If so, find the
3813 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00003814 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3815 if (A == B) // (A & C)|(A & D) == A & (C|D)
3816 V1 = A, V2 = C, V3 = D;
3817 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3818 V1 = A, V2 = B, V3 = C;
3819 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3820 V1 = C, V2 = A, V3 = D;
3821 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3822 V1 = C, V2 = A, V3 = B;
3823
3824 if (V1) {
3825 Value *Or =
3826 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3827 return BinaryOperator::createAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00003828 }
Chris Lattner1150df92007-04-08 07:47:01 +00003829
3830 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
Chris Lattnerc8d37882007-04-08 08:01:49 +00003831 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner1150df92007-04-08 07:47:01 +00003832 // Try all combination of terms to find V3 and ~V3.
3833 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3834 if (V3 == B)
3835 V1 = D, V2 = C;
3836 else if (V3 == D)
3837 V1 = B, V2 = C;
3838 }
3839 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3840 if (V3 == A)
3841 V1 = C, V2 = D;
3842 else if (V3 == C)
3843 V1 = A, V2 = D;
3844 }
3845 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3846 if (V3 == B)
3847 V1 = D, V2 = A;
3848 else if (V3 == D)
3849 V1 = B, V2 = A;
3850 }
3851 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3852 if (V3 == A)
3853 V1 = C, V2 = B;
3854 else if (V3 == C)
3855 V1 = A, V2 = B;
3856 }
3857 if (V1) {
3858 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3859 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3860 return BinaryOperator::createXor(A, V2);
3861 }
3862 }
3863 }
Chris Lattner15212982005-09-18 03:42:07 +00003864 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003865
3866 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003867 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3868 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3869 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003870 SI0->getOperand(1) == SI1->getOperand(1) &&
3871 (SI0->hasOneUse() || SI1->hasOneUse())) {
3872 Instruction *NewOp =
3873 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3874 SI1->getOperand(0),
3875 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003876 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3877 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003878 }
3879 }
Chris Lattner812aab72003-08-12 19:11:07 +00003880
Chris Lattnerd4252a72004-07-30 07:50:03 +00003881 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3882 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003883 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003884 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003885 } else {
3886 A = 0;
3887 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003888 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003889 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3890 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003891 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003892 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003893
Misha Brukman9c003d82004-07-30 12:50:08 +00003894 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003895 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3896 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3897 I.getName()+".demorgan"), I);
3898 return BinaryOperator::createNot(And);
3899 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003900 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003901
Reid Spencer266e42b2006-12-23 06:05:41 +00003902 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3903 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3904 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003905 return R;
3906
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003907 Value *LHSVal, *RHSVal;
3908 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003909 ICmpInst::Predicate LHSCC, RHSCC;
3910 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3911 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3912 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3913 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3914 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3915 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3916 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3917 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003918 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003919 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3920 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3921 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3922 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003923 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003924 std::swap(LHS, RHS);
3925 std::swap(LHSCst, RHSCst);
3926 std::swap(LHSCC, RHSCC);
3927 }
3928
Reid Spencer266e42b2006-12-23 06:05:41 +00003929 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003930 // comparing a value against two constants and or'ing the result
3931 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003932 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3933 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003934 // equal.
3935 assert(LHSCst != RHSCst && "Compares not folded above?");
3936
3937 switch (LHSCC) {
3938 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003939 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003940 switch (RHSCC) {
3941 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003942 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003943 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3944 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3945 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3946 LHSVal->getName()+".off");
3947 InsertNewInstBefore(Add, I);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003948 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003949 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003950 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003951 break; // (X == 13 | X == 15) -> no change
3952 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3953 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003954 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003955 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3956 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3957 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003958 return ReplaceInstUsesWith(I, RHS);
3959 }
3960 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003961 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003962 switch (RHSCC) {
3963 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003964 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3965 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3966 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003967 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003968 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3969 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3970 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003971 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003972 }
3973 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003974 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003975 switch (RHSCC) {
3976 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003977 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003978 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003979 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3980 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3981 false, I);
3982 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3983 break;
3984 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3985 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003986 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003987 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3988 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003989 }
3990 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003991 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003992 switch (RHSCC) {
3993 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003994 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3995 break;
3996 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3997 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3998 false, I);
3999 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4000 break;
4001 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4002 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4003 return ReplaceInstUsesWith(I, RHS);
4004 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4005 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004006 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004007 break;
4008 case ICmpInst::ICMP_UGT:
4009 switch (RHSCC) {
4010 default: assert(0 && "Unknown integer condition code!");
4011 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4012 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4013 return ReplaceInstUsesWith(I, LHS);
4014 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4015 break;
4016 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4017 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004018 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004019 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4020 break;
4021 }
4022 break;
4023 case ICmpInst::ICMP_SGT:
4024 switch (RHSCC) {
4025 default: assert(0 && "Unknown integer condition code!");
4026 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4027 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4028 return ReplaceInstUsesWith(I, LHS);
4029 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4030 break;
4031 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4032 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004033 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4035 break;
4036 }
4037 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004038 }
4039 }
4040 }
Chris Lattner3af10532006-05-05 06:39:07 +00004041
4042 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004043 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004044 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004045 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4046 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004047 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004048 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004049 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4050 I.getType(), TD) &&
4051 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4052 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004053 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4054 Op1C->getOperand(0),
4055 I.getName());
4056 InsertNewInstBefore(NewOp, I);
4057 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4058 }
Chris Lattner3af10532006-05-05 06:39:07 +00004059 }
Chris Lattner3af10532006-05-05 06:39:07 +00004060
Chris Lattner15212982005-09-18 03:42:07 +00004061
Chris Lattner113f4f42002-06-25 16:13:24 +00004062 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004063}
4064
Chris Lattnerc2076352004-02-16 01:20:27 +00004065// XorSelf - Implements: X ^ X --> 0
4066struct XorSelf {
4067 Value *RHS;
4068 XorSelf(Value *rhs) : RHS(rhs) {}
4069 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4070 Instruction *apply(BinaryOperator &Xor) const {
4071 return &Xor;
4072 }
4073};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004074
4075
Chris Lattner113f4f42002-06-25 16:13:24 +00004076Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004077 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004078 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004079
Chris Lattner81a7a232004-10-16 18:11:37 +00004080 if (isa<UndefValue>(Op1))
4081 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4082
Chris Lattnerc2076352004-02-16 01:20:27 +00004083 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4084 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4085 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004086 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004087 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004088
4089 // See if we can simplify any instructions used by the instruction whose sole
4090 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004091 if (!isa<VectorType>(I.getType())) {
4092 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4093 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4094 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4095 KnownZero, KnownOne))
4096 return &I;
4097 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004098
Zhou Sheng75b871f2007-01-11 12:24:14 +00004099 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004100 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4101 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004102 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004103 return new ICmpInst(ICI->getInversePredicate(),
4104 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004105
Reid Spencer266e42b2006-12-23 06:05:41 +00004106 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004107 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004108 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4109 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004110 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4111 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004112 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004113 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004114 }
Chris Lattner023a4832004-06-18 06:07:51 +00004115
4116 // ~(~X & Y) --> (X | ~Y)
4117 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4118 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4119 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4120 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004121 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004122 Op0I->getOperand(1)->getName()+".not");
4123 InsertNewInstBefore(NotY, I);
4124 return BinaryOperator::createOr(Op0NotVal, NotY);
4125 }
4126 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004127
Chris Lattner97638592003-07-23 21:37:07 +00004128 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004129 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004130 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004131 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004132 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4133 return BinaryOperator::createSub(
4134 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004135 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004136 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004137 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004138 // (X + C) ^ signbit -> (X + C + signbit)
4139 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4140 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004141
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004142 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004143 } else if (Op0I->getOpcode() == Instruction::Or) {
4144 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004145 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004146 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4147 // Anything in both C1 and C2 is known to be zero, remove it from
4148 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004149 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004150 NewRHS = ConstantExpr::getAnd(NewRHS,
4151 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004152 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004153 I.setOperand(0, Op0I->getOperand(0));
4154 I.setOperand(1, NewRHS);
4155 return &I;
4156 }
Chris Lattner97638592003-07-23 21:37:07 +00004157 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004158 }
Chris Lattner183b3362004-04-09 19:05:30 +00004159
4160 // Try to fold constant and into select arguments.
4161 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004162 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004163 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004164 if (isa<PHINode>(Op0))
4165 if (Instruction *NV = FoldOpIntoPhi(I))
4166 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004167 }
4168
Chris Lattnerbb74e222003-03-10 23:06:50 +00004169 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004170 if (X == Op1)
4171 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004172 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004173
Chris Lattnerbb74e222003-03-10 23:06:50 +00004174 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004175 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004176 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004177
Chris Lattner07418422007-03-18 22:51:34 +00004178
4179 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4180 if (Op1I) {
4181 Value *A, *B;
4182 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4183 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004184 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004185 I.swapOperands();
4186 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004187 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004188 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004189 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004190 }
Chris Lattner07418422007-03-18 22:51:34 +00004191 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4192 if (Op0 == A) // A^(A^B) == B
4193 return ReplaceInstUsesWith(I, B);
4194 else if (Op0 == B) // A^(B^A) == B
4195 return ReplaceInstUsesWith(I, A);
4196 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004197 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004198 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004199 std::swap(A, B);
4200 }
Chris Lattner07418422007-03-18 22:51:34 +00004201 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004202 I.swapOperands(); // Simplified below.
4203 std::swap(Op0, Op1);
4204 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004205 }
Chris Lattner07418422007-03-18 22:51:34 +00004206 }
4207
4208 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4209 if (Op0I) {
4210 Value *A, *B;
4211 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4212 if (A == Op1) // (B|A)^B == (A|B)^B
4213 std::swap(A, B);
4214 if (B == Op1) { // (A|B)^B == A & ~B
4215 Instruction *NotB =
4216 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4217 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004218 }
Chris Lattner07418422007-03-18 22:51:34 +00004219 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4220 if (Op1 == A) // (A^B)^A == B
4221 return ReplaceInstUsesWith(I, B);
4222 else if (Op1 == B) // (B^A)^A == B
4223 return ReplaceInstUsesWith(I, A);
4224 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4225 if (A == Op1) // (A&B)^A -> (B&A)^A
4226 std::swap(A, B);
4227 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004228 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004229 Instruction *N =
4230 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004231 return BinaryOperator::createAnd(N, Op1);
4232 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004233 }
Chris Lattner07418422007-03-18 22:51:34 +00004234 }
4235
4236 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4237 if (Op0I && Op1I && Op0I->isShift() &&
4238 Op0I->getOpcode() == Op1I->getOpcode() &&
4239 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4240 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4241 Instruction *NewOp =
4242 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4243 Op1I->getOperand(0),
4244 Op0I->getName()), I);
4245 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4246 Op1I->getOperand(1));
4247 }
4248
4249 if (Op0I && Op1I) {
4250 Value *A, *B, *C, *D;
4251 // (A & B)^(A | B) -> A ^ B
4252 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4253 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4254 if ((A == C && B == D) || (A == D && B == C))
4255 return BinaryOperator::createXor(A, B);
4256 }
4257 // (A | B)^(A & B) -> A ^ B
4258 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4259 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4260 if ((A == C && B == D) || (A == D && B == C))
4261 return BinaryOperator::createXor(A, B);
4262 }
4263
4264 // (A & B)^(C & D)
4265 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4266 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4267 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4268 // (X & Y)^(X & Y) -> (Y^Z) & X
4269 Value *X = 0, *Y = 0, *Z = 0;
4270 if (A == C)
4271 X = A, Y = B, Z = D;
4272 else if (A == D)
4273 X = A, Y = B, Z = C;
4274 else if (B == C)
4275 X = B, Y = A, Z = D;
4276 else if (B == D)
4277 X = B, Y = A, Z = C;
4278
4279 if (X) {
4280 Instruction *NewOp =
4281 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4282 return BinaryOperator::createAnd(NewOp, X);
4283 }
4284 }
4285 }
4286
Reid Spencer266e42b2006-12-23 06:05:41 +00004287 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4288 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4289 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004290 return R;
4291
Chris Lattner3af10532006-05-05 06:39:07 +00004292 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004293 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004294 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004295 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4296 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004297 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004298 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004299 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4300 I.getType(), TD) &&
4301 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4302 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004303 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4304 Op1C->getOperand(0),
4305 I.getName());
4306 InsertNewInstBefore(NewOp, I);
4307 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4308 }
Chris Lattner3af10532006-05-05 06:39:07 +00004309 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004310
Chris Lattner113f4f42002-06-25 16:13:24 +00004311 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004312}
4313
Chris Lattner6862fbd2004-09-29 17:40:11 +00004314/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4315/// overflowed for this type.
4316static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004317 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004318 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004319
Reid Spencerf4071162007-03-21 23:19:50 +00004320 if (IsSigned)
4321 if (In2->getValue().isNegative())
4322 return Result->getValue().sgt(In1->getValue());
4323 else
4324 return Result->getValue().slt(In1->getValue());
4325 else
4326 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004327}
4328
Chris Lattner0798af32005-01-13 20:14:25 +00004329/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4330/// code necessary to compute the offset from the base pointer (without adding
4331/// in the base pointer). Return the result as a signed integer of intptr size.
4332static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4333 TargetData &TD = IC.getTargetData();
4334 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004335 const Type *IntPtrTy = TD.getIntPtrType();
4336 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004337
4338 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004339 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004340
Chris Lattner0798af32005-01-13 20:14:25 +00004341 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4342 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004343 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004344 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004345 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4346 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004347 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004348 Scale = ConstantExpr::getMul(OpC, Scale);
4349 if (Constant *RC = dyn_cast<Constant>(Result))
4350 Result = ConstantExpr::getAdd(RC, Scale);
4351 else {
4352 // Emit an add instruction.
4353 Result = IC.InsertNewInstBefore(
4354 BinaryOperator::createAdd(Result, Scale,
4355 GEP->getName()+".offs"), I);
4356 }
4357 }
4358 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004359 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004360 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004361 Op->getName()+".c"), I);
4362 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004363 // We'll let instcombine(mul) convert this to a shl if possible.
4364 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4365 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004366
4367 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004368 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004369 GEP->getName()+".offs"), I);
4370 }
4371 }
4372 return Result;
4373}
4374
Reid Spencer266e42b2006-12-23 06:05:41 +00004375/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004376/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004377Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4378 ICmpInst::Predicate Cond,
4379 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004380 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004381
4382 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4383 if (isa<PointerType>(CI->getOperand(0)->getType()))
4384 RHS = CI->getOperand(0);
4385
Chris Lattner0798af32005-01-13 20:14:25 +00004386 Value *PtrBase = GEPLHS->getOperand(0);
4387 if (PtrBase == RHS) {
4388 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004389 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4390 // each index is zero or not.
4391 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004392 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004393 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4394 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004395 bool EmitIt = true;
4396 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4397 if (isa<UndefValue>(C)) // undef index -> undef.
4398 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4399 if (C->isNullValue())
4400 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004401 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4402 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004403 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004404 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004405 ConstantInt::get(Type::Int1Ty,
4406 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004407 }
4408
4409 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004410 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004411 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004412 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4413 if (InVal == 0)
4414 InVal = Comp;
4415 else {
4416 InVal = InsertNewInstBefore(InVal, I);
4417 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004418 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004419 InVal = BinaryOperator::createOr(InVal, Comp);
4420 else // True if all are equal
4421 InVal = BinaryOperator::createAnd(InVal, Comp);
4422 }
4423 }
4424 }
4425
4426 if (InVal)
4427 return InVal;
4428 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004429 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004430 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4431 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004432 }
Chris Lattner0798af32005-01-13 20:14:25 +00004433
Reid Spencer266e42b2006-12-23 06:05:41 +00004434 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004435 // the result to fold to a constant!
4436 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4437 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4438 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004439 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4440 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004441 }
4442 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004443 // If the base pointers are different, but the indices are the same, just
4444 // compare the base pointer.
4445 if (PtrBase != GEPRHS->getOperand(0)) {
4446 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004447 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004448 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004449 if (IndicesTheSame)
4450 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4451 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4452 IndicesTheSame = false;
4453 break;
4454 }
4455
4456 // If all indices are the same, just compare the base pointers.
4457 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004458 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4459 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004460
4461 // Otherwise, the base pointers are different and the indices are
4462 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004463 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004464 }
Chris Lattner0798af32005-01-13 20:14:25 +00004465
Chris Lattner81e84172005-01-13 22:25:21 +00004466 // If one of the GEPs has all zero indices, recurse.
4467 bool AllZeros = true;
4468 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4469 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4470 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4471 AllZeros = false;
4472 break;
4473 }
4474 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004475 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4476 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004477
4478 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004479 AllZeros = true;
4480 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4481 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4482 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4483 AllZeros = false;
4484 break;
4485 }
4486 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004487 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004488
Chris Lattner4fa89822005-01-14 00:20:05 +00004489 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4490 // If the GEPs only differ by one index, compare it.
4491 unsigned NumDifferences = 0; // Keep track of # differences.
4492 unsigned DiffOperand = 0; // The operand that differs.
4493 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4494 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004495 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4496 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004497 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004498 NumDifferences = 2;
4499 break;
4500 } else {
4501 if (NumDifferences++) break;
4502 DiffOperand = i;
4503 }
4504 }
4505
4506 if (NumDifferences == 0) // SAME GEP?
4507 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004508 ConstantInt::get(Type::Int1Ty,
4509 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004510 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004511 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4512 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004513 // Make sure we do a signed comparison here.
4514 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004515 }
4516 }
4517
Reid Spencer266e42b2006-12-23 06:05:41 +00004518 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004519 // the result to fold to a constant!
4520 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4521 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4522 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4523 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4524 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004525 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004526 }
4527 }
4528 return 0;
4529}
4530
Reid Spencer266e42b2006-12-23 06:05:41 +00004531Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4532 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004534
Chris Lattner6ee923f2007-01-14 19:42:17 +00004535 // Fold trivial predicates.
4536 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4537 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4538 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4539 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4540
4541 // Simplify 'fcmp pred X, X'
4542 if (Op0 == Op1) {
4543 switch (I.getPredicate()) {
4544 default: assert(0 && "Unknown predicate!");
4545 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4546 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4547 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4548 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4549 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4550 case FCmpInst::FCMP_OLT: // True if ordered and less than
4551 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4552 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4553
4554 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4555 case FCmpInst::FCMP_ULT: // True if unordered or less than
4556 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4557 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4558 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4559 I.setPredicate(FCmpInst::FCMP_UNO);
4560 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4561 return &I;
4562
4563 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4564 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4565 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4566 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4567 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4568 I.setPredicate(FCmpInst::FCMP_ORD);
4569 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4570 return &I;
4571 }
4572 }
4573
Reid Spencer266e42b2006-12-23 06:05:41 +00004574 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004575 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004576
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 // Handle fcmp with constant RHS
4578 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4579 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4580 switch (LHSI->getOpcode()) {
4581 case Instruction::PHI:
4582 if (Instruction *NV = FoldOpIntoPhi(I))
4583 return NV;
4584 break;
4585 case Instruction::Select:
4586 // If either operand of the select is a constant, we can fold the
4587 // comparison into the select arms, which will cause one to be
4588 // constant folded and the select turned into a bitwise or.
4589 Value *Op1 = 0, *Op2 = 0;
4590 if (LHSI->hasOneUse()) {
4591 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4592 // Fold the known value into the constant operand.
4593 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4594 // Insert a new FCmp of the other select operand.
4595 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4596 LHSI->getOperand(2), RHSC,
4597 I.getName()), I);
4598 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4599 // Fold the known value into the constant operand.
4600 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4601 // Insert a new FCmp of the other select operand.
4602 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4603 LHSI->getOperand(1), RHSC,
4604 I.getName()), I);
4605 }
4606 }
4607
4608 if (Op1)
4609 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4610 break;
4611 }
4612 }
4613
4614 return Changed ? &I : 0;
4615}
4616
4617Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4618 bool Changed = SimplifyCompare(I);
4619 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4620 const Type *Ty = Op0->getType();
4621
4622 // icmp X, X
4623 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004624 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4625 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004626
4627 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004628 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004629
4630 // icmp of GlobalValues can never equal each other as long as they aren't
4631 // external weak linkage type.
4632 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4633 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4634 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004635 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4636 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004637
4638 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004639 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004640 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4641 isa<ConstantPointerNull>(Op0)) &&
4642 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004643 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004644 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4645 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004646
Reid Spencer266e42b2006-12-23 06:05:41 +00004647 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004648 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004649 switch (I.getPredicate()) {
4650 default: assert(0 && "Invalid icmp instruction!");
4651 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004652 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004653 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004654 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004655 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004656 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004657 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004658
Reid Spencer266e42b2006-12-23 06:05:41 +00004659 case ICmpInst::ICMP_UGT:
4660 case ICmpInst::ICMP_SGT:
4661 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004662 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004663 case ICmpInst::ICMP_ULT:
4664 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004665 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4666 InsertNewInstBefore(Not, I);
4667 return BinaryOperator::createAnd(Not, Op1);
4668 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004669 case ICmpInst::ICMP_UGE:
4670 case ICmpInst::ICMP_SGE:
4671 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004672 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004673 case ICmpInst::ICMP_ULE:
4674 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004675 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4676 InsertNewInstBefore(Not, I);
4677 return BinaryOperator::createOr(Not, Op1);
4678 }
4679 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004680 }
4681
Chris Lattner2dd01742004-06-09 04:24:29 +00004682 // See if we are doing a comparison between a constant and an instruction that
4683 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004684 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004685 switch (I.getPredicate()) {
4686 default: break;
4687 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4688 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004689 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004690 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4691 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4692 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4693 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00004694 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4695 if (CI->isMinValue(true))
4696 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4697 ConstantInt::getAllOnesValue(Op0->getType()));
4698
Reid Spencer266e42b2006-12-23 06:05:41 +00004699 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004700
Reid Spencer266e42b2006-12-23 06:05:41 +00004701 case ICmpInst::ICMP_SLT:
4702 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004703 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004704 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4705 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4706 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4707 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4708 break;
4709
4710 case ICmpInst::ICMP_UGT:
4711 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004712 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004713 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4714 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4715 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4716 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00004717
4718 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4719 if (CI->isMaxValue(true))
4720 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4721 ConstantInt::getNullValue(Op0->getType()));
Reid Spencer266e42b2006-12-23 06:05:41 +00004722 break;
4723
4724 case ICmpInst::ICMP_SGT:
4725 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004726 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004727 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4728 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4729 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4730 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4731 break;
4732
4733 case ICmpInst::ICMP_ULE:
4734 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004735 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004736 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4737 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4738 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4739 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4740 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004741
Reid Spencer266e42b2006-12-23 06:05:41 +00004742 case ICmpInst::ICMP_SLE:
4743 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004744 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004745 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4746 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4747 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4748 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4749 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004750
Reid Spencer266e42b2006-12-23 06:05:41 +00004751 case ICmpInst::ICMP_UGE:
4752 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004753 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004754 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4755 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4756 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4757 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4758 break;
4759
4760 case ICmpInst::ICMP_SGE:
4761 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004762 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004763 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4764 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4765 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4766 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4767 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004768 }
4769
Reid Spencer266e42b2006-12-23 06:05:41 +00004770 // If we still have a icmp le or icmp ge instruction, turn it into the
4771 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004772 // already been handled above, this requires little checking.
4773 //
Reid Spencer624766f2007-03-25 19:55:33 +00004774 switch (I.getPredicate()) {
4775 default: break;
4776 case ICmpInst::ICMP_ULE:
4777 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4778 case ICmpInst::ICMP_SLE:
4779 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4780 case ICmpInst::ICMP_UGE:
4781 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4782 case ICmpInst::ICMP_SGE:
4783 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4784 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004785
4786 // See if we can fold the comparison based on bits known to be zero or one
4787 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004788 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4789 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4790 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004791 KnownZero, KnownOne, 0))
4792 return &I;
4793
4794 // Given the known and unknown bits, compute a range that the LHS could be
4795 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004796 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004797 // Compute the Min, Max and RHS values based on the known bits. For the
4798 // EQ and NE we use unsigned values.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00004799 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4800 const APInt& RHSVal = CI->getValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00004801 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004802 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4803 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004804 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004805 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4806 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004807 }
4808 switch (I.getPredicate()) { // LE/GE have been folded already.
4809 default: assert(0 && "Unknown icmp opcode!");
4810 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004811 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004812 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004813 break;
4814 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004815 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004816 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004817 break;
4818 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004819 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004820 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004821 if (Min.uge(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004822 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004823 break;
4824 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004825 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004826 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004827 if (Max.ule(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004828 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004829 break;
4830 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004831 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004832 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004833 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004834 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004835 break;
4836 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004837 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004838 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004839 if (Max.sle(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004840 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004841 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004842 }
4843 }
4844
Reid Spencer266e42b2006-12-23 06:05:41 +00004845 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004846 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004847 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004848 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00004849 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4850 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004851 }
4852
Chris Lattnera74deaf2007-04-03 17:43:25 +00004853 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00004854 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4855 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4856 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004857 case Instruction::GetElementPtr:
4858 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004859 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00004860 bool isAllZeros = true;
4861 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4862 if (!isa<Constant>(LHSI->getOperand(i)) ||
4863 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4864 isAllZeros = false;
4865 break;
4866 }
4867 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004868 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00004869 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4870 }
4871 break;
4872
Chris Lattner77c32c32005-04-23 15:31:55 +00004873 case Instruction::PHI:
4874 if (Instruction *NV = FoldOpIntoPhi(I))
4875 return NV;
4876 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00004877 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00004878 // If either operand of the select is a constant, we can fold the
4879 // comparison into the select arms, which will cause one to be
4880 // constant folded and the select turned into a bitwise or.
4881 Value *Op1 = 0, *Op2 = 0;
4882 if (LHSI->hasOneUse()) {
4883 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4884 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004885 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4886 // Insert a new ICmp of the other select operand.
4887 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4888 LHSI->getOperand(2), RHSC,
4889 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004890 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4891 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004892 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4893 // Insert a new ICmp of the other select operand.
4894 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4895 LHSI->getOperand(1), RHSC,
4896 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004897 }
4898 }
Jeff Cohen82639852005-04-23 21:38:35 +00004899
Chris Lattner77c32c32005-04-23 15:31:55 +00004900 if (Op1)
4901 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4902 break;
4903 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00004904 case Instruction::Malloc:
4905 // If we have (malloc != null), and if the malloc has a single use, we
4906 // can assume it is successful and remove the malloc.
4907 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4908 AddToWorkList(LHSI);
4909 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4910 !isTrueWhenEqual(I)));
4911 }
4912 break;
4913 }
Chris Lattner77c32c32005-04-23 15:31:55 +00004914 }
4915
Reid Spencer266e42b2006-12-23 06:05:41 +00004916 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00004917 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004918 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004919 return NI;
4920 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4922 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004923 return NI;
4924
Reid Spencer266e42b2006-12-23 06:05:41 +00004925 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00004926 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4927 // now.
4928 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4929 if (isa<PointerType>(Op0->getType()) &&
4930 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004931 // We keep moving the cast from the left operand over to the right
4932 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00004933 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004934
Chris Lattner64d87b02007-01-06 01:45:59 +00004935 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4936 // so eliminate it as well.
4937 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4938 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004939
Chris Lattner16930792003-11-03 04:25:02 +00004940 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00004941 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00004942 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004943 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004944 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00004946 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004947 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004948 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00004949 }
Chris Lattner64d87b02007-01-06 01:45:59 +00004950 }
4951
4952 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004953 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00004954 // This comes up when you have code like
4955 // int X = A < B;
4956 // if (X) ...
4957 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004958 // with a constant or another cast from the same type.
4959 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004960 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004961 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004962 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004963
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004964 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00004965 Value *A, *B, *C, *D;
4966 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4967 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4968 Value *OtherVal = A == Op1 ? B : A;
4969 return new ICmpInst(I.getPredicate(), OtherVal,
4970 Constant::getNullValue(A->getType()));
4971 }
4972
4973 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4974 // A^c1 == C^c2 --> A == C^(c1^c2)
4975 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4976 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
4977 if (Op1->hasOneUse()) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004978 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner17c7c032007-01-05 03:04:57 +00004979 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
4980 return new ICmpInst(I.getPredicate(), A,
4981 InsertNewInstBefore(Xor, I));
4982 }
4983
4984 // A^B == A^D -> B == D
4985 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4986 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4987 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4988 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4989 }
4990 }
4991
4992 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4993 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004994 // A == (A^B) -> B == 0
4995 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00004996 return new ICmpInst(I.getPredicate(), OtherVal,
4997 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00004998 }
4999 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005000 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005001 return new ICmpInst(I.getPredicate(), B,
5002 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005003 }
5004 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005005 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005006 return new ICmpInst(I.getPredicate(), B,
5007 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005008 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005009
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005010 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5011 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5012 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5013 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5014 Value *X = 0, *Y = 0, *Z = 0;
5015
5016 if (A == C) {
5017 X = B; Y = D; Z = A;
5018 } else if (A == D) {
5019 X = B; Y = C; Z = A;
5020 } else if (B == C) {
5021 X = A; Y = D; Z = B;
5022 } else if (B == D) {
5023 X = A; Y = C; Z = B;
5024 }
5025
5026 if (X) { // Build (X^Y) & Z
5027 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5028 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5029 I.setOperand(0, Op1);
5030 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5031 return &I;
5032 }
5033 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005034 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005035 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005036}
5037
Chris Lattnera74deaf2007-04-03 17:43:25 +00005038/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5039///
5040Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5041 Instruction *LHSI,
5042 ConstantInt *RHS) {
5043 const APInt &RHSV = RHS->getValue();
5044
5045 switch (LHSI->getOpcode()) {
Duncan Sandsf01a47c2007-04-04 06:42:45 +00005046 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00005047 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5048 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5049 // fold the xor.
5050 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5051 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5052 Value *CompareVal = LHSI->getOperand(0);
5053
5054 // If the sign bit of the XorCST is not set, there is no change to
5055 // the operation, just stop using the Xor.
5056 if (!XorCST->getValue().isNegative()) {
5057 ICI.setOperand(0, CompareVal);
5058 AddToWorkList(LHSI);
5059 return &ICI;
5060 }
5061
5062 // Was the old condition true if the operand is positive?
5063 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5064
5065 // If so, the new one isn't.
5066 isTrueIfPositive ^= true;
5067
5068 if (isTrueIfPositive)
5069 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5070 else
5071 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5072 }
5073 }
5074 break;
5075 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5076 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5077 LHSI->getOperand(0)->hasOneUse()) {
5078 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5079
5080 // If the LHS is an AND of a truncating cast, we can widen the
5081 // and/compare to be the input width without changing the value
5082 // produced, eliminating a cast.
5083 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5084 // We can do this transformation if either the AND constant does not
5085 // have its sign bit set or if it is an equality comparison.
5086 // Extending a relational comparison when we're checking the sign
5087 // bit would not work.
5088 if (Cast->hasOneUse() &&
5089 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5090 RHSV.isPositive())) {
5091 uint32_t BitWidth =
5092 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5093 APInt NewCST = AndCST->getValue();
5094 NewCST.zext(BitWidth);
5095 APInt NewCI = RHSV;
5096 NewCI.zext(BitWidth);
5097 Instruction *NewAnd =
5098 BinaryOperator::createAnd(Cast->getOperand(0),
5099 ConstantInt::get(NewCST),LHSI->getName());
5100 InsertNewInstBefore(NewAnd, ICI);
5101 return new ICmpInst(ICI.getPredicate(), NewAnd,
5102 ConstantInt::get(NewCI));
5103 }
5104 }
5105
5106 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5107 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5108 // happens a LOT in code produced by the C front-end, for bitfield
5109 // access.
5110 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5111 if (Shift && !Shift->isShift())
5112 Shift = 0;
5113
5114 ConstantInt *ShAmt;
5115 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5116 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5117 const Type *AndTy = AndCST->getType(); // Type of the and.
5118
5119 // We can fold this as long as we can't shift unknown bits
5120 // into the mask. This can only happen with signed shift
5121 // rights, as they sign-extend.
5122 if (ShAmt) {
5123 bool CanFold = Shift->isLogicalShift();
5124 if (!CanFold) {
5125 // To test for the bad case of the signed shr, see if any
5126 // of the bits shifted in could be tested after the mask.
5127 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5128 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5129
5130 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5131 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5132 AndCST->getValue()) == 0)
5133 CanFold = true;
5134 }
5135
5136 if (CanFold) {
5137 Constant *NewCst;
5138 if (Shift->getOpcode() == Instruction::Shl)
5139 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5140 else
5141 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5142
5143 // Check to see if we are shifting out any of the bits being
5144 // compared.
5145 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5146 // If we shifted bits out, the fold is not going to work out.
5147 // As a special case, check to see if this means that the
5148 // result is always true or false now.
5149 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5150 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5151 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5152 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5153 } else {
5154 ICI.setOperand(1, NewCst);
5155 Constant *NewAndCST;
5156 if (Shift->getOpcode() == Instruction::Shl)
5157 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5158 else
5159 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5160 LHSI->setOperand(1, NewAndCST);
5161 LHSI->setOperand(0, Shift->getOperand(0));
5162 AddToWorkList(Shift); // Shift is dead.
5163 AddUsesToWorkList(ICI);
5164 return &ICI;
5165 }
5166 }
5167 }
5168
5169 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5170 // preferable because it allows the C<<Y expression to be hoisted out
5171 // of a loop if Y is invariant and X is not.
5172 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5173 ICI.isEquality() && !Shift->isArithmeticShift() &&
5174 isa<Instruction>(Shift->getOperand(0))) {
5175 // Compute C << Y.
5176 Value *NS;
5177 if (Shift->getOpcode() == Instruction::LShr) {
5178 NS = BinaryOperator::createShl(AndCST,
5179 Shift->getOperand(1), "tmp");
5180 } else {
5181 // Insert a logical shift.
5182 NS = BinaryOperator::createLShr(AndCST,
5183 Shift->getOperand(1), "tmp");
5184 }
5185 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5186
5187 // Compute X & (C << Y).
5188 Instruction *NewAnd =
5189 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5190 InsertNewInstBefore(NewAnd, ICI);
5191
5192 ICI.setOperand(0, NewAnd);
5193 return &ICI;
5194 }
5195 }
5196 break;
5197
5198 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5199 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5200 if (ICI.isEquality()) {
5201 uint32_t TypeBits = RHSV.getBitWidth();
5202
5203 // Check that the shift amount is in range. If not, don't perform
5204 // undefined shifts. When the shift is visited it will be
5205 // simplified.
5206 if (ShAmt->uge(TypeBits))
5207 break;
5208
5209 // If we are comparing against bits always shifted out, the
5210 // comparison cannot succeed.
5211 Constant *Comp =
5212 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5213 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5214 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5215 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5216 return ReplaceInstUsesWith(ICI, Cst);
5217 }
5218
5219 if (LHSI->hasOneUse()) {
5220 // Otherwise strength reduce the shift into an and.
5221 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5222 Constant *Mask =
5223 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5224
5225 Instruction *AndI =
5226 BinaryOperator::createAnd(LHSI->getOperand(0),
5227 Mask, LHSI->getName()+".mask");
5228 Value *And = InsertNewInstBefore(AndI, ICI);
5229 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnere5bbb3c2007-04-03 23:29:39 +00005230 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00005231 }
5232 }
5233 }
5234 break;
5235
5236 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5237 case Instruction::AShr:
5238 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5239 if (ICI.isEquality()) {
5240 // Check that the shift amount is in range. If not, don't perform
5241 // undefined shifts. When the shift is visited it will be
5242 // simplified.
5243 uint32_t TypeBits = RHSV.getBitWidth();
5244 if (ShAmt->uge(TypeBits))
5245 break;
5246 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5247
5248 // If we are comparing against bits always shifted out, the
5249 // comparison cannot succeed.
5250 APInt Comp = RHSV << ShAmtVal;
5251 if (LHSI->getOpcode() == Instruction::LShr)
5252 Comp = Comp.lshr(ShAmtVal);
5253 else
5254 Comp = Comp.ashr(ShAmtVal);
5255
5256 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5257 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5258 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5259 return ReplaceInstUsesWith(ICI, Cst);
5260 }
5261
5262 if (LHSI->hasOneUse() || RHSV == 0) {
5263 // Otherwise strength reduce the shift into an and.
5264 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5265 Constant *Mask = ConstantInt::get(Val);
5266
5267 Instruction *AndI =
5268 BinaryOperator::createAnd(LHSI->getOperand(0),
5269 Mask, LHSI->getName()+".mask");
5270 Value *And = InsertNewInstBefore(AndI, ICI);
5271 return new ICmpInst(ICI.getPredicate(), And,
5272 ConstantExpr::getShl(RHS, ShAmt));
5273 }
5274 }
5275 }
5276 break;
5277
5278 case Instruction::SDiv:
5279 case Instruction::UDiv:
5280 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5281 // Fold this div into the comparison, producing a range check.
5282 // Determine, based on the divide type, what the range is being
5283 // checked. If there is an overflow on the low or high side, remember
5284 // it, otherwise compute the range [low, hi) bounding the new value.
5285 // See: InsertRangeTest above for the kinds of replacements possible.
5286 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5287 // FIXME: If the operand types don't match the type of the divide
5288 // then don't attempt this transform. The code below doesn't have the
5289 // logic to deal with a signed divide and an unsigned compare (and
5290 // vice versa). This is because (x /s C1) <s C2 produces different
5291 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5292 // (x /u C1) <u C2. Simply casting the operands and result won't
5293 // work. :( The if statement below tests that condition and bails
5294 // if it finds it.
5295 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5296 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5297 break;
5298 if (DivRHS->isZero())
5299 break; // Don't hack on div by zero
5300
5301 // Initialize the variables that will indicate the nature of the
5302 // range check.
5303 bool LoOverflow = false, HiOverflow = false;
5304 ConstantInt *LoBound = 0, *HiBound = 0;
5305
5306 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5307 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5308 // C2 (CI). By solving for X we can turn this into a range check
5309 // instead of computing a divide.
5310 ConstantInt *Prod = Multiply(RHS, DivRHS);
5311
5312 // Determine if the product overflows by seeing if the product is
5313 // not equal to the divide. Make sure we do the same kind of divide
5314 // as in the LHS instruction that we're folding.
5315 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5316 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5317
5318 // Get the ICmp opcode
5319 ICmpInst::Predicate predicate = ICI.getPredicate();
5320
5321 if (!DivIsSigned) { // udiv
5322 LoBound = Prod;
5323 LoOverflow = ProdOV;
5324 HiOverflow = ProdOV ||
5325 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5326 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5327 if (RHSV == 0) { // (X / pos) op 0
5328 // Can't overflow.
5329 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5330 HiBound = DivRHS;
5331 } else if (RHSV.isPositive()) { // (X / pos) op pos
5332 LoBound = Prod;
5333 LoOverflow = ProdOV;
5334 HiOverflow = ProdOV ||
5335 AddWithOverflow(HiBound, Prod, DivRHS, true);
5336 } else { // (X / pos) op neg
5337 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5338 LoOverflow = AddWithOverflow(LoBound, Prod,
5339 cast<ConstantInt>(DivRHSH), true);
5340 HiBound = AddOne(Prod);
5341 HiOverflow = ProdOV;
5342 }
5343 } else { // Divisor is < 0.
5344 if (RHSV == 0) { // (X / neg) op 0
5345 LoBound = AddOne(DivRHS);
5346 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5347 if (HiBound == DivRHS)
5348 LoBound = 0; // - INTMIN = INTMIN
5349 } else if (RHSV.isPositive()) { // (X / neg) op pos
5350 HiOverflow = LoOverflow = ProdOV;
5351 if (!LoOverflow)
5352 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5353 true);
5354 HiBound = AddOne(Prod);
5355 } else { // (X / neg) op neg
5356 LoBound = Prod;
5357 LoOverflow = HiOverflow = ProdOV;
5358 HiBound = Subtract(Prod, DivRHS);
5359 }
5360
5361 // Dividing by a negate swaps the condition.
5362 predicate = ICmpInst::getSwappedPredicate(predicate);
5363 }
5364
5365 if (LoBound) {
5366 Value *X = LHSI->getOperand(0);
5367 switch (predicate) {
5368 default: assert(0 && "Unhandled icmp opcode!");
5369 case ICmpInst::ICMP_EQ:
5370 if (LoOverflow && HiOverflow)
5371 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5372 else if (HiOverflow)
5373 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5374 ICmpInst::ICMP_UGE, X, LoBound);
5375 else if (LoOverflow)
5376 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5377 ICmpInst::ICMP_ULT, X, HiBound);
5378 else
5379 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5380 true, ICI);
5381 case ICmpInst::ICMP_NE:
5382 if (LoOverflow && HiOverflow)
5383 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5384 else if (HiOverflow)
5385 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5386 ICmpInst::ICMP_ULT, X, LoBound);
5387 else if (LoOverflow)
5388 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5389 ICmpInst::ICMP_UGE, X, HiBound);
5390 else
5391 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5392 false, ICI);
5393 case ICmpInst::ICMP_ULT:
5394 case ICmpInst::ICMP_SLT:
5395 if (LoOverflow)
5396 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5397 return new ICmpInst(predicate, X, LoBound);
5398 case ICmpInst::ICMP_UGT:
5399 case ICmpInst::ICMP_SGT:
5400 if (HiOverflow)
5401 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5402 if (predicate == ICmpInst::ICMP_UGT)
5403 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5404 else
5405 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5406 }
5407 }
5408 }
5409 break;
5410 }
5411
5412 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5413 if (ICI.isEquality()) {
5414 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5415
5416 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5417 // the second operand is a constant, simplify a bit.
5418 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5419 switch (BO->getOpcode()) {
5420 case Instruction::SRem:
5421 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5422 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5423 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5424 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5425 Instruction *NewRem =
5426 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5427 BO->getName());
5428 InsertNewInstBefore(NewRem, ICI);
5429 return new ICmpInst(ICI.getPredicate(), NewRem,
5430 Constant::getNullValue(BO->getType()));
5431 }
5432 }
5433 break;
5434 case Instruction::Add:
5435 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5436 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5437 if (BO->hasOneUse())
5438 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5439 Subtract(RHS, BOp1C));
5440 } else if (RHSV == 0) {
5441 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5442 // efficiently invertible, or if the add has just this one use.
5443 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5444
5445 if (Value *NegVal = dyn_castNegVal(BOp1))
5446 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5447 else if (Value *NegVal = dyn_castNegVal(BOp0))
5448 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5449 else if (BO->hasOneUse()) {
5450 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5451 InsertNewInstBefore(Neg, ICI);
5452 Neg->takeName(BO);
5453 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5454 }
5455 }
5456 break;
5457 case Instruction::Xor:
5458 // For the xor case, we can xor two constants together, eliminating
5459 // the explicit xor.
5460 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5461 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5462 ConstantExpr::getXor(RHS, BOC));
5463
5464 // FALLTHROUGH
5465 case Instruction::Sub:
5466 // Replace (([sub|xor] A, B) != 0) with (A != B)
5467 if (RHSV == 0)
5468 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5469 BO->getOperand(1));
5470 break;
5471
5472 case Instruction::Or:
5473 // If bits are being or'd in that are not present in the constant we
5474 // are comparing against, then the comparison could never succeed!
5475 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5476 Constant *NotCI = ConstantExpr::getNot(RHS);
5477 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5478 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5479 isICMP_NE));
5480 }
5481 break;
5482
5483 case Instruction::And:
5484 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5485 // If bits are being compared against that are and'd out, then the
5486 // comparison can never succeed!
5487 if ((RHSV & ~BOC->getValue()) != 0)
5488 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5489 isICMP_NE));
5490
5491 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5492 if (RHS == BOC && RHSV.isPowerOf2())
5493 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5494 ICmpInst::ICMP_NE, LHSI,
5495 Constant::getNullValue(RHS->getType()));
5496
5497 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5498 if (isSignBit(BOC)) {
5499 Value *X = BO->getOperand(0);
5500 Constant *Zero = Constant::getNullValue(X->getType());
5501 ICmpInst::Predicate pred = isICMP_NE ?
5502 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5503 return new ICmpInst(pred, X, Zero);
5504 }
5505
5506 // ((X & ~7) == 0) --> X < 8
5507 if (RHSV == 0 && isHighOnes(BOC)) {
5508 Value *X = BO->getOperand(0);
5509 Constant *NegX = ConstantExpr::getNeg(BOC);
5510 ICmpInst::Predicate pred = isICMP_NE ?
5511 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5512 return new ICmpInst(pred, X, NegX);
5513 }
5514 }
5515 default: break;
5516 }
5517 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5518 // Handle icmp {eq|ne} <intrinsic>, intcst.
5519 if (II->getIntrinsicID() == Intrinsic::bswap) {
5520 AddToWorkList(II);
5521 ICI.setOperand(0, II->getOperand(1));
5522 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5523 return &ICI;
5524 }
5525 }
5526 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattner28d921d2007-04-14 23:32:02 +00005527 // If the LHS is a cast from an integral value of the same size,
5528 // then since we know the RHS is a constant, try to simlify.
Chris Lattnera74deaf2007-04-03 17:43:25 +00005529 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5530 Value *CastOp = Cast->getOperand(0);
5531 const Type *SrcTy = CastOp->getType();
5532 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5533 if (SrcTy->isInteger() &&
5534 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5535 // If this is an unsigned comparison, try to make the comparison use
5536 // smaller constant values.
5537 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5538 // X u< 128 => X s> -1
5539 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5540 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5541 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5542 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5543 // X u> 127 => X s< 0
5544 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5545 Constant::getNullValue(SrcTy));
5546 }
5547 }
5548 }
5549 }
5550 return 0;
5551}
5552
5553/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5554/// We only handle extending casts so far.
5555///
Reid Spencer266e42b2006-12-23 06:05:41 +00005556Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5557 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005558 Value *LHSCIOp = LHSCI->getOperand(0);
5559 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005560 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005561 Value *RHSCIOp;
5562
Reid Spencer266e42b2006-12-23 06:05:41 +00005563 // We only handle extension cast instructions, so far. Enforce this.
5564 if (LHSCI->getOpcode() != Instruction::ZExt &&
5565 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005566 return 0;
5567
Reid Spencer266e42b2006-12-23 06:05:41 +00005568 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5569 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005570
Reid Spencer266e42b2006-12-23 06:05:41 +00005571 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005572 // Not an extension from the same type?
5573 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005574 if (RHSCIOp->getType() != LHSCIOp->getType())
5575 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005576
5577 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5578 // and the other is a zext), then we can't handle this.
5579 if (CI->getOpcode() != LHSCI->getOpcode())
5580 return 0;
5581
5582 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5583 // then we can't handle this.
5584 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5585 return 0;
5586
5587 // Okay, just insert a compare of the reduced operands now!
5588 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005589 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005590
Reid Spencer266e42b2006-12-23 06:05:41 +00005591 // If we aren't dealing with a constant on the RHS, exit early
5592 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5593 if (!CI)
5594 return 0;
5595
5596 // Compute the constant that would happen if we truncated to SrcTy then
5597 // reextended to DestTy.
5598 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5599 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5600
5601 // If the re-extended constant didn't change...
5602 if (Res2 == CI) {
5603 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5604 // For example, we might have:
5605 // %A = sext short %X to uint
5606 // %B = icmp ugt uint %A, 1330
5607 // It is incorrect to transform this into
5608 // %B = icmp ugt short %X, 1330
5609 // because %A may have negative value.
5610 //
5611 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5612 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005613 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005614 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5615 else
5616 return 0;
5617 }
5618
5619 // The re-extended constant changed so the constant cannot be represented
5620 // in the shorter type. Consequently, we cannot emit a simple comparison.
5621
5622 // First, handle some easy cases. We know the result cannot be equal at this
5623 // point so handle the ICI.isEquality() cases
5624 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005625 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005626 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005627 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005628
5629 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5630 // should have been folded away previously and not enter in here.
5631 Value *Result;
5632 if (isSignedCmp) {
5633 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005634 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005635 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005636 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005637 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005638 } else {
5639 // We're performing an unsigned comparison.
5640 if (isSignedExt) {
5641 // We're performing an unsigned comp with a sign extended value.
5642 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005643 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005644 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5645 NegOne, ICI.getName()), ICI);
5646 } else {
5647 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005648 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005649 }
5650 }
5651
5652 // Finally, return the value computed.
5653 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5654 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5655 return ReplaceInstUsesWith(ICI, Result);
5656 } else {
5657 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5658 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5659 "ICmp should be folded!");
5660 if (Constant *CI = dyn_cast<Constant>(Result))
5661 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5662 else
5663 return BinaryOperator::createNot(Result);
5664 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005665}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005666
Reid Spencer2341c222007-02-02 02:16:23 +00005667Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5668 return commonShiftTransforms(I);
5669}
5670
5671Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5672 return commonShiftTransforms(I);
5673}
5674
5675Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5676 return commonShiftTransforms(I);
5677}
5678
5679Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5680 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005682
5683 // shl X, 0 == X and shr X, 0 == X
5684 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005685 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005686 Op0 == Constant::getNullValue(Op0->getType()))
5687 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005688
Reid Spencer266e42b2006-12-23 06:05:41 +00005689 if (isa<UndefValue>(Op0)) {
5690 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005691 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005692 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005693 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5694 }
5695 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005696 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5697 return ReplaceInstUsesWith(I, Op0);
5698 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005699 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005700 }
5701
Chris Lattnerd4dee402006-11-10 23:38:52 +00005702 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5703 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005704 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005705 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005706 return ReplaceInstUsesWith(I, CSI);
5707
Chris Lattner183b3362004-04-09 19:05:30 +00005708 // Try to fold constant and into select arguments.
5709 if (isa<Constant>(Op0))
5710 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005712 return R;
5713
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005714 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005715 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005716 if (MaskedValueIsZero(Op0,
5717 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005718 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005719 }
5720 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005721
Reid Spencere0fc4df2006-10-20 07:07:24 +00005722 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005723 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5724 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005725 return 0;
5726}
5727
Reid Spencere0fc4df2006-10-20 07:07:24 +00005728Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005729 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005730 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005731
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005732 // See if we can simplify any instructions used by the instruction whose sole
5733 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005734 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5735 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5736 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005737 KnownZero, KnownOne))
5738 return &I;
5739
Chris Lattner14553932006-01-06 07:12:35 +00005740 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5741 // of a signed value.
5742 //
Zhou Shengb25806f2007-03-30 09:29:48 +00005743 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005744 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005745 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5746 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005747 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005748 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005749 }
Chris Lattner14553932006-01-06 07:12:35 +00005750 }
5751
5752 // ((X*C1) << C2) == (X * (C1 << C2))
5753 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5754 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5755 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5756 return BinaryOperator::createMul(BO->getOperand(0),
5757 ConstantExpr::getShl(BOOp, Op1));
5758
5759 // Try to fold constant and into select arguments.
5760 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5761 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5762 return R;
5763 if (isa<PHINode>(Op0))
5764 if (Instruction *NV = FoldOpIntoPhi(I))
5765 return NV;
5766
5767 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005768 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5769 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5770 Value *V1, *V2;
5771 ConstantInt *CC;
5772 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005773 default: break;
5774 case Instruction::Add:
5775 case Instruction::And:
5776 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005777 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005778 // These operators commute.
5779 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005780 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5781 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005782 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005783 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005784 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005785 Op0BO->getName());
5786 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005787 Instruction *X =
5788 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5789 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005790 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005791 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005792 return BinaryOperator::createAnd(X, ConstantInt::get(
5793 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005794 }
Chris Lattner14553932006-01-06 07:12:35 +00005795
Chris Lattner797dee72005-09-18 06:30:59 +00005796 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005797 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005798 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005799 match(Op0BOOp1,
5800 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005801 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5802 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005803 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005804 Op0BO->getOperand(0), Op1,
5805 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005806 InsertNewInstBefore(YS, I); // (Y << C)
5807 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005808 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005809 V1->getName()+".mask");
5810 InsertNewInstBefore(XM, I); // X & (CC << C)
5811
5812 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5813 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005814 }
Chris Lattner14553932006-01-06 07:12:35 +00005815
Reid Spencer2f34b982007-02-02 14:41:37 +00005816 // FALL THROUGH.
5817 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005818 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005819 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5820 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005821 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005822 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005823 Op0BO->getOperand(1), Op1,
5824 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005825 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005826 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005827 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005828 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005829 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005830 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005831 return BinaryOperator::createAnd(X, ConstantInt::get(
5832 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005833 }
Chris Lattner14553932006-01-06 07:12:35 +00005834
Chris Lattner1df0e982006-05-31 21:14:00 +00005835 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005836 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5837 match(Op0BO->getOperand(0),
5838 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005839 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005840 cast<BinaryOperator>(Op0BO->getOperand(0))
5841 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005842 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005843 Op0BO->getOperand(1), Op1,
5844 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005845 InsertNewInstBefore(YS, I); // (Y << C)
5846 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005847 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005848 V1->getName()+".mask");
5849 InsertNewInstBefore(XM, I); // X & (CC << C)
5850
Chris Lattner1df0e982006-05-31 21:14:00 +00005851 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005852 }
Chris Lattner14553932006-01-06 07:12:35 +00005853
Chris Lattner27cb9db2005-09-18 05:12:10 +00005854 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005855 }
Chris Lattner14553932006-01-06 07:12:35 +00005856 }
5857
5858
5859 // If the operand is an bitwise operator with a constant RHS, and the
5860 // shift is the only use, we can pull it out of the shift.
5861 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5862 bool isValid = true; // Valid only for And, Or, Xor
5863 bool highBitSet = false; // Transform if high bit of constant set?
5864
5865 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005866 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005867 case Instruction::Add:
5868 isValid = isLeftShift;
5869 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005870 case Instruction::Or:
5871 case Instruction::Xor:
5872 highBitSet = false;
5873 break;
5874 case Instruction::And:
5875 highBitSet = true;
5876 break;
Chris Lattner14553932006-01-06 07:12:35 +00005877 }
5878
5879 // If this is a signed shift right, and the high bit is modified
5880 // by the logical operation, do not perform the transformation.
5881 // The highBitSet boolean indicates the value of the high bit of
5882 // the constant which would cause it to be modified for this
5883 // operation.
5884 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005885 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005886 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005887 }
5888
5889 if (isValid) {
5890 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5891
5892 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005893 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005894 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005895 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005896
5897 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5898 NewRHS);
5899 }
5900 }
5901 }
5902 }
5903
Chris Lattnereb372a02006-01-06 07:52:12 +00005904 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005905 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5906 if (ShiftOp && !ShiftOp->isShift())
5907 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005908
Reid Spencere0fc4df2006-10-20 07:07:24 +00005909 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005910 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00005911 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5912 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00005913 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5914 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5915 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005916
Zhou Sheng56cda952007-04-02 08:20:41 +00005917 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005918 if (AmtSum > TypeBits)
5919 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005920
5921 const IntegerType *Ty = cast<IntegerType>(I.getType());
5922
5923 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005924 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005925 return BinaryOperator::create(I.getOpcode(), X,
5926 ConstantInt::get(Ty, AmtSum));
5927 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5928 I.getOpcode() == Instruction::AShr) {
5929 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5930 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5931 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5932 I.getOpcode() == Instruction::LShr) {
5933 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5934 Instruction *Shift =
5935 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5936 InsertNewInstBefore(Shift, I);
5937
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005938 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005939 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005940 }
5941
Chris Lattner3e009e82007-02-05 00:57:54 +00005942 // Okay, if we get here, one shift must be left, and the other shift must be
5943 // right. See if the amounts are equal.
5944 if (ShiftAmt1 == ShiftAmt2) {
5945 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5946 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005947 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005948 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005949 }
5950 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5951 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005952 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005953 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005954 }
5955 // We can simplify ((X << C) >>s C) into a trunc + sext.
5956 // NOTE: we could do this for any C, but that would make 'unusual' integer
5957 // types. For now, just stick to ones well-supported by the code
5958 // generators.
5959 const Type *SExtType = 0;
5960 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005961 case 1 :
5962 case 8 :
5963 case 16 :
5964 case 32 :
5965 case 64 :
5966 case 128:
5967 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5968 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005969 default: break;
5970 }
5971 if (SExtType) {
5972 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5973 InsertNewInstBefore(NewTrunc, I);
5974 return new SExtInst(NewTrunc, Ty);
5975 }
5976 // Otherwise, we can't handle it yet.
5977 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00005978 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005979
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005980 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005981 if (I.getOpcode() == Instruction::Shl) {
5982 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5983 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005984 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005985 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005986 InsertNewInstBefore(Shift, I);
5987
Reid Spencer52830322007-03-25 21:11:44 +00005988 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5989 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005990 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005991
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005992 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005993 if (I.getOpcode() == Instruction::LShr) {
5994 assert(ShiftOp->getOpcode() == Instruction::Shl);
5995 Instruction *Shift =
5996 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5997 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005998
Reid Spencer769a5a82007-03-26 17:18:58 +00005999 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006000 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006001 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006002
6003 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6004 } else {
6005 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00006006 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006007
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006008 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006009 if (I.getOpcode() == Instruction::Shl) {
6010 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6011 ShiftOp->getOpcode() == Instruction::AShr);
6012 Instruction *Shift =
6013 BinaryOperator::create(ShiftOp->getOpcode(), X,
6014 ConstantInt::get(Ty, ShiftDiff));
6015 InsertNewInstBefore(Shift, I);
6016
Reid Spencer52830322007-03-25 21:11:44 +00006017 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006018 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006019 }
6020
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006021 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006022 if (I.getOpcode() == Instruction::LShr) {
6023 assert(ShiftOp->getOpcode() == Instruction::Shl);
6024 Instruction *Shift =
6025 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6026 InsertNewInstBefore(Shift, I);
6027
Reid Spencer441486c2007-03-26 23:45:51 +00006028 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006029 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006030 }
6031
6032 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006033 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006034 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006035 return 0;
6036}
6037
Chris Lattner48a44f72002-05-02 17:06:02 +00006038
Chris Lattner8f663e82005-10-29 04:36:15 +00006039/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6040/// expression. If so, decompose it, returning some value X, such that Val is
6041/// X*Scale+Offset.
6042///
6043static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006044 int &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006045 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006046 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006047 Offset = CI->getZExtValue();
6048 Scale = 1;
6049 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006050 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6051 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006052 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006053 if (I->getOpcode() == Instruction::Shl) {
6054 // This is a value scaled by '1 << the shift amt'.
6055 Scale = 1U << CUI->getZExtValue();
6056 Offset = 0;
6057 return I->getOperand(0);
6058 } else if (I->getOpcode() == Instruction::Mul) {
6059 // This value is scaled by 'CUI'.
6060 Scale = CUI->getZExtValue();
6061 Offset = 0;
6062 return I->getOperand(0);
6063 } else if (I->getOpcode() == Instruction::Add) {
6064 // We have X+C. Check to see if we really have (X*C2)+C1,
6065 // where C1 is divisible by C2.
6066 unsigned SubScale;
6067 Value *SubVal =
6068 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6069 Offset += CUI->getZExtValue();
6070 if (SubScale > 1 && (Offset % SubScale == 0)) {
6071 Scale = SubScale;
6072 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006073 }
6074 }
6075 }
6076 }
6077 }
6078
6079 // Otherwise, we can't look past this.
6080 Scale = 1;
6081 Offset = 0;
6082 return Val;
6083}
6084
6085
Chris Lattner216be912005-10-24 06:03:58 +00006086/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6087/// try to eliminate the cast by moving the type information into the alloc.
6088Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6089 AllocationInst &AI) {
6090 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006091 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006092
Chris Lattnerac87beb2005-10-24 06:22:12 +00006093 // Remove any uses of AI that are dead.
6094 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006095
Chris Lattnerac87beb2005-10-24 06:22:12 +00006096 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6097 Instruction *User = cast<Instruction>(*UI++);
6098 if (isInstructionTriviallyDead(User)) {
6099 while (UI != E && *UI == User)
6100 ++UI; // If this instruction uses AI more than once, don't break UI.
6101
Chris Lattnerac87beb2005-10-24 06:22:12 +00006102 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006103 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006104 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006105 }
6106 }
6107
Chris Lattner216be912005-10-24 06:03:58 +00006108 // Get the type really allocated and the type casted to.
6109 const Type *AllocElTy = AI.getAllocatedType();
6110 const Type *CastElTy = PTy->getElementType();
6111 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006112
Chris Lattner945e4372007-02-14 05:52:17 +00006113 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6114 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006115 if (CastElTyAlign < AllocElTyAlign) return 0;
6116
Chris Lattner46705b22005-10-24 06:35:18 +00006117 // If the allocation has multiple uses, only promote it if we are strictly
6118 // increasing the alignment of the resultant allocation. If we keep it the
6119 // same, we open the door to infinite loops of various kinds.
6120 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6121
Chris Lattner216be912005-10-24 06:03:58 +00006122 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6123 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006124 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006125
Chris Lattner8270c332005-10-29 03:19:53 +00006126 // See if we can satisfy the modulus by pulling a scale out of the array
6127 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006128 unsigned ArraySizeScale;
6129 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00006130 Value *NumElements = // See if the array size is a decomposable linear expr.
6131 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6132
Chris Lattner8270c332005-10-29 03:19:53 +00006133 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6134 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006135 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6136 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006137
Chris Lattner8270c332005-10-29 03:19:53 +00006138 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6139 Value *Amt = 0;
6140 if (Scale == 1) {
6141 Amt = NumElements;
6142 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006143 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006144 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6145 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00006146 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006147 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006148 else if (Scale != 1) {
6149 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6150 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006151 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006152 }
6153
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006154 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6155 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattner8f663e82005-10-29 04:36:15 +00006156 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6157 Amt = InsertNewInstBefore(Tmp, AI);
6158 }
6159
Chris Lattner216be912005-10-24 06:03:58 +00006160 AllocationInst *New;
6161 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006162 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006163 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006164 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006165 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006166 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006167
6168 // If the allocation has multiple uses, insert a cast and change all things
6169 // that used it to use the new cast. This will also hack on CI, but it will
6170 // die soon.
6171 if (!AI.hasOneUse()) {
6172 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006173 // New is the allocation instruction, pointer typed. AI is the original
6174 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6175 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006176 InsertNewInstBefore(NewCast, AI);
6177 AI.replaceAllUsesWith(NewCast);
6178 }
Chris Lattner216be912005-10-24 06:03:58 +00006179 return ReplaceInstUsesWith(CI, New);
6180}
6181
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006182/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006183/// and return it as type Ty without inserting any new casts and without
6184/// changing the computed value. This is used by code that tries to decide
6185/// whether promoting or shrinking integer operations to wider or smaller types
6186/// will allow us to eliminate a truncate or extend.
6187///
6188/// This is a truncation operation if Ty is smaller than V->getType(), or an
6189/// extension operation if Ty is larger.
6190static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006191 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006192 // We can always evaluate constants in another type.
6193 if (isa<ConstantInt>(V))
6194 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006195
6196 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006197 if (!I) return false;
6198
6199 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006200
6201 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006202 case Instruction::Add:
6203 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006204 case Instruction::And:
6205 case Instruction::Or:
6206 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006207 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006208 // These operators can all arbitrarily be extended or truncated.
6209 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6210 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006211
Chris Lattner960acb02006-11-29 07:18:39 +00006212 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006213 if (!I->hasOneUse()) return false;
6214 // If we are truncating the result of this SHL, and if it's a shift of a
6215 // constant amount, we can always perform a SHL in a smaller type.
6216 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006217 uint32_t BitWidth = Ty->getBitWidth();
6218 if (BitWidth < OrigTy->getBitWidth() &&
6219 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006220 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6221 }
6222 break;
6223 case Instruction::LShr:
6224 if (!I->hasOneUse()) return false;
6225 // If this is a truncate of a logical shr, we can truncate it to a smaller
6226 // lshr iff we know that the bits we would otherwise be shifting in are
6227 // already zeros.
6228 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006229 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6230 uint32_t BitWidth = Ty->getBitWidth();
6231 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006232 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00006233 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6234 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner28d921d2007-04-14 23:32:02 +00006235 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006236 }
6237 }
Chris Lattner960acb02006-11-29 07:18:39 +00006238 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006239 case Instruction::Trunc:
6240 case Instruction::ZExt:
6241 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006242 // If this is a cast from the destination type, we can trivially eliminate
6243 // it, and this will remove a cast overall.
6244 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006245 // If the first operand is itself a cast, and is eliminable, do not count
6246 // this as an eliminable cast. We would prefer to eliminate those two
6247 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006248 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006249 return true;
6250
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006251 ++NumCastsRemoved;
6252 return true;
6253 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006254 break;
6255 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006256 // TODO: Can handle more cases here.
6257 break;
6258 }
6259
6260 return false;
6261}
6262
6263/// EvaluateInDifferentType - Given an expression that
6264/// CanEvaluateInDifferentType returns true for, actually insert the code to
6265/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006266Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006267 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006268 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006269 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006270
6271 // Otherwise, it must be an instruction.
6272 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006273 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006274 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006275 case Instruction::Add:
6276 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006277 case Instruction::And:
6278 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006279 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006280 case Instruction::AShr:
6281 case Instruction::LShr:
6282 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006283 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006284 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6285 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6286 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006287 break;
6288 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006289 case Instruction::Trunc:
6290 case Instruction::ZExt:
6291 case Instruction::SExt:
6292 case Instruction::BitCast:
6293 // If the source type of the cast is the type we're trying for then we can
6294 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006295 if (I->getOperand(0)->getType() == Ty)
6296 return I->getOperand(0);
6297
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006298 // Some other kind of cast, which shouldn't happen, so just ..
6299 // FALL THROUGH
6300 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006301 // TODO: Can handle more cases here.
6302 assert(0 && "Unreachable!");
6303 break;
6304 }
6305
6306 return InsertNewInstBefore(Res, *I);
6307}
6308
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006309/// @brief Implement the transforms common to all CastInst visitors.
6310Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006311 Value *Src = CI.getOperand(0);
6312
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006313 // Casting undef to anything results in undef so might as just replace it and
6314 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006315 if (isa<UndefValue>(Src)) // cast undef -> undef
6316 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6317
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006318 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6319 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006320 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006321 if (Instruction::CastOps opc =
6322 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6323 // The first cast (CSrc) is eliminable so we need to fix up or replace
6324 // the second cast (CI). CSrc will then have a good chance of being dead.
6325 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006326 }
6327 }
Chris Lattner03841652004-05-25 04:29:21 +00006328
Chris Lattnerd0d51602003-06-21 23:12:02 +00006329 // If casting the result of a getelementptr instruction with no offset, turn
6330 // this into a cast of the original pointer!
6331 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006332 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006333 bool AllZeroOperands = true;
6334 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6335 if (!isa<Constant>(GEP->getOperand(i)) ||
6336 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6337 AllZeroOperands = false;
6338 break;
6339 }
6340 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006341 // Changing the cast operand is usually not a good idea but it is safe
6342 // here because the pointer operand is being replaced with another
6343 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006344 CI.setOperand(0, GEP->getOperand(0));
6345 return &CI;
6346 }
6347 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006348
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006349 // If we are casting a malloc or alloca to a pointer to a type of the same
6350 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006351 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006352 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6353 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006354
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006355 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006356 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6357 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6358 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006359
6360 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006361 if (isa<PHINode>(Src))
6362 if (Instruction *NV = FoldOpIntoPhi(CI))
6363 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006364
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006365 return 0;
6366}
6367
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006368/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6369/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006370/// cases.
6371/// @brief Implement the transforms common to CastInst with integer operands
6372Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6373 if (Instruction *Result = commonCastTransforms(CI))
6374 return Result;
6375
6376 Value *Src = CI.getOperand(0);
6377 const Type *SrcTy = Src->getType();
6378 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006379 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6380 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006382 // See if we can simplify any instructions used by the LHS whose sole
6383 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006384 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6385 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006386 KnownZero, KnownOne))
6387 return &CI;
6388
6389 // If the source isn't an instruction or has more than one use then we
6390 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006391 Instruction *SrcI = dyn_cast<Instruction>(Src);
6392 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006393 return 0;
6394
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006395 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006396 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006397 if (!isa<BitCastInst>(CI) &&
6398 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6399 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006400 // If this cast is a truncate, evaluting in a different type always
6401 // eliminates the cast, so it is always a win. If this is a noop-cast
6402 // this just removes a noop cast which isn't pointful, but simplifies
6403 // the code. If this is a zero-extension, we need to do an AND to
6404 // maintain the clear top-part of the computation, so we require that
6405 // the input have eliminated at least one cast. If this is a sign
6406 // extension, we insert two new casts (to do the extension) so we
6407 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006408 bool DoXForm;
6409 switch (CI.getOpcode()) {
6410 default:
6411 // All the others use floating point so we shouldn't actually
6412 // get here because of the check above.
6413 assert(0 && "Unknown cast type");
6414 case Instruction::Trunc:
6415 DoXForm = true;
6416 break;
6417 case Instruction::ZExt:
6418 DoXForm = NumCastsRemoved >= 1;
6419 break;
6420 case Instruction::SExt:
6421 DoXForm = NumCastsRemoved >= 2;
6422 break;
6423 case Instruction::BitCast:
6424 DoXForm = false;
6425 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006426 }
6427
6428 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006429 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6430 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006431 assert(Res->getType() == DestTy);
6432 switch (CI.getOpcode()) {
6433 default: assert(0 && "Unknown cast type!");
6434 case Instruction::Trunc:
6435 case Instruction::BitCast:
6436 // Just replace this cast with the result.
6437 return ReplaceInstUsesWith(CI, Res);
6438 case Instruction::ZExt: {
6439 // We need to emit an AND to clear the high bits.
6440 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00006441 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6442 SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006443 return BinaryOperator::createAnd(Res, C);
6444 }
6445 case Instruction::SExt:
6446 // We need to emit a cast to truncate, then a cast to sext.
6447 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006448 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6449 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006450 }
6451 }
6452 }
6453
6454 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6455 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6456
6457 switch (SrcI->getOpcode()) {
6458 case Instruction::Add:
6459 case Instruction::Mul:
6460 case Instruction::And:
6461 case Instruction::Or:
6462 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00006463 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006464 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6465 // Don't insert two casts if they cannot be eliminated. We allow
6466 // two casts to be inserted if the sizes are the same. This could
6467 // only be converting signedness, which is a noop.
6468 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006469 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6470 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006471 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006472 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6473 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6474 return BinaryOperator::create(
6475 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006476 }
6477 }
6478
6479 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6480 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6481 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006482 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006483 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006484 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006485 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6486 }
6487 break;
6488 case Instruction::SDiv:
6489 case Instruction::UDiv:
6490 case Instruction::SRem:
6491 case Instruction::URem:
6492 // If we are just changing the sign, rewrite.
6493 if (DestBitSize == SrcBitSize) {
6494 // Don't insert two casts if they cannot be eliminated. We allow
6495 // two casts to be inserted if the sizes are the same. This could
6496 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006497 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6498 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006499 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6500 Op0, DestTy, SrcI);
6501 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6502 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006503 return BinaryOperator::create(
6504 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6505 }
6506 }
6507 break;
6508
6509 case Instruction::Shl:
6510 // Allow changing the sign of the source operand. Do not allow
6511 // changing the size of the shift, UNLESS the shift amount is a
6512 // constant. We must not change variable sized shifts to a smaller
6513 // size, because it is undefined to shift more bits out than exist
6514 // in the value.
6515 if (DestBitSize == SrcBitSize ||
6516 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006517 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6518 Instruction::BitCast : Instruction::Trunc);
6519 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006520 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006521 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006522 }
6523 break;
6524 case Instruction::AShr:
6525 // If this is a signed shr, and if all bits shifted in are about to be
6526 // truncated off, turn it into an unsigned shr to allow greater
6527 // simplifications.
6528 if (DestBitSize < SrcBitSize &&
6529 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006530 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006531 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6532 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006533 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006534 }
6535 }
6536 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006537 }
6538 return 0;
6539}
6540
Chris Lattner74ff60f2007-04-11 06:57:46 +00006541Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006542 if (Instruction *Result = commonIntCastTransforms(CI))
6543 return Result;
6544
6545 Value *Src = CI.getOperand(0);
6546 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006547 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6548 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006549
6550 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6551 switch (SrcI->getOpcode()) {
6552 default: break;
6553 case Instruction::LShr:
6554 // We can shrink lshr to something smaller if we know the bits shifted in
6555 // are already zeros.
6556 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006557 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00006558
6559 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006560 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006561 Value* SrcIOp0 = SrcI->getOperand(0);
6562 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006563 if (ShAmt >= DestBitWidth) // All zeros.
6564 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6565
6566 // Okay, we can shrink this. Truncate the input, then return a new
6567 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006568 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6569 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6570 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006571 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006572 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006573 } else { // This is a variable shr.
6574
6575 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6576 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6577 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006578 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006579 Value *One = ConstantInt::get(SrcI->getType(), 1);
6580
Reid Spencer2341c222007-02-02 02:16:23 +00006581 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006582 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006583 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006584 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6585 SrcI->getOperand(0),
6586 "tmp"), CI);
6587 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006588 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006589 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006590 }
6591 break;
6592 }
6593 }
6594
6595 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006596}
6597
Chris Lattner74ff60f2007-04-11 06:57:46 +00006598Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006599 // If one of the common conversion will work ..
6600 if (Instruction *Result = commonIntCastTransforms(CI))
6601 return Result;
6602
6603 Value *Src = CI.getOperand(0);
6604
6605 // If this is a cast of a cast
6606 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006607 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6608 // types and if the sizes are just right we can convert this into a logical
6609 // 'and' which will be much cheaper than the pair of casts.
6610 if (isa<TruncInst>(CSrc)) {
6611 // Get the sizes of the types involved
6612 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00006613 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6614 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6615 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006616 // If we're actually extending zero bits and the trunc is a no-op
6617 if (MidSize < DstSize && SrcSize == DstSize) {
6618 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006619 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006620 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006621 Instruction *And =
6622 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6623 // Unfortunately, if the type changed, we need to cast it back.
6624 if (And->getType() != CI.getType()) {
6625 And->setName(CSrc->getName()+".mask");
6626 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006627 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006628 }
6629 return And;
6630 }
6631 }
6632 }
6633
Chris Lattner7ddbff02007-04-11 05:45:39 +00006634 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6635 // If we are just checking for a icmp eq of a single bit and zext'ing it
6636 // to an integer, then shift the bit to the appropriate place and then
6637 // cast to integer to avoid the comparison.
6638 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00006639 const APInt &Op1CV = Op1C->getValue();
Chris Lattnerd0f79422007-04-11 06:53:04 +00006640
6641 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6642 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6643 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6644 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6645 Value *In = ICI->getOperand(0);
6646 Value *Sh = ConstantInt::get(In->getType(),
6647 In->getType()->getPrimitiveSizeInBits()-1);
6648 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattner28d921d2007-04-14 23:32:02 +00006649 In->getName()+".lobit"),
Chris Lattnerd0f79422007-04-11 06:53:04 +00006650 CI);
6651 if (In->getType() != CI.getType())
6652 In = CastInst::createIntegerCast(In, CI.getType(),
6653 false/*ZExt*/, "tmp", &CI);
6654
6655 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6656 Constant *One = ConstantInt::get(In->getType(), 1);
6657 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattner28d921d2007-04-14 23:32:02 +00006658 In->getName()+".not"),
Chris Lattnerd0f79422007-04-11 06:53:04 +00006659 CI);
6660 }
6661
6662 return ReplaceInstUsesWith(CI, In);
6663 }
6664
6665
6666
Chris Lattner20f23722007-04-11 06:12:58 +00006667 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6668 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6669 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6670 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6671 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6672 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6673 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6674 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner7ddbff02007-04-11 05:45:39 +00006675 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6676 // This only works for EQ and NE
6677 ICI->isEquality()) {
6678 // If Op1C some other power of two, convert:
6679 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6680 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6681 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6682 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6683
6684 APInt KnownZeroMask(~KnownZero);
6685 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6686 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6687 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6688 // (X&4) == 2 --> false
6689 // (X&4) != 2 --> true
6690 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6691 Res = ConstantExpr::getZExt(Res, CI.getType());
6692 return ReplaceInstUsesWith(CI, Res);
6693 }
6694
6695 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6696 Value *In = ICI->getOperand(0);
6697 if (ShiftAmt) {
6698 // Perform a logical shr by shiftamt.
6699 // Insert the shift to put the result in the low bit.
6700 In = InsertNewInstBefore(
6701 BinaryOperator::createLShr(In,
6702 ConstantInt::get(In->getType(), ShiftAmt),
6703 In->getName()+".lobit"), CI);
6704 }
6705
6706 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6707 Constant *One = ConstantInt::get(In->getType(), 1);
6708 In = BinaryOperator::createXor(In, One, "tmp");
6709 InsertNewInstBefore(cast<Instruction>(In), CI);
6710 }
6711
6712 if (CI.getType() == In->getType())
6713 return ReplaceInstUsesWith(CI, In);
6714 else
6715 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6716 }
6717 }
6718 }
6719 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006720 return 0;
6721}
6722
Chris Lattner74ff60f2007-04-11 06:57:46 +00006723Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00006724 if (Instruction *I = commonIntCastTransforms(CI))
6725 return I;
6726
Chris Lattner74ff60f2007-04-11 06:57:46 +00006727 Value *Src = CI.getOperand(0);
6728
6729 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6730 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6731 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6732 // If we are just checking for a icmp eq of a single bit and zext'ing it
6733 // to an integer, then shift the bit to the appropriate place and then
6734 // cast to integer to avoid the comparison.
6735 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6736 const APInt &Op1CV = Op1C->getValue();
6737
6738 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6739 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6740 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6741 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6742 Value *In = ICI->getOperand(0);
6743 Value *Sh = ConstantInt::get(In->getType(),
6744 In->getType()->getPrimitiveSizeInBits()-1);
6745 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattner28d921d2007-04-14 23:32:02 +00006746 In->getName()+".lobit"),
Chris Lattner74ff60f2007-04-11 06:57:46 +00006747 CI);
6748 if (In->getType() != CI.getType())
6749 In = CastInst::createIntegerCast(In, CI.getType(),
6750 true/*SExt*/, "tmp", &CI);
6751
6752 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6753 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6754 In->getName()+".not"), CI);
6755
6756 return ReplaceInstUsesWith(CI, In);
6757 }
6758 }
6759 }
6760
Chris Lattner20f23722007-04-11 06:12:58 +00006761 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006762}
6763
6764Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6765 return commonCastTransforms(CI);
6766}
6767
6768Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6769 return commonCastTransforms(CI);
6770}
6771
6772Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006773 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006774}
6775
6776Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006777 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006778}
6779
6780Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6781 return commonCastTransforms(CI);
6782}
6783
6784Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6785 return commonCastTransforms(CI);
6786}
6787
6788Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006789 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006790}
6791
6792Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6793 return commonCastTransforms(CI);
6794}
6795
6796Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6797
6798 // If the operands are integer typed then apply the integer transforms,
6799 // otherwise just apply the common ones.
6800 Value *Src = CI.getOperand(0);
6801 const Type *SrcTy = Src->getType();
6802 const Type *DestTy = CI.getType();
6803
Chris Lattner03c49532007-01-15 02:27:26 +00006804 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006805 if (Instruction *Result = commonIntCastTransforms(CI))
6806 return Result;
6807 } else {
6808 if (Instruction *Result = commonCastTransforms(CI))
6809 return Result;
6810 }
6811
6812
6813 // Get rid of casts from one type to the same type. These are useless and can
6814 // be replaced by the operand.
6815 if (DestTy == Src->getType())
6816 return ReplaceInstUsesWith(CI, Src);
6817
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006818 // If the source and destination are pointers, and this cast is equivalent to
6819 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6820 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006821 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6822 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6823 const Type *DstElTy = DstPTy->getElementType();
6824 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006825
Reid Spencerc635f472006-12-31 05:48:39 +00006826 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006827 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006828 while (SrcElTy != DstElTy &&
6829 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6830 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6831 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006832 ++NumZeros;
6833 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006834
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006835 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006836 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006837 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6838 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006839 }
6840 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006841 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006842
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006843 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6844 if (SVI->hasOneUse()) {
6845 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6846 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006847 if (isa<VectorType>(DestTy) &&
6848 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006849 SVI->getType()->getNumElements()) {
6850 CastInst *Tmp;
6851 // If either of the operands is a cast from CI.getType(), then
6852 // evaluating the shuffle in the casted destination's type will allow
6853 // us to eliminate at least one cast.
6854 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6855 Tmp->getOperand(0)->getType() == DestTy) ||
6856 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6857 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006858 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6859 SVI->getOperand(0), DestTy, &CI);
6860 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6861 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006862 // Return a new shuffle vector. Use the same element ID's, as we
6863 // know the vector types match #elts.
6864 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006865 }
6866 }
6867 }
6868 }
Chris Lattner260ab202002-04-18 17:39:14 +00006869 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006870}
6871
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006872/// GetSelectFoldableOperands - We want to turn code that looks like this:
6873/// %C = or %A, %B
6874/// %D = select %cond, %C, %A
6875/// into:
6876/// %C = select %cond, %B, 0
6877/// %D = or %A, %C
6878///
6879/// Assuming that the specified instruction is an operand to the select, return
6880/// a bitmask indicating which operands of this instruction are foldable if they
6881/// equal the other incoming value of the select.
6882///
6883static unsigned GetSelectFoldableOperands(Instruction *I) {
6884 switch (I->getOpcode()) {
6885 case Instruction::Add:
6886 case Instruction::Mul:
6887 case Instruction::And:
6888 case Instruction::Or:
6889 case Instruction::Xor:
6890 return 3; // Can fold through either operand.
6891 case Instruction::Sub: // Can only fold on the amount subtracted.
6892 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006893 case Instruction::LShr:
6894 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006895 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006896 default:
6897 return 0; // Cannot fold
6898 }
6899}
6900
6901/// GetSelectFoldableConstant - For the same transformation as the previous
6902/// function, return the identity constant that goes into the select.
6903static Constant *GetSelectFoldableConstant(Instruction *I) {
6904 switch (I->getOpcode()) {
6905 default: assert(0 && "This cannot happen!"); abort();
6906 case Instruction::Add:
6907 case Instruction::Sub:
6908 case Instruction::Or:
6909 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006910 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006911 case Instruction::LShr:
6912 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006913 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006914 case Instruction::And:
6915 return ConstantInt::getAllOnesValue(I->getType());
6916 case Instruction::Mul:
6917 return ConstantInt::get(I->getType(), 1);
6918 }
6919}
6920
Chris Lattner411336f2005-01-19 21:50:18 +00006921/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6922/// have the same opcode and only one use each. Try to simplify this.
6923Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6924 Instruction *FI) {
6925 if (TI->getNumOperands() == 1) {
6926 // If this is a non-volatile load or a cast from the same type,
6927 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006928 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006929 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6930 return 0;
6931 } else {
6932 return 0; // unknown unary op.
6933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006934
Chris Lattner411336f2005-01-19 21:50:18 +00006935 // Fold this by inserting a select from the input values.
6936 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6937 FI->getOperand(0), SI.getName()+".v");
6938 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006939 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6940 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006941 }
6942
Reid Spencer2341c222007-02-02 02:16:23 +00006943 // Only handle binary operators here.
6944 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006945 return 0;
6946
6947 // Figure out if the operations have any operands in common.
6948 Value *MatchOp, *OtherOpT, *OtherOpF;
6949 bool MatchIsOpZero;
6950 if (TI->getOperand(0) == FI->getOperand(0)) {
6951 MatchOp = TI->getOperand(0);
6952 OtherOpT = TI->getOperand(1);
6953 OtherOpF = FI->getOperand(1);
6954 MatchIsOpZero = true;
6955 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6956 MatchOp = TI->getOperand(1);
6957 OtherOpT = TI->getOperand(0);
6958 OtherOpF = FI->getOperand(0);
6959 MatchIsOpZero = false;
6960 } else if (!TI->isCommutative()) {
6961 return 0;
6962 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6963 MatchOp = TI->getOperand(0);
6964 OtherOpT = TI->getOperand(1);
6965 OtherOpF = FI->getOperand(0);
6966 MatchIsOpZero = true;
6967 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6968 MatchOp = TI->getOperand(1);
6969 OtherOpT = TI->getOperand(0);
6970 OtherOpF = FI->getOperand(1);
6971 MatchIsOpZero = true;
6972 } else {
6973 return 0;
6974 }
6975
6976 // If we reach here, they do have operations in common.
6977 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6978 OtherOpF, SI.getName()+".v");
6979 InsertNewInstBefore(NewSI, SI);
6980
6981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6982 if (MatchIsOpZero)
6983 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6984 else
6985 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006986 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006987 assert(0 && "Shouldn't get here");
6988 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006989}
6990
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006991Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006992 Value *CondVal = SI.getCondition();
6993 Value *TrueVal = SI.getTrueValue();
6994 Value *FalseVal = SI.getFalseValue();
6995
6996 // select true, X, Y -> X
6997 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006998 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006999 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00007000
7001 // select C, X, X -> X
7002 if (TrueVal == FalseVal)
7003 return ReplaceInstUsesWith(SI, TrueVal);
7004
Chris Lattner81a7a232004-10-16 18:11:37 +00007005 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7006 return ReplaceInstUsesWith(SI, FalseVal);
7007 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7008 return ReplaceInstUsesWith(SI, TrueVal);
7009 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7010 if (isa<Constant>(TrueVal))
7011 return ReplaceInstUsesWith(SI, TrueVal);
7012 else
7013 return ReplaceInstUsesWith(SI, FalseVal);
7014 }
7015
Reid Spencer542964f2007-01-11 18:21:29 +00007016 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007017 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007018 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007019 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007020 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007021 } else {
7022 // Change: A = select B, false, C --> A = and !B, C
7023 Value *NotCond =
7024 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7025 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007026 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007027 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007028 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007029 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007030 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007031 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007032 } else {
7033 // Change: A = select B, C, true --> A = or !B, C
7034 Value *NotCond =
7035 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7036 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007037 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007038 }
7039 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00007040 }
Chris Lattner1c631e82004-04-08 04:43:23 +00007041
Chris Lattner183b3362004-04-09 19:05:30 +00007042 // Selecting between two integer constants?
7043 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7044 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00007045 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00007046 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007047 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00007048 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00007049 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00007050 Value *NotCond =
7051 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00007052 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007053 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00007054 }
Chris Lattner20f23722007-04-11 06:12:58 +00007055
7056 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner35167c32004-06-09 07:59:58 +00007057
Reid Spencer266e42b2006-12-23 06:05:41 +00007058 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007059
Reid Spencer266e42b2006-12-23 06:05:41 +00007060 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00007061 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00007062 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00007063 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007064 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007065 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00007066 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00007067 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00007068 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7069 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7070 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00007071 InsertNewInstBefore(SRA, SI);
7072
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007073 // Finally, convert to the type of the select RHS. We figure out
7074 // if this requires a SExt, Trunc or BitCast based on the sizes.
7075 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng56cda952007-04-02 08:20:41 +00007076 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7077 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007078 if (SRASize < SISize)
7079 opc = Instruction::SExt;
7080 else if (SRASize > SISize)
7081 opc = Instruction::Trunc;
7082 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007083 }
7084 }
7085
7086
7087 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00007088 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007089 // non-constant value, eliminate this whole mess. This corresponds to
7090 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00007091 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007092 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007093 cast<Constant>(IC->getOperand(1))->isNullValue())
7094 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7095 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007096 isa<ConstantInt>(ICA->getOperand(1)) &&
7097 (ICA->getOperand(1) == TrueValC ||
7098 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007099 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7100 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007101 // know whether we have a icmp_ne or icmp_eq and whether the
7102 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00007103 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00007104 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007105 Value *V = ICA;
7106 if (ShouldNotVal)
7107 V = InsertNewInstBefore(BinaryOperator::create(
7108 Instruction::Xor, V, ICA->getOperand(1)), SI);
7109 return ReplaceInstUsesWith(SI, V);
7110 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007111 }
Chris Lattner533bc492004-03-30 19:37:13 +00007112 }
Chris Lattner623fba12004-04-10 22:21:27 +00007113
7114 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007115 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7116 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007117 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007118 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007119 return ReplaceInstUsesWith(SI, FalseVal);
7120 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007121 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007122 return ReplaceInstUsesWith(SI, TrueVal);
7123 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7124
Reid Spencer266e42b2006-12-23 06:05:41 +00007125 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007126 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007127 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007128 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007129 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007130 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7131 return ReplaceInstUsesWith(SI, TrueVal);
7132 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7133 }
7134 }
7135
7136 // See if we are selecting two values based on a comparison of the two values.
7137 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7138 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7139 // Transform (X == Y) ? X : Y -> Y
7140 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7141 return ReplaceInstUsesWith(SI, FalseVal);
7142 // Transform (X != Y) ? X : Y -> X
7143 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7144 return ReplaceInstUsesWith(SI, TrueVal);
7145 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7146
7147 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7148 // Transform (X == Y) ? Y : X -> X
7149 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7150 return ReplaceInstUsesWith(SI, FalseVal);
7151 // Transform (X != Y) ? Y : X -> Y
7152 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007153 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007154 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7155 }
7156 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007157
Chris Lattnera04c9042005-01-13 22:52:24 +00007158 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7159 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7160 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007161 Instruction *AddOp = 0, *SubOp = 0;
7162
Chris Lattner411336f2005-01-19 21:50:18 +00007163 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7164 if (TI->getOpcode() == FI->getOpcode())
7165 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7166 return IV;
7167
7168 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7169 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007170 if (TI->getOpcode() == Instruction::Sub &&
7171 FI->getOpcode() == Instruction::Add) {
7172 AddOp = FI; SubOp = TI;
7173 } else if (FI->getOpcode() == Instruction::Sub &&
7174 TI->getOpcode() == Instruction::Add) {
7175 AddOp = TI; SubOp = FI;
7176 }
7177
7178 if (AddOp) {
7179 Value *OtherAddOp = 0;
7180 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7181 OtherAddOp = AddOp->getOperand(1);
7182 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7183 OtherAddOp = AddOp->getOperand(0);
7184 }
7185
7186 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007187 // So at this point we know we have (Y -> OtherAddOp):
7188 // select C, (add X, Y), (sub X, Z)
7189 Value *NegVal; // Compute -Z
7190 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7191 NegVal = ConstantExpr::getNeg(C);
7192 } else {
7193 NegVal = InsertNewInstBefore(
7194 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007195 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007196
7197 Value *NewTrueOp = OtherAddOp;
7198 Value *NewFalseOp = NegVal;
7199 if (AddOp != TI)
7200 std::swap(NewTrueOp, NewFalseOp);
7201 Instruction *NewSel =
7202 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7203
7204 NewSel = InsertNewInstBefore(NewSel, SI);
7205 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007206 }
7207 }
7208 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007209
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007210 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007211 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007212 // See the comment above GetSelectFoldableOperands for a description of the
7213 // transformation we are doing here.
7214 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7215 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7216 !isa<Constant>(FalseVal))
7217 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7218 unsigned OpToFold = 0;
7219 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7220 OpToFold = 1;
7221 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7222 OpToFold = 2;
7223 }
7224
7225 if (OpToFold) {
7226 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007227 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007228 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007229 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007230 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007231 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7232 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007233 else {
7234 assert(0 && "Unknown instruction!!");
7235 }
7236 }
7237 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007238
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007239 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7240 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7241 !isa<Constant>(TrueVal))
7242 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7243 unsigned OpToFold = 0;
7244 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7245 OpToFold = 1;
7246 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7247 OpToFold = 2;
7248 }
7249
7250 if (OpToFold) {
7251 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007252 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007253 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007254 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007255 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7257 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007258 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007259 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007260 }
7261 }
7262 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007263
7264 if (BinaryOperator::isNot(CondVal)) {
7265 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7266 SI.setOperand(1, FalseVal);
7267 SI.setOperand(2, TrueVal);
7268 return &SI;
7269 }
7270
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007271 return 0;
7272}
7273
Chris Lattner82f2ef22006-03-06 20:18:44 +00007274/// GetKnownAlignment - If the specified pointer has an alignment that we can
7275/// determine, return it, otherwise return 0.
7276static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7277 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7278 unsigned Align = GV->getAlignment();
7279 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007280 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007281 return Align;
7282 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7283 unsigned Align = AI->getAlignment();
7284 if (Align == 0 && TD) {
7285 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007286 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007287 else if (isa<MallocInst>(AI)) {
7288 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007289 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007290 Align =
7291 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007292 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007293 Align =
7294 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007295 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007296 }
7297 }
7298 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007299 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007300 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007301 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007302 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007303 if (isa<PointerType>(CI->getOperand(0)->getType()))
7304 return GetKnownAlignment(CI->getOperand(0), TD);
7305 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007306 } else if (isa<GetElementPtrInst>(V) ||
7307 (isa<ConstantExpr>(V) &&
7308 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7309 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007310 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7311 if (BaseAlignment == 0) return 0;
7312
7313 // If all indexes are zero, it is just the alignment of the base pointer.
7314 bool AllZeroOperands = true;
7315 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7316 if (!isa<Constant>(GEPI->getOperand(i)) ||
7317 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7318 AllZeroOperands = false;
7319 break;
7320 }
7321 if (AllZeroOperands)
7322 return BaseAlignment;
7323
7324 // Otherwise, if the base alignment is >= the alignment we expect for the
7325 // base pointer type, then we know that the resultant pointer is aligned at
7326 // least as much as its type requires.
7327 if (!TD) return 0;
7328
7329 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007330 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007331 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007332 <= BaseAlignment) {
7333 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007334 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007335 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007336 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007337 return 0;
7338 }
7339 return 0;
7340}
7341
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007342
Chris Lattnerc66b2232006-01-13 20:11:04 +00007343/// visitCallInst - CallInst simplification. This mostly only handles folding
7344/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7345/// the heavy lifting.
7346///
Chris Lattner970c33a2003-06-19 17:00:31 +00007347Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007348 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7349 if (!II) return visitCallSite(&CI);
7350
Chris Lattner51ea1272004-02-28 05:22:00 +00007351 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7352 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007353 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007354 bool Changed = false;
7355
7356 // memmove/cpy/set of zero bytes is a noop.
7357 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7358 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7359
Chris Lattner00648e12004-10-12 04:52:52 +00007360 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007361 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007362 // Replace the instruction with just byte operations. We would
7363 // transform other cases to loads/stores, but we don't know if
7364 // alignment is sufficient.
7365 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007366 }
7367
Chris Lattner00648e12004-10-12 04:52:52 +00007368 // If we have a memmove and the source operation is a constant global,
7369 // then the source and dest pointers can't alias, so we can change this
7370 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007371 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007372 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7373 if (GVSrc->isConstant()) {
7374 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007375 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007376 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007377 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007378 Name = "llvm.memcpy.i32";
7379 else
7380 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007381 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007382 CI.getCalledFunction()->getFunctionType());
7383 CI.setOperand(0, MemCpy);
7384 Changed = true;
7385 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007386 }
Chris Lattner00648e12004-10-12 04:52:52 +00007387
Chris Lattner82f2ef22006-03-06 20:18:44 +00007388 // If we can determine a pointer alignment that is bigger than currently
7389 // set, update the alignment.
7390 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7391 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7392 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7393 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007394 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007395 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007396 Changed = true;
7397 }
7398 } else if (isa<MemSetInst>(MI)) {
7399 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007400 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007401 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007402 Changed = true;
7403 }
7404 }
7405
Chris Lattnerc66b2232006-01-13 20:11:04 +00007406 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007407 } else {
7408 switch (II->getIntrinsicID()) {
7409 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007410 case Intrinsic::ppc_altivec_lvx:
7411 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007412 case Intrinsic::x86_sse_loadu_ps:
7413 case Intrinsic::x86_sse2_loadu_pd:
7414 case Intrinsic::x86_sse2_loadu_dq:
7415 // Turn PPC lvx -> load if the pointer is known aligned.
7416 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007417 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007418 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007419 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007420 return new LoadInst(Ptr);
7421 }
7422 break;
7423 case Intrinsic::ppc_altivec_stvx:
7424 case Intrinsic::ppc_altivec_stvxl:
7425 // Turn stvx -> store if the pointer is known aligned.
7426 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007427 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007428 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7429 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007430 return new StoreInst(II->getOperand(1), Ptr);
7431 }
7432 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007433 case Intrinsic::x86_sse_storeu_ps:
7434 case Intrinsic::x86_sse2_storeu_pd:
7435 case Intrinsic::x86_sse2_storeu_dq:
7436 case Intrinsic::x86_sse2_storel_dq:
7437 // Turn X86 storeu -> store if the pointer is known aligned.
7438 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7439 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007440 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7441 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007442 return new StoreInst(II->getOperand(2), Ptr);
7443 }
7444 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007445
7446 case Intrinsic::x86_sse_cvttss2si: {
7447 // These intrinsics only demands the 0th element of its input vector. If
7448 // we can simplify the input based on that, do so now.
7449 uint64_t UndefElts;
7450 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7451 UndefElts)) {
7452 II->setOperand(1, V);
7453 return II;
7454 }
7455 break;
7456 }
7457
Chris Lattnere79d2492006-04-06 19:19:17 +00007458 case Intrinsic::ppc_altivec_vperm:
7459 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007460 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007461 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7462
7463 // Check that all of the elements are integer constants or undefs.
7464 bool AllEltsOk = true;
7465 for (unsigned i = 0; i != 16; ++i) {
7466 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7467 !isa<UndefValue>(Mask->getOperand(i))) {
7468 AllEltsOk = false;
7469 break;
7470 }
7471 }
7472
7473 if (AllEltsOk) {
7474 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007475 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7476 II->getOperand(1), Mask->getType(), CI);
7477 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7478 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007479 Value *Result = UndefValue::get(Op0->getType());
7480
7481 // Only extract each element once.
7482 Value *ExtractedElts[32];
7483 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7484
7485 for (unsigned i = 0; i != 16; ++i) {
7486 if (isa<UndefValue>(Mask->getOperand(i)))
7487 continue;
Chris Lattner28d921d2007-04-14 23:32:02 +00007488 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007489 Idx &= 31; // Match the hardware behavior.
7490
7491 if (ExtractedElts[Idx] == 0) {
7492 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007493 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007494 InsertNewInstBefore(Elt, CI);
7495 ExtractedElts[Idx] = Elt;
7496 }
7497
7498 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007499 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007500 InsertNewInstBefore(cast<Instruction>(Result), CI);
7501 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007502 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007503 }
7504 }
7505 break;
7506
Chris Lattner503221f2006-01-13 21:28:09 +00007507 case Intrinsic::stackrestore: {
7508 // If the save is right next to the restore, remove the restore. This can
7509 // happen when variable allocas are DCE'd.
7510 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7511 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7512 BasicBlock::iterator BI = SS;
7513 if (&*++BI == II)
7514 return EraseInstFromFunction(CI);
7515 }
7516 }
7517
7518 // If the stack restore is in a return/unwind block and if there are no
7519 // allocas or calls between the restore and the return, nuke the restore.
7520 TerminatorInst *TI = II->getParent()->getTerminator();
7521 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7522 BasicBlock::iterator BI = II;
7523 bool CannotRemove = false;
7524 for (++BI; &*BI != TI; ++BI) {
7525 if (isa<AllocaInst>(BI) ||
7526 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7527 CannotRemove = true;
7528 break;
7529 }
7530 }
7531 if (!CannotRemove)
7532 return EraseInstFromFunction(CI);
7533 }
7534 break;
7535 }
7536 }
Chris Lattner00648e12004-10-12 04:52:52 +00007537 }
7538
Chris Lattnerc66b2232006-01-13 20:11:04 +00007539 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007540}
7541
7542// InvokeInst simplification
7543//
7544Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007545 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007546}
7547
Chris Lattneraec3d942003-10-07 22:32:43 +00007548// visitCallSite - Improvements for call and invoke instructions.
7549//
7550Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007551 bool Changed = false;
7552
7553 // If the callee is a constexpr cast of a function, attempt to move the cast
7554 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007555 if (transformConstExprCastCall(CS)) return 0;
7556
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007557 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007558
Chris Lattner61d9d812005-05-13 07:09:09 +00007559 if (Function *CalleeF = dyn_cast<Function>(Callee))
7560 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7561 Instruction *OldCall = CS.getInstruction();
7562 // If the call and callee calling conventions don't match, this call must
7563 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007564 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007565 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007566 if (!OldCall->use_empty())
7567 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7568 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7569 return EraseInstFromFunction(*OldCall);
7570 return 0;
7571 }
7572
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007573 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7574 // This instruction is not reachable, just remove it. We insert a store to
7575 // undef so that we know that this code is not reachable, despite the fact
7576 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007577 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007578 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007579 CS.getInstruction());
7580
7581 if (!CS.getInstruction()->use_empty())
7582 CS.getInstruction()->
7583 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7584
7585 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7586 // Don't break the CFG, insert a dummy cond branch.
7587 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007588 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007589 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007590 return EraseInstFromFunction(*CS.getInstruction());
7591 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007592
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007593 const PointerType *PTy = cast<PointerType>(Callee->getType());
7594 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7595 if (FTy->isVarArg()) {
7596 // See if we can optimize any arguments passed through the varargs area of
7597 // the call.
7598 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7599 E = CS.arg_end(); I != E; ++I)
7600 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7601 // If this cast does not effect the value passed through the varargs
7602 // area, we can eliminate the use of the cast.
7603 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007604 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007605 *I = Op;
7606 Changed = true;
7607 }
7608 }
7609 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007610
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007611 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007612}
7613
Chris Lattner970c33a2003-06-19 17:00:31 +00007614// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7615// attempt to move the cast to the arguments of the call/invoke.
7616//
7617bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7618 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7619 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007620 if (CE->getOpcode() != Instruction::BitCast ||
7621 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007622 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007623 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007624 Instruction *Caller = CS.getInstruction();
7625
7626 // Okay, this is a cast from a function to a different type. Unless doing so
7627 // would cause a type conversion of one of our arguments, change this call to
7628 // be a direct call with arguments casted to the appropriate types.
7629 //
7630 const FunctionType *FT = Callee->getFunctionType();
7631 const Type *OldRetTy = Caller->getType();
7632
Chris Lattner1f7942f2004-01-14 06:06:08 +00007633 // Check to see if we are changing the return type...
7634 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007635 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007636 // Conversion is ok if changing from pointer to int of same size.
7637 !(isa<PointerType>(FT->getReturnType()) &&
7638 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007639 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007640
7641 // If the callsite is an invoke instruction, and the return value is used by
7642 // a PHI node in a successor, we cannot change the return type of the call
7643 // because there is no place to put the cast instruction (without breaking
7644 // the critical edge). Bail out in this case.
7645 if (!Caller->use_empty())
7646 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7647 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7648 UI != E; ++UI)
7649 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7650 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007651 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007652 return false;
7653 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007654
7655 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7656 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007657
Chris Lattner970c33a2003-06-19 17:00:31 +00007658 CallSite::arg_iterator AI = CS.arg_begin();
7659 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7660 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007661 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007662 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Dale Johannesen7c2001d2007-04-04 19:16:42 +00007663 //Some conversions are safe even if we do not have a body.
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007664 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007665 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007666 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007667 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007668 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7669 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007670 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007671 if (Callee->isDeclaration() && !isConvertible) return false;
Dale Johannesen7c2001d2007-04-04 19:16:42 +00007672
7673 // Most other conversions can be done if we have a body, even if these
7674 // lose information, e.g. int->short.
7675 // Some conversions cannot be done at all, e.g. float to pointer.
7676 // Logic here parallels CastInst::getCastOpcode (the design there
7677 // requires legality checks like this be done before calling it).
7678 if (ParamTy->isInteger()) {
7679 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7680 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7681 return false;
7682 }
7683 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7684 !isa<PointerType>(ActTy))
7685 return false;
7686 } else if (ParamTy->isFloatingPoint()) {
7687 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7688 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7689 return false;
7690 }
7691 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7692 return false;
7693 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7694 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7695 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7696 return false;
7697 }
7698 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7699 return false;
7700 } else if (isa<PointerType>(ParamTy)) {
7701 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7702 return false;
7703 } else {
7704 return false;
7705 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007706 }
7707
7708 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007709 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007710 return false; // Do not delete arguments unless we have a function body...
7711
7712 // Okay, we decided that this is a safe thing to do: go ahead and start
7713 // inserting cast instructions as necessary...
7714 std::vector<Value*> Args;
7715 Args.reserve(NumActualArgs);
7716
7717 AI = CS.arg_begin();
7718 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7719 const Type *ParamTy = FT->getParamType(i);
7720 if ((*AI)->getType() == ParamTy) {
7721 Args.push_back(*AI);
7722 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007723 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007724 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007725 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007726 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007727 }
7728 }
7729
7730 // If the function takes more arguments than the call was taking, add them
7731 // now...
7732 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7733 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7734
7735 // If we are removing arguments to the function, emit an obnoxious warning...
7736 if (FT->getNumParams() < NumActualArgs)
7737 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007738 cerr << "WARNING: While resolving call to function '"
7739 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007740 } else {
7741 // Add all of the arguments in their promoted form to the arg list...
7742 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7743 const Type *PTy = getPromotedType((*AI)->getType());
7744 if (PTy != (*AI)->getType()) {
7745 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007746 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7747 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007748 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007749 InsertNewInstBefore(Cast, *Caller);
7750 Args.push_back(Cast);
7751 } else {
7752 Args.push_back(*AI);
7753 }
7754 }
7755 }
7756
7757 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007758 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007759
7760 Instruction *NC;
7761 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007762 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007763 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007764 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007765 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007766 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007767 if (cast<CallInst>(Caller)->isTailCall())
7768 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007769 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007770 }
7771
Chris Lattner6e0123b2007-02-11 01:23:03 +00007772 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007773 Value *NV = NC;
7774 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7775 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007776 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007777 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7778 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007779 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007780
7781 // If this is an invoke instruction, we should insert it after the first
7782 // non-phi, instruction in the normal successor block.
7783 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7784 BasicBlock::iterator I = II->getNormalDest()->begin();
7785 while (isa<PHINode>(I)) ++I;
7786 InsertNewInstBefore(NC, *I);
7787 } else {
7788 // Otherwise, it's a call, just insert cast right after the call instr
7789 InsertNewInstBefore(NC, *Caller);
7790 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007791 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007792 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007793 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007794 }
7795 }
7796
7797 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7798 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007799 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007800 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007801 return true;
7802}
7803
Chris Lattnercadac0c2006-11-01 04:51:18 +00007804/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7805/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7806/// and a single binop.
7807Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7808 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007809 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7810 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007811 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007812 Value *LHSVal = FirstInst->getOperand(0);
7813 Value *RHSVal = FirstInst->getOperand(1);
7814
7815 const Type *LHSType = LHSVal->getType();
7816 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007817
7818 // Scan to see if all operands are the same opcode, all have one use, and all
7819 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007820 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007821 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007822 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007823 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007824 // types or GEP's with different index types.
7825 I->getOperand(0)->getType() != LHSType ||
7826 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007827 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007828
7829 // If they are CmpInst instructions, check their predicates
7830 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7831 if (cast<CmpInst>(I)->getPredicate() !=
7832 cast<CmpInst>(FirstInst)->getPredicate())
7833 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007834
7835 // Keep track of which operand needs a phi node.
7836 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7837 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007838 }
7839
Chris Lattner4f218d52006-11-08 19:42:28 +00007840 // Otherwise, this is safe to transform, determine if it is profitable.
7841
7842 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7843 // Indexes are often folded into load/store instructions, so we don't want to
7844 // hide them behind a phi.
7845 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7846 return 0;
7847
Chris Lattnercadac0c2006-11-01 04:51:18 +00007848 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007849 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007850 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007851 if (LHSVal == 0) {
7852 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7853 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7854 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007855 InsertNewInstBefore(NewLHS, PN);
7856 LHSVal = NewLHS;
7857 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007858
7859 if (RHSVal == 0) {
7860 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7861 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7862 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007863 InsertNewInstBefore(NewRHS, PN);
7864 RHSVal = NewRHS;
7865 }
7866
Chris Lattnercd62f112006-11-08 19:29:23 +00007867 // Add all operands to the new PHIs.
7868 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7869 if (NewLHS) {
7870 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7871 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7872 }
7873 if (NewRHS) {
7874 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7875 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7876 }
7877 }
7878
Chris Lattnercadac0c2006-11-01 04:51:18 +00007879 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007880 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007881 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7882 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7883 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007884 else {
7885 assert(isa<GetElementPtrInst>(FirstInst));
7886 return new GetElementPtrInst(LHSVal, RHSVal);
7887 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007888}
7889
Chris Lattner14f82c72006-11-01 07:13:54 +00007890/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7891/// of the block that defines it. This means that it must be obvious the value
7892/// of the load is not changed from the point of the load to the end of the
7893/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007894///
7895/// Finally, it is safe, but not profitable, to sink a load targetting a
7896/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7897/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007898static bool isSafeToSinkLoad(LoadInst *L) {
7899 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7900
7901 for (++BBI; BBI != E; ++BBI)
7902 if (BBI->mayWriteToMemory())
7903 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007904
7905 // Check for non-address taken alloca. If not address-taken already, it isn't
7906 // profitable to do this xform.
7907 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7908 bool isAddressTaken = false;
7909 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7910 UI != E; ++UI) {
7911 if (isa<LoadInst>(UI)) continue;
7912 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7913 // If storing TO the alloca, then the address isn't taken.
7914 if (SI->getOperand(1) == AI) continue;
7915 }
7916 isAddressTaken = true;
7917 break;
7918 }
7919
7920 if (!isAddressTaken)
7921 return false;
7922 }
7923
Chris Lattner14f82c72006-11-01 07:13:54 +00007924 return true;
7925}
7926
Chris Lattner970c33a2003-06-19 17:00:31 +00007927
Chris Lattner7515cab2004-11-14 19:13:23 +00007928// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7929// operator and they all are only used by the PHI, PHI together their
7930// inputs, and do the operation once, to the result of the PHI.
7931Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7932 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7933
7934 // Scan the instruction, looking for input operations that can be folded away.
7935 // If all input operands to the phi are the same instruction (e.g. a cast from
7936 // the same type or "+42") we can pull the operation through the PHI, reducing
7937 // code size and simplifying code.
7938 Constant *ConstantOp = 0;
7939 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007940 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007941 if (isa<CastInst>(FirstInst)) {
7942 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007943 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007944 // Can fold binop, compare or shift here if the RHS is a constant,
7945 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007946 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007947 if (ConstantOp == 0)
7948 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007949 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7950 isVolatile = LI->isVolatile();
7951 // We can't sink the load if the loaded value could be modified between the
7952 // load and the PHI.
7953 if (LI->getParent() != PN.getIncomingBlock(0) ||
7954 !isSafeToSinkLoad(LI))
7955 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007956 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007957 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007958 return FoldPHIArgBinOpIntoPHI(PN);
7959 // Can't handle general GEPs yet.
7960 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007961 } else {
7962 return 0; // Cannot fold this operation.
7963 }
7964
7965 // Check to see if all arguments are the same operation.
7966 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7967 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7968 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007969 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007970 return 0;
7971 if (CastSrcTy) {
7972 if (I->getOperand(0)->getType() != CastSrcTy)
7973 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007974 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007975 // We can't sink the load if the loaded value could be modified between
7976 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007977 if (LI->isVolatile() != isVolatile ||
7978 LI->getParent() != PN.getIncomingBlock(i) ||
7979 !isSafeToSinkLoad(LI))
7980 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007981 } else if (I->getOperand(1) != ConstantOp) {
7982 return 0;
7983 }
7984 }
7985
7986 // Okay, they are all the same operation. Create a new PHI node of the
7987 // correct type, and PHI together all of the LHS's of the instructions.
7988 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7989 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007990 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007991
7992 Value *InVal = FirstInst->getOperand(0);
7993 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007994
7995 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007996 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7997 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7998 if (NewInVal != InVal)
7999 InVal = 0;
8000 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8001 }
8002
8003 Value *PhiVal;
8004 if (InVal) {
8005 // The new PHI unions all of the same values together. This is really
8006 // common, so we handle it intelligently here for compile-time speed.
8007 PhiVal = InVal;
8008 delete NewPN;
8009 } else {
8010 InsertNewInstBefore(NewPN, PN);
8011 PhiVal = NewPN;
8012 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008013
Chris Lattner7515cab2004-11-14 19:13:23 +00008014 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008015 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8016 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00008017 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00008018 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00008019 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00008020 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00008021 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8022 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8023 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00008024 else
Reid Spencer2341c222007-02-02 02:16:23 +00008025 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00008026 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008027}
Chris Lattner48a44f72002-05-02 17:06:02 +00008028
Chris Lattner71536432005-01-17 05:10:15 +00008029/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8030/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00008031static bool DeadPHICycle(PHINode *PN,
8032 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00008033 if (PN->use_empty()) return true;
8034 if (!PN->hasOneUse()) return false;
8035
8036 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00008037 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00008038 return true;
8039
8040 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8041 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008042
Chris Lattner71536432005-01-17 05:10:15 +00008043 return false;
8044}
8045
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008046// PHINode simplification
8047//
Chris Lattner113f4f42002-06-25 16:13:24 +00008048Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00008049 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00008050 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00008051
Owen Andersonae8aa642006-07-10 22:03:18 +00008052 if (Value *V = PN.hasConstantValue())
8053 return ReplaceInstUsesWith(PN, V);
8054
Owen Andersonae8aa642006-07-10 22:03:18 +00008055 // If all PHI operands are the same operation, pull them through the PHI,
8056 // reducing code size.
8057 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8058 PN.getIncomingValue(0)->hasOneUse())
8059 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8060 return Result;
8061
8062 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8063 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8064 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008065 if (PN.hasOneUse()) {
8066 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8067 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00008068 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00008069 PotentiallyDeadPHIs.insert(&PN);
8070 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8071 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8072 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008073
8074 // If this phi has a single use, and if that use just computes a value for
8075 // the next iteration of a loop, delete the phi. This occurs with unused
8076 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8077 // common case here is good because the only other things that catch this
8078 // are induction variable analysis (sometimes) and ADCE, which is only run
8079 // late.
8080 if (PHIUser->hasOneUse() &&
8081 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8082 PHIUser->use_back() == &PN) {
8083 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8084 }
8085 }
Owen Andersonae8aa642006-07-10 22:03:18 +00008086
Chris Lattner91daeb52003-12-19 05:58:40 +00008087 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008088}
8089
Reid Spencer13bc5d72006-12-12 09:18:51 +00008090static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8091 Instruction *InsertPoint,
8092 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00008093 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8094 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008095 // We must cast correctly to the pointer type. Ensure that we
8096 // sign extend the integer value if it is smaller as this is
8097 // used for address computation.
8098 Instruction::CastOps opcode =
8099 (VTySize < PtrSize ? Instruction::SExt :
8100 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8101 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00008102}
8103
Chris Lattner48a44f72002-05-02 17:06:02 +00008104
Chris Lattner113f4f42002-06-25 16:13:24 +00008105Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008106 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00008107 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00008108 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008109 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00008110 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008111
Chris Lattner81a7a232004-10-16 18:11:37 +00008112 if (isa<UndefValue>(GEP.getOperand(0)))
8113 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8114
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008115 bool HasZeroPointerIndex = false;
8116 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8117 HasZeroPointerIndex = C->isNullValue();
8118
8119 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008120 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008121
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008122 // Keep track of whether all indices are zero constants integers.
8123 bool AllZeroIndices = true;
8124
Chris Lattner69193f92004-04-05 01:30:19 +00008125 // Eliminate unneeded casts for indices.
8126 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008127
Chris Lattner2b2412d2004-04-07 18:38:20 +00008128 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008129 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8130 // Track whether this GEP has all zero indices, if so, it doesn't move the
8131 // input pointer, it just changes its type.
8132 if (AllZeroIndices) {
8133 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
8134 AllZeroIndices = CI->isNullValue();
8135 else
8136 AllZeroIndices = false;
8137 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008138 if (isa<SequentialType>(*GTI)) {
8139 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008140 if (CI->getOpcode() == Instruction::ZExt ||
8141 CI->getOpcode() == Instruction::SExt) {
8142 const Type *SrcTy = CI->getOperand(0)->getType();
8143 // We can eliminate a cast from i32 to i64 iff the target
8144 // is a 32-bit pointer target.
8145 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8146 MadeChange = true;
8147 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008148 }
8149 }
8150 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008151 // If we are using a wider index than needed for this platform, shrink it
8152 // to what we need. If the incoming value needs a cast instruction,
8153 // insert it. This explicit cast can make subsequent optimizations more
8154 // obvious.
8155 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008156 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008157 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008158 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008159 MadeChange = true;
8160 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008161 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8162 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008163 GEP.setOperand(i, Op);
8164 MadeChange = true;
8165 }
Chris Lattner69193f92004-04-05 01:30:19 +00008166 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008167 }
Chris Lattner69193f92004-04-05 01:30:19 +00008168 if (MadeChange) return &GEP;
8169
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008170 // If this GEP instruction doesn't move the pointer, and if the input operand
8171 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8172 // real input to the dest type.
8173 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
8174 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8175 GEP.getType());
8176
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008177 // Combine Indices - If the source pointer to this getelementptr instruction
8178 // is a getelementptr instruction, combine the indices of the two
8179 // getelementptr instructions into a single instruction.
8180 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008181 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008182 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008183 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008184
8185 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008186 // Note that if our source is a gep chain itself that we wait for that
8187 // chain to be resolved before we perform this transformation. This
8188 // avoids us creating a TON of code in some cases.
8189 //
8190 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8191 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8192 return 0; // Wait until our source is folded to completion.
8193
Chris Lattneraf6094f2007-02-15 22:48:32 +00008194 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008195
8196 // Find out whether the last index in the source GEP is a sequential idx.
8197 bool EndsWithSequential = false;
8198 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8199 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008200 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008201
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008202 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008203 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008204 // Replace: gep (gep %P, long B), long A, ...
8205 // With: T = long A+B; gep %P, T, ...
8206 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008207 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008208 if (SO1 == Constant::getNullValue(SO1->getType())) {
8209 Sum = GO1;
8210 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8211 Sum = SO1;
8212 } else {
8213 // If they aren't the same type, convert both to an integer of the
8214 // target's pointer size.
8215 if (SO1->getType() != GO1->getType()) {
8216 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008217 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008218 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008219 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008220 } else {
8221 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008222 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008223 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008224 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008225
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008226 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008227 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008228 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008229 } else {
8230 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008231 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8232 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008233 }
8234 }
8235 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008236 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8237 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8238 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008239 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8240 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008241 }
Chris Lattner69193f92004-04-05 01:30:19 +00008242 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008243
8244 // Recycle the GEP we already have if possible.
8245 if (SrcGEPOperands.size() == 2) {
8246 GEP.setOperand(0, SrcGEPOperands[0]);
8247 GEP.setOperand(1, Sum);
8248 return &GEP;
8249 } else {
8250 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8251 SrcGEPOperands.end()-1);
8252 Indices.push_back(Sum);
8253 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8254 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008255 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008256 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008257 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008258 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008259 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8260 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008261 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8262 }
8263
8264 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008265 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8266 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008267
Chris Lattner5f667a62004-05-07 22:09:22 +00008268 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008269 // GEP of global variable. If all of the indices for this GEP are
8270 // constants, we can promote this to a constexpr instead of an instruction.
8271
8272 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008273 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008274 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8275 for (; I != E && isa<Constant>(*I); ++I)
8276 Indices.push_back(cast<Constant>(*I));
8277
8278 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008279 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8280 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008281
8282 // Replace all uses of the GEP with the new constexpr...
8283 return ReplaceInstUsesWith(GEP, CE);
8284 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008285 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008286 if (!isa<PointerType>(X->getType())) {
8287 // Not interesting. Source pointer must be a cast from pointer.
8288 } else if (HasZeroPointerIndex) {
8289 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8290 // into : GEP [10 x ubyte]* X, long 0, ...
8291 //
8292 // This occurs when the program declares an array extern like "int X[];"
8293 //
8294 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8295 const PointerType *XTy = cast<PointerType>(X->getType());
8296 if (const ArrayType *XATy =
8297 dyn_cast<ArrayType>(XTy->getElementType()))
8298 if (const ArrayType *CATy =
8299 dyn_cast<ArrayType>(CPTy->getElementType()))
8300 if (CATy->getElementType() == XATy->getElementType()) {
8301 // At this point, we know that the cast source type is a pointer
8302 // to an array of the same type as the destination pointer
8303 // array. Because the array type is never stepped over (there
8304 // is a leading zero) we can fold the cast into this GEP.
8305 GEP.setOperand(0, X);
8306 return &GEP;
8307 }
8308 } else if (GEP.getNumOperands() == 2) {
8309 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008310 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8311 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008312 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8313 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8314 if (isa<ArrayType>(SrcElTy) &&
8315 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8316 TD->getTypeSize(ResElTy)) {
8317 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008318 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008319 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008320 // V and GEP are both pointer types --> BitCast
8321 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008322 }
Chris Lattner2a893292005-09-13 18:36:04 +00008323
8324 // Transform things like:
8325 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8326 // (where tmp = 8*tmp2) into:
8327 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8328
8329 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008330 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008331 uint64_t ArrayEltSize =
8332 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8333
8334 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8335 // allow either a mul, shift, or constant here.
8336 Value *NewIdx = 0;
8337 ConstantInt *Scale = 0;
8338 if (ArrayEltSize == 1) {
8339 NewIdx = GEP.getOperand(1);
8340 Scale = ConstantInt::get(NewIdx->getType(), 1);
8341 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008342 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008343 Scale = CI;
8344 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8345 if (Inst->getOpcode() == Instruction::Shl &&
8346 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00008347 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8348 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8349 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +00008350 NewIdx = Inst->getOperand(0);
8351 } else if (Inst->getOpcode() == Instruction::Mul &&
8352 isa<ConstantInt>(Inst->getOperand(1))) {
8353 Scale = cast<ConstantInt>(Inst->getOperand(1));
8354 NewIdx = Inst->getOperand(0);
8355 }
8356 }
8357
8358 // If the index will be to exactly the right offset with the scale taken
8359 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008360 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008361 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008362 Scale = ConstantInt::get(Scale->getType(),
8363 Scale->getZExtValue() / ArrayEltSize);
8364 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008365 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8366 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008367 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8368 NewIdx = InsertNewInstBefore(Sc, GEP);
8369 }
8370
8371 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008372 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008373 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008374 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008375 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8376 // The NewGEP must be pointer typed, so must the old one -> BitCast
8377 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008378 }
8379 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008380 }
Chris Lattnerca081252001-12-14 16:52:21 +00008381 }
8382
Chris Lattnerca081252001-12-14 16:52:21 +00008383 return 0;
8384}
8385
Chris Lattner1085bdf2002-11-04 16:18:53 +00008386Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8387 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8388 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008389 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8390 const Type *NewTy =
8391 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008392 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008393
8394 // Create and insert the replacement instruction...
8395 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008396 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008397 else {
8398 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008399 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008400 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008401
8402 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008403
Chris Lattner1085bdf2002-11-04 16:18:53 +00008404 // Scan to the end of the allocation instructions, to skip over a block of
8405 // allocas if possible...
8406 //
8407 BasicBlock::iterator It = New;
8408 while (isa<AllocationInst>(*It)) ++It;
8409
8410 // Now that I is pointing to the first non-allocation-inst in the block,
8411 // insert our getelementptr instruction...
8412 //
Reid Spencerc635f472006-12-31 05:48:39 +00008413 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008414 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8415 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008416
8417 // Now make everything use the getelementptr instead of the original
8418 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008419 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008420 } else if (isa<UndefValue>(AI.getArraySize())) {
8421 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008422 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008423
8424 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8425 // Note that we only do this for alloca's, because malloc should allocate and
8426 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008427 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008428 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008429 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8430
Chris Lattner1085bdf2002-11-04 16:18:53 +00008431 return 0;
8432}
8433
Chris Lattner8427bff2003-12-07 01:24:23 +00008434Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8435 Value *Op = FI.getOperand(0);
8436
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008437 // free undef -> unreachable.
8438 if (isa<UndefValue>(Op)) {
8439 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008440 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008441 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008442 return EraseInstFromFunction(FI);
8443 }
Chris Lattnerefb33d22007-04-14 00:20:02 +00008444
Chris Lattnerf3a36602004-02-28 04:57:37 +00008445 // If we have 'free null' delete the instruction. This can happen in stl code
8446 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008447 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008448 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +00008449
8450 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8451 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8452 FI.setOperand(0, CI->getOperand(0));
8453 return &FI;
8454 }
8455
8456 // Change free (gep X, 0,0,0,0) into free(X)
8457 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8458 if (GEPI->hasAllZeroIndices()) {
8459 AddToWorkList(GEPI);
8460 FI.setOperand(0, GEPI->getOperand(0));
8461 return &FI;
8462 }
8463 }
8464
8465 // Change free(malloc) into nothing, if the malloc has a single use.
8466 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8467 if (MI->hasOneUse()) {
8468 EraseInstFromFunction(FI);
8469 return EraseInstFromFunction(*MI);
8470 }
Chris Lattnerf3a36602004-02-28 04:57:37 +00008471
Chris Lattner8427bff2003-12-07 01:24:23 +00008472 return 0;
8473}
8474
8475
Chris Lattner72684fe2005-01-31 05:51:45 +00008476/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008477static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8478 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008479 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008480
8481 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008482 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008483 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008484
Reid Spencer31a4ef42007-01-22 05:51:25 +00008485 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008486 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008487 // If the source is an array, the code below will not succeed. Check to
8488 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8489 // constants.
8490 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8491 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8492 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008493 Value *Idxs[2];
8494 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8495 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008496 SrcTy = cast<PointerType>(CastOp->getType());
8497 SrcPTy = SrcTy->getElementType();
8498 }
8499
Reid Spencer31a4ef42007-01-22 05:51:25 +00008500 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008501 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008502 // Do not allow turning this into a load of an integer, which is then
8503 // casted to a pointer, this pessimizes pointer analysis a lot.
8504 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008505 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8506 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008507
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008508 // Okay, we are casting from one integer or pointer type to another of
8509 // the same size. Instead of casting the pointer before the load, cast
8510 // the result of the loaded value.
8511 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8512 CI->getName(),
8513 LI.isVolatile()),LI);
8514 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008515 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008516 }
Chris Lattner35e24772004-07-13 01:49:43 +00008517 }
8518 }
8519 return 0;
8520}
8521
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008522/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008523/// from this value cannot trap. If it is not obviously safe to load from the
8524/// specified pointer, we do a quick local scan of the basic block containing
8525/// ScanFrom, to determine if the address is already accessed.
8526static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8527 // If it is an alloca or global variable, it is always safe to load from.
8528 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8529
8530 // Otherwise, be a little bit agressive by scanning the local block where we
8531 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008532 // from/to. If so, the previous load or store would have already trapped,
8533 // so there is no harm doing an extra load (also, CSE will later eliminate
8534 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008535 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8536
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008537 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008538 --BBI;
8539
8540 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8541 if (LI->getOperand(0) == V) return true;
8542 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8543 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008544
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008545 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008546 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008547}
8548
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008549Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8550 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008551
Chris Lattnera9d84e32005-05-01 04:24:53 +00008552 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008553 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008554 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8555 return Res;
8556
8557 // None of the following transforms are legal for volatile loads.
8558 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008559
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008560 if (&LI.getParent()->front() != &LI) {
8561 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008562 // If the instruction immediately before this is a store to the same
8563 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008564 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8565 if (SI->getOperand(1) == LI.getOperand(0))
8566 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008567 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8568 if (LIB->getOperand(0) == LI.getOperand(0))
8569 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008570 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008571
8572 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8573 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8574 isa<UndefValue>(GEPI->getOperand(0))) {
8575 // Insert a new store to null instruction before the load to indicate
8576 // that this code is not reachable. We do this instead of inserting
8577 // an unreachable instruction directly because we cannot modify the
8578 // CFG.
8579 new StoreInst(UndefValue::get(LI.getType()),
8580 Constant::getNullValue(Op->getType()), &LI);
8581 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8582 }
8583
Chris Lattner81a7a232004-10-16 18:11:37 +00008584 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008585 // load null/undef -> undef
8586 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008587 // Insert a new store to null instruction before the load to indicate that
8588 // this code is not reachable. We do this instead of inserting an
8589 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008590 new StoreInst(UndefValue::get(LI.getType()),
8591 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008592 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008593 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008594
Chris Lattner81a7a232004-10-16 18:11:37 +00008595 // Instcombine load (constant global) into the value loaded.
8596 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008597 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008598 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008599
Chris Lattner81a7a232004-10-16 18:11:37 +00008600 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8601 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8602 if (CE->getOpcode() == Instruction::GetElementPtr) {
8603 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008604 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008605 if (Constant *V =
8606 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008607 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008608 if (CE->getOperand(0)->isNullValue()) {
8609 // Insert a new store to null instruction before the load to indicate
8610 // that this code is not reachable. We do this instead of inserting
8611 // an unreachable instruction directly because we cannot modify the
8612 // CFG.
8613 new StoreInst(UndefValue::get(LI.getType()),
8614 Constant::getNullValue(Op->getType()), &LI);
8615 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8616 }
8617
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008618 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008619 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8620 return Res;
8621 }
8622 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008623
Chris Lattnera9d84e32005-05-01 04:24:53 +00008624 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008625 // Change select and PHI nodes to select values instead of addresses: this
8626 // helps alias analysis out a lot, allows many others simplifications, and
8627 // exposes redundancy in the code.
8628 //
8629 // Note that we cannot do the transformation unless we know that the
8630 // introduced loads cannot trap! Something like this is valid as long as
8631 // the condition is always false: load (select bool %C, int* null, int* %G),
8632 // but it would not be valid if we transformed it to load from null
8633 // unconditionally.
8634 //
8635 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8636 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008637 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8638 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008639 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008640 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008641 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008642 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008643 return new SelectInst(SI->getCondition(), V1, V2);
8644 }
8645
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008646 // load (select (cond, null, P)) -> load P
8647 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8648 if (C->isNullValue()) {
8649 LI.setOperand(0, SI->getOperand(2));
8650 return &LI;
8651 }
8652
8653 // load (select (cond, P, null)) -> load P
8654 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8655 if (C->isNullValue()) {
8656 LI.setOperand(0, SI->getOperand(1));
8657 return &LI;
8658 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008659 }
8660 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008661 return 0;
8662}
8663
Reid Spencere928a152007-01-19 21:20:31 +00008664/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008665/// when possible.
8666static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8667 User *CI = cast<User>(SI.getOperand(1));
8668 Value *CastOp = CI->getOperand(0);
8669
8670 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8671 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8672 const Type *SrcPTy = SrcTy->getElementType();
8673
Reid Spencer31a4ef42007-01-22 05:51:25 +00008674 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008675 // If the source is an array, the code below will not succeed. Check to
8676 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8677 // constants.
8678 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8679 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8680 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008681 Value* Idxs[2];
8682 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8683 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008684 SrcTy = cast<PointerType>(CastOp->getType());
8685 SrcPTy = SrcTy->getElementType();
8686 }
8687
Reid Spencer9a4bed02007-01-20 23:35:48 +00008688 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8689 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8690 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008691
8692 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008693 // the same size. Instead of casting the pointer before
8694 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008695 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008696 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008697 Instruction::CastOps opcode = Instruction::BitCast;
8698 const Type* CastSrcTy = SIOp0->getType();
8699 const Type* CastDstTy = SrcPTy;
8700 if (isa<PointerType>(CastDstTy)) {
8701 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008702 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008703 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008704 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008705 opcode = Instruction::PtrToInt;
8706 }
8707 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008708 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008709 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008710 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008711 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8712 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008713 return new StoreInst(NewCast, CastOp);
8714 }
8715 }
8716 }
8717 return 0;
8718}
8719
Chris Lattner31f486c2005-01-31 05:36:43 +00008720Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8721 Value *Val = SI.getOperand(0);
8722 Value *Ptr = SI.getOperand(1);
8723
8724 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008725 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008726 ++NumCombined;
8727 return 0;
8728 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008729
8730 // If the RHS is an alloca with a single use, zapify the store, making the
8731 // alloca dead.
8732 if (Ptr->hasOneUse()) {
8733 if (isa<AllocaInst>(Ptr)) {
8734 EraseInstFromFunction(SI);
8735 ++NumCombined;
8736 return 0;
8737 }
8738
8739 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8740 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8741 GEP->getOperand(0)->hasOneUse()) {
8742 EraseInstFromFunction(SI);
8743 ++NumCombined;
8744 return 0;
8745 }
8746 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008747
Chris Lattner5997cf92006-02-08 03:25:32 +00008748 // Do really simple DSE, to catch cases where there are several consequtive
8749 // stores to the same location, separated by a few arithmetic operations. This
8750 // situation often occurs with bitfield accesses.
8751 BasicBlock::iterator BBI = &SI;
8752 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8753 --ScanInsts) {
8754 --BBI;
8755
8756 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8757 // Prev store isn't volatile, and stores to the same location?
8758 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8759 ++NumDeadStore;
8760 ++BBI;
8761 EraseInstFromFunction(*PrevSI);
8762 continue;
8763 }
8764 break;
8765 }
8766
Chris Lattnerdab43b22006-05-26 19:19:20 +00008767 // If this is a load, we have to stop. However, if the loaded value is from
8768 // the pointer we're loading and is producing the pointer we're storing,
8769 // then *this* store is dead (X = load P; store X -> P).
8770 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8771 if (LI == Val && LI->getOperand(0) == Ptr) {
8772 EraseInstFromFunction(SI);
8773 ++NumCombined;
8774 return 0;
8775 }
8776 // Otherwise, this is a load from some other location. Stores before it
8777 // may not be dead.
8778 break;
8779 }
8780
Chris Lattner5997cf92006-02-08 03:25:32 +00008781 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008782 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008783 break;
8784 }
8785
8786
8787 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008788
8789 // store X, null -> turns into 'unreachable' in SimplifyCFG
8790 if (isa<ConstantPointerNull>(Ptr)) {
8791 if (!isa<UndefValue>(Val)) {
8792 SI.setOperand(0, UndefValue::get(Val->getType()));
8793 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008794 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008795 ++NumCombined;
8796 }
8797 return 0; // Do not modify these!
8798 }
8799
8800 // store undef, Ptr -> noop
8801 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008802 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008803 ++NumCombined;
8804 return 0;
8805 }
8806
Chris Lattner72684fe2005-01-31 05:51:45 +00008807 // If the pointer destination is a cast, see if we can fold the cast into the
8808 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008809 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008810 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8811 return Res;
8812 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008813 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008814 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8815 return Res;
8816
Chris Lattner219175c2005-09-12 23:23:25 +00008817
8818 // If this store is the last instruction in the basic block, and if the block
8819 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008820 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008821 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner14a251b2007-04-15 00:07:55 +00008822 if (BI->isUnconditional())
8823 if (SimplifyStoreAtEndOfBlock(SI))
8824 return 0; // xform done!
Chris Lattner219175c2005-09-12 23:23:25 +00008825
Chris Lattner31f486c2005-01-31 05:36:43 +00008826 return 0;
8827}
8828
Chris Lattner14a251b2007-04-15 00:07:55 +00008829/// SimplifyStoreAtEndOfBlock - Turn things like:
8830/// if () { *P = v1; } else { *P = v2 }
8831/// into a phi node with a store in the successor.
8832///
8833bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
8834 BasicBlock *StoreBB = SI.getParent();
8835
8836 // Check to see if the successor block has exactly two incoming edges. If
8837 // so, see if the other predecessor contains a store to the same location.
8838 // if so, insert a PHI node (if needed) and move the stores down.
8839 BasicBlock *Dest = StoreBB->getTerminator()->getSuccessor(0);
8840
8841 // Determine whether Dest has exactly two predecessors and, if so, compute
8842 // the other predecessor.
8843 pred_iterator PI = pred_begin(Dest);
8844 BasicBlock *Other = 0;
8845 if (*PI != StoreBB)
8846 Other = *PI;
8847 ++PI;
8848 if (PI == pred_end(Dest))
8849 return false;
8850
8851 if (*PI != StoreBB) {
8852 if (Other)
8853 return false;
8854 Other = *PI;
8855 }
8856 if (++PI != pred_end(Dest))
8857 return false;
8858
8859
8860 BasicBlock::iterator BBI = Other->getTerminator();
8861 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
8862
8863 // Make sure this other block ends in an unconditional branch and that
8864 // there is an instruction before the branch.
8865 if (!OtherBr || !cast<BranchInst>(BBI)->isUnconditional() ||
8866 BBI == Other->begin())
8867 return false;
8868
8869 // See if the last instruction in other block is a store to the same location.
8870 --BBI;
8871 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8872
8873 // If this instruction is a store to the same location.
8874 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
8875 return false;
8876
8877 // Okay, we know we can perform this transformation. Insert a PHI
8878 // node now if we need it.
8879 Value *MergedVal = OtherStore->getOperand(0);
8880 if (MergedVal != SI.getOperand(0)) {
8881 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8882 PN->reserveOperandSpace(2);
8883 PN->addIncoming(SI.getOperand(0), SI.getParent());
8884 PN->addIncoming(OtherStore->getOperand(0), Other);
8885 MergedVal = InsertNewInstBefore(PN, Dest->front());
8886 }
8887
8888 // Advance to a place where it is safe to insert the new store and
8889 // insert it.
8890 BBI = Dest->begin();
8891 while (isa<PHINode>(BBI)) ++BBI;
8892 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8893 OtherStore->isVolatile()), *BBI);
8894
8895 // Nuke the old stores.
8896 EraseInstFromFunction(SI);
8897 EraseInstFromFunction(*OtherStore);
8898 ++NumCombined;
8899 return true;
8900}
8901
Chris Lattner31f486c2005-01-31 05:36:43 +00008902
Chris Lattner9eef8a72003-06-04 04:46:00 +00008903Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8904 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008905 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008906 BasicBlock *TrueDest;
8907 BasicBlock *FalseDest;
8908 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8909 !isa<Constant>(X)) {
8910 // Swap Destinations and condition...
8911 BI.setCondition(X);
8912 BI.setSuccessor(0, FalseDest);
8913 BI.setSuccessor(1, TrueDest);
8914 return &BI;
8915 }
8916
Reid Spencer266e42b2006-12-23 06:05:41 +00008917 // Cannonicalize fcmp_one -> fcmp_oeq
8918 FCmpInst::Predicate FPred; Value *Y;
8919 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8920 TrueDest, FalseDest)))
8921 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8922 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8923 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008924 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008925 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8926 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008927 // Swap Destinations and condition...
8928 BI.setCondition(NewSCC);
8929 BI.setSuccessor(0, FalseDest);
8930 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008931 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008932 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008933 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008934 return &BI;
8935 }
8936
8937 // Cannonicalize icmp_ne -> icmp_eq
8938 ICmpInst::Predicate IPred;
8939 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8940 TrueDest, FalseDest)))
8941 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8942 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8943 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8944 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008945 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008946 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8947 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008948 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008949 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008950 BI.setSuccessor(0, FalseDest);
8951 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008952 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008953 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008954 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008955 return &BI;
8956 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008957
Chris Lattner9eef8a72003-06-04 04:46:00 +00008958 return 0;
8959}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008960
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008961Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8962 Value *Cond = SI.getCondition();
8963 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8964 if (I->getOpcode() == Instruction::Add)
8965 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8966 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8967 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008968 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008969 AddRHS));
8970 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008971 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008972 return &SI;
8973 }
8974 }
8975 return 0;
8976}
8977
Chris Lattner6bc98652006-03-05 00:22:33 +00008978/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8979/// is to leave as a vector operation.
8980static bool CheapToScalarize(Value *V, bool isConstant) {
8981 if (isa<ConstantAggregateZero>(V))
8982 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008983 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008984 if (isConstant) return true;
8985 // If all elts are the same, we can extract.
8986 Constant *Op0 = C->getOperand(0);
8987 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8988 if (C->getOperand(i) != Op0)
8989 return false;
8990 return true;
8991 }
8992 Instruction *I = dyn_cast<Instruction>(V);
8993 if (!I) return false;
8994
8995 // Insert element gets simplified to the inserted element or is deleted if
8996 // this is constant idx extract element and its a constant idx insertelt.
8997 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8998 isa<ConstantInt>(I->getOperand(2)))
8999 return true;
9000 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9001 return true;
9002 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9003 if (BO->hasOneUse() &&
9004 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9005 CheapToScalarize(BO->getOperand(1), isConstant)))
9006 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00009007 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9008 if (CI->hasOneUse() &&
9009 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9010 CheapToScalarize(CI->getOperand(1), isConstant)))
9011 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00009012
9013 return false;
9014}
9015
Chris Lattner945e4372007-02-14 05:52:17 +00009016/// Read and decode a shufflevector mask.
9017///
9018/// It turns undef elements into values that are larger than the number of
9019/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00009020static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9021 unsigned NElts = SVI->getType()->getNumElements();
9022 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9023 return std::vector<unsigned>(NElts, 0);
9024 if (isa<UndefValue>(SVI->getOperand(2)))
9025 return std::vector<unsigned>(NElts, 2*NElts);
9026
9027 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009028 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00009029 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9030 if (isa<UndefValue>(CP->getOperand(i)))
9031 Result.push_back(NElts*2); // undef -> 8
9032 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00009033 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00009034 return Result;
9035}
9036
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009037/// FindScalarElement - Given a vector and an element number, see if the scalar
9038/// value is already around as a register, for example if it were inserted then
9039/// extracted from the vector.
9040static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009041 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9042 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00009043 unsigned Width = PTy->getNumElements();
9044 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009045 return UndefValue::get(PTy->getElementType());
9046
9047 if (isa<UndefValue>(V))
9048 return UndefValue::get(PTy->getElementType());
9049 else if (isa<ConstantAggregateZero>(V))
9050 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00009051 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009052 return CP->getOperand(EltNo);
9053 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9054 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009055 if (!isa<ConstantInt>(III->getOperand(2)))
9056 return 0;
9057 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009058
9059 // If this is an insert to the element we are looking for, return the
9060 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009061 if (EltNo == IIElt)
9062 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009063
9064 // Otherwise, the insertelement doesn't modify the value, recurse on its
9065 // vector input.
9066 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00009067 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00009068 unsigned InEl = getShuffleMask(SVI)[EltNo];
9069 if (InEl < Width)
9070 return FindScalarElement(SVI->getOperand(0), InEl);
9071 else if (InEl < Width*2)
9072 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9073 else
9074 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009075 }
9076
9077 // Otherwise, we don't know.
9078 return 0;
9079}
9080
Robert Bocchinoa8352962006-01-13 22:48:06 +00009081Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009082
Chris Lattner92346c32006-03-31 18:25:14 +00009083 // If packed val is undef, replace extract with scalar undef.
9084 if (isa<UndefValue>(EI.getOperand(0)))
9085 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9086
9087 // If packed val is constant 0, replace extract with scalar 0.
9088 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9089 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9090
Reid Spencerd84d35b2007-02-15 02:26:10 +00009091 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009092 // If packed val is constant with uniform operands, replace EI
9093 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00009094 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009095 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00009096 if (C->getOperand(i) != op0) {
9097 op0 = 0;
9098 break;
9099 }
9100 if (op0)
9101 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009102 }
Chris Lattner6bc98652006-03-05 00:22:33 +00009103
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009104 // If extracting a specified index from the vector, see if we can recursively
9105 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009106 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +00009107 unsigned IndexVal = IdxC->getZExtValue();
9108 unsigned VectorWidth =
9109 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9110
9111 // If this is extracting an invalid index, turn this into undef, to avoid
9112 // crashing the code below.
9113 if (IndexVal >= VectorWidth)
9114 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9115
Chris Lattner2deeaea2006-10-05 06:55:50 +00009116 // This instruction only demands the single element from the input vector.
9117 // If the input vector has a single use, simplify it based on this use
9118 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +00009119 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00009120 uint64_t UndefElts;
9121 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00009122 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00009123 UndefElts)) {
9124 EI.setOperand(0, V);
9125 return &EI;
9126 }
9127 }
9128
Reid Spencere0fc4df2006-10-20 07:07:24 +00009129 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009130 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +00009131
9132 // If the this extractelement is directly using a bitcast from a vector of
9133 // the same number of elements, see if we can find the source element from
9134 // it. In this case, we will end up needing to bitcast the scalars.
9135 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9136 if (const VectorType *VT =
9137 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9138 if (VT->getNumElements() == VectorWidth)
9139 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9140 return new BitCastInst(Elt, EI.getType());
9141 }
Chris Lattner2d37f922006-04-10 23:06:36 +00009142 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009143
Chris Lattner83f65782006-05-25 22:53:38 +00009144 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009145 if (I->hasOneUse()) {
9146 // Push extractelement into predecessor operation if legal and
9147 // profitable to do so
9148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009149 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9150 if (CheapToScalarize(BO, isConstantElt)) {
9151 ExtractElementInst *newEI0 =
9152 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9153 EI.getName()+".lhs");
9154 ExtractElementInst *newEI1 =
9155 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9156 EI.getName()+".rhs");
9157 InsertNewInstBefore(newEI0, EI);
9158 InsertNewInstBefore(newEI1, EI);
9159 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9160 }
Reid Spencerde46e482006-11-02 20:25:50 +00009161 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009162 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00009163 PointerType::get(EI.getType()), EI);
9164 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00009165 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00009166 InsertNewInstBefore(GEP, EI);
9167 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00009168 }
9169 }
9170 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9171 // Extracting the inserted element?
9172 if (IE->getOperand(2) == EI.getOperand(1))
9173 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9174 // If the inserted and extracted elements are constants, they must not
9175 // be the same value, extract from the pre-inserted value instead.
9176 if (isa<Constant>(IE->getOperand(2)) &&
9177 isa<Constant>(EI.getOperand(1))) {
9178 AddUsesToWorkList(EI);
9179 EI.setOperand(0, IE->getOperand(0));
9180 return &EI;
9181 }
9182 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9183 // If this is extracting an element from a shufflevector, figure out where
9184 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009185 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9186 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00009187 Value *Src;
9188 if (SrcIdx < SVI->getType()->getNumElements())
9189 Src = SVI->getOperand(0);
9190 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9191 SrcIdx -= SVI->getType()->getNumElements();
9192 Src = SVI->getOperand(1);
9193 } else {
9194 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009195 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009196 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009197 }
9198 }
Chris Lattner83f65782006-05-25 22:53:38 +00009199 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009200 return 0;
9201}
9202
Chris Lattner90951862006-04-16 00:51:47 +00009203/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9204/// elements from either LHS or RHS, return the shuffle mask and true.
9205/// Otherwise, return false.
9206static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9207 std::vector<Constant*> &Mask) {
9208 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9209 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009210 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009211
9212 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009213 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009214 return true;
9215 } else if (V == LHS) {
9216 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009217 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009218 return true;
9219 } else if (V == RHS) {
9220 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009221 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009222 return true;
9223 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9224 // If this is an insert of an extract from some other vector, include it.
9225 Value *VecOp = IEI->getOperand(0);
9226 Value *ScalarOp = IEI->getOperand(1);
9227 Value *IdxOp = IEI->getOperand(2);
9228
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009229 if (!isa<ConstantInt>(IdxOp))
9230 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009231 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009232
9233 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9234 // Okay, we can handle this if the vector we are insertinting into is
9235 // transitively ok.
9236 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9237 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009238 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009239 return true;
9240 }
9241 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9242 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009243 EI->getOperand(0)->getType() == V->getType()) {
9244 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009245 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009246
9247 // This must be extracting from either LHS or RHS.
9248 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9249 // Okay, we can handle this if the vector we are insertinting into is
9250 // transitively ok.
9251 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9252 // If so, update the mask to reflect the inserted value.
9253 if (EI->getOperand(0) == LHS) {
9254 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009255 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009256 } else {
9257 assert(EI->getOperand(0) == RHS);
9258 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009259 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009260
9261 }
9262 return true;
9263 }
9264 }
9265 }
9266 }
9267 }
9268 // TODO: Handle shufflevector here!
9269
9270 return false;
9271}
9272
9273/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9274/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9275/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009276static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009277 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009278 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009279 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009280 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009281 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009282
9283 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009284 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009285 return V;
9286 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009287 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009288 return V;
9289 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9290 // If this is an insert of an extract from some other vector, include it.
9291 Value *VecOp = IEI->getOperand(0);
9292 Value *ScalarOp = IEI->getOperand(1);
9293 Value *IdxOp = IEI->getOperand(2);
9294
9295 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9296 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9297 EI->getOperand(0)->getType() == V->getType()) {
9298 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009299 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9300 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009301
9302 // Either the extracted from or inserted into vector must be RHSVec,
9303 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009304 if (EI->getOperand(0) == RHS || RHS == 0) {
9305 RHS = EI->getOperand(0);
9306 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009307 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009308 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009309 return V;
9310 }
9311
Chris Lattner90951862006-04-16 00:51:47 +00009312 if (VecOp == RHS) {
9313 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009314 // Everything but the extracted element is replaced with the RHS.
9315 for (unsigned i = 0; i != NumElts; ++i) {
9316 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009317 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009318 }
9319 return V;
9320 }
Chris Lattner90951862006-04-16 00:51:47 +00009321
9322 // If this insertelement is a chain that comes from exactly these two
9323 // vectors, return the vector and the effective shuffle.
9324 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9325 return EI->getOperand(0);
9326
Chris Lattner39fac442006-04-15 01:39:45 +00009327 }
9328 }
9329 }
Chris Lattner90951862006-04-16 00:51:47 +00009330 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009331
9332 // Otherwise, can't do anything fancy. Return an identity vector.
9333 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009334 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009335 return V;
9336}
9337
9338Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9339 Value *VecOp = IE.getOperand(0);
9340 Value *ScalarOp = IE.getOperand(1);
9341 Value *IdxOp = IE.getOperand(2);
9342
Chris Lattner4ca9cbb2007-04-09 01:11:16 +00009343 // Inserting an undef or into an undefined place, remove this.
9344 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9345 ReplaceInstUsesWith(IE, VecOp);
9346
Chris Lattner39fac442006-04-15 01:39:45 +00009347 // If the inserted element was extracted from some other vector, and if the
9348 // indexes are constant, try to turn this into a shufflevector operation.
9349 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9350 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9351 EI->getOperand(0)->getType() == IE.getType()) {
9352 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattner28d921d2007-04-14 23:32:02 +00009353 unsigned ExtractedIdx =
9354 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009355 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009356
9357 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9358 return ReplaceInstUsesWith(IE, VecOp);
9359
9360 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9361 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9362
9363 // If we are extracting a value from a vector, then inserting it right
9364 // back into the same place, just use the input vector.
9365 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9366 return ReplaceInstUsesWith(IE, VecOp);
9367
9368 // We could theoretically do this for ANY input. However, doing so could
9369 // turn chains of insertelement instructions into a chain of shufflevector
9370 // instructions, and right now we do not merge shufflevectors. As such,
9371 // only do this in a situation where it is clear that there is benefit.
9372 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9373 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9374 // the values of VecOp, except then one read from EIOp0.
9375 // Build a new shuffle mask.
9376 std::vector<Constant*> Mask;
9377 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009378 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009379 else {
9380 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009381 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009382 NumVectorElts));
9383 }
Reid Spencerc635f472006-12-31 05:48:39 +00009384 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009385 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009386 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009387 }
9388
9389 // If this insertelement isn't used by some other insertelement, turn it
9390 // (and any insertelements it points to), into one big shuffle.
9391 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9392 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009393 Value *RHS = 0;
9394 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9395 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9396 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009397 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009398 }
9399 }
9400 }
9401
9402 return 0;
9403}
9404
9405
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009406Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9407 Value *LHS = SVI.getOperand(0);
9408 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009409 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009410
9411 bool MadeChange = false;
9412
Chris Lattner2deeaea2006-10-05 06:55:50 +00009413 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009414 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009415 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9416
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009417 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009418 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009419 if (isa<UndefValue>(SVI.getOperand(1))) {
9420 // Scan to see if there are any references to the RHS. If so, replace them
9421 // with undef element refs and set MadeChange to true.
9422 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9423 if (Mask[i] >= e && Mask[i] != 2*e) {
9424 Mask[i] = 2*e;
9425 MadeChange = true;
9426 }
9427 }
9428
9429 if (MadeChange) {
9430 // Remap any references to RHS to use LHS.
9431 std::vector<Constant*> Elts;
9432 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9433 if (Mask[i] == 2*e)
9434 Elts.push_back(UndefValue::get(Type::Int32Ty));
9435 else
9436 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9437 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009438 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009439 }
9440 }
Chris Lattner39fac442006-04-15 01:39:45 +00009441
Chris Lattner12249be2006-05-25 23:48:38 +00009442 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9443 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9444 if (LHS == RHS || isa<UndefValue>(LHS)) {
9445 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009446 // shuffle(undef,undef,mask) -> undef.
9447 return ReplaceInstUsesWith(SVI, LHS);
9448 }
9449
Chris Lattner12249be2006-05-25 23:48:38 +00009450 // Remap any references to RHS to use LHS.
9451 std::vector<Constant*> Elts;
9452 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009453 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009454 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009455 else {
9456 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9457 (Mask[i] < e && isa<UndefValue>(LHS)))
9458 Mask[i] = 2*e; // Turn into undef.
9459 else
9460 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009461 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009462 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009463 }
Chris Lattner12249be2006-05-25 23:48:38 +00009464 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009465 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009466 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009467 LHS = SVI.getOperand(0);
9468 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009469 MadeChange = true;
9470 }
9471
Chris Lattner0e477162006-05-26 00:29:06 +00009472 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009473 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009474
Chris Lattner12249be2006-05-25 23:48:38 +00009475 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9476 if (Mask[i] >= e*2) continue; // Ignore undef values.
9477 // Is this an identity shuffle of the LHS value?
9478 isLHSID &= (Mask[i] == i);
9479
9480 // Is this an identity shuffle of the RHS value?
9481 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009482 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009483
Chris Lattner12249be2006-05-25 23:48:38 +00009484 // Eliminate identity shuffles.
9485 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9486 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009487
Chris Lattner0e477162006-05-26 00:29:06 +00009488 // If the LHS is a shufflevector itself, see if we can combine it with this
9489 // one without producing an unusual shuffle. Here we are really conservative:
9490 // we are absolutely afraid of producing a shuffle mask not in the input
9491 // program, because the code gen may not be smart enough to turn a merged
9492 // shuffle into two specific shuffles: it may produce worse code. As such,
9493 // we only merge two shuffles if the result is one of the two input shuffle
9494 // masks. In this case, merging the shuffles just removes one instruction,
9495 // which we know is safe. This is good for things like turning:
9496 // (splat(splat)) -> splat.
9497 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9498 if (isa<UndefValue>(RHS)) {
9499 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9500
9501 std::vector<unsigned> NewMask;
9502 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9503 if (Mask[i] >= 2*e)
9504 NewMask.push_back(2*e);
9505 else
9506 NewMask.push_back(LHSMask[Mask[i]]);
9507
9508 // If the result mask is equal to the src shuffle or this shuffle mask, do
9509 // the replacement.
9510 if (NewMask == LHSMask || NewMask == Mask) {
9511 std::vector<Constant*> Elts;
9512 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9513 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009514 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009515 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009516 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009517 }
9518 }
9519 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9520 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009521 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009522 }
9523 }
9524 }
Chris Lattner4284f642007-01-30 22:32:46 +00009525
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009526 return MadeChange ? &SVI : 0;
9527}
9528
9529
Robert Bocchinoa8352962006-01-13 22:48:06 +00009530
Chris Lattner39c98bb2004-12-08 23:43:58 +00009531
9532/// TryToSinkInstruction - Try to move the specified instruction from its
9533/// current block into the beginning of DestBlock, which can only happen if it's
9534/// safe to move the instruction past all of the instructions between it and the
9535/// end of its block.
9536static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9537 assert(I->hasOneUse() && "Invariants didn't hold!");
9538
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009539 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9540 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009541
Chris Lattner39c98bb2004-12-08 23:43:58 +00009542 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009543 if (isa<AllocaInst>(I) && I->getParent() ==
9544 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009545 return false;
9546
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009547 // We can only sink load instructions if there is nothing between the load and
9548 // the end of block that could change the value.
9549 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009550 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9551 Scan != E; ++Scan)
9552 if (Scan->mayWriteToMemory())
9553 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009554 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009555
9556 BasicBlock::iterator InsertPos = DestBlock->begin();
9557 while (isa<PHINode>(InsertPos)) ++InsertPos;
9558
Chris Lattner9f269e42005-08-08 19:11:57 +00009559 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009560 ++NumSunkInst;
9561 return true;
9562}
9563
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009564
9565/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9566/// all reachable code to the worklist.
9567///
9568/// This has a couple of tricks to make the code faster and more powerful. In
9569/// particular, we constant fold and DCE instructions as we go, to avoid adding
9570/// them to the worklist (this significantly speeds up instcombine on code where
9571/// many instructions are dead or constant). Additionally, if we find a branch
9572/// whose condition is a known constant, we only visit the reachable successors.
9573///
9574static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009575 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009576 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009577 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009578 std::vector<BasicBlock*> Worklist;
9579 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009580
Chris Lattner12b89cc2007-03-23 19:17:18 +00009581 while (!Worklist.empty()) {
9582 BB = Worklist.back();
9583 Worklist.pop_back();
9584
9585 // We have now visited this block! If we've already been here, ignore it.
9586 if (!Visited.insert(BB)) continue;
9587
9588 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9589 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009590
Chris Lattner12b89cc2007-03-23 19:17:18 +00009591 // DCE instruction if trivially dead.
9592 if (isInstructionTriviallyDead(Inst)) {
9593 ++NumDeadInst;
9594 DOUT << "IC: DCE: " << *Inst;
9595 Inst->eraseFromParent();
9596 continue;
9597 }
9598
9599 // ConstantProp instruction if trivially constant.
9600 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9601 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9602 Inst->replaceAllUsesWith(C);
9603 ++NumConstProp;
9604 Inst->eraseFromParent();
9605 continue;
9606 }
9607
9608 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009609 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009610
9611 // Recursively visit successors. If this is a branch or switch on a
9612 // constant, only visit the reachable successor.
9613 TerminatorInst *TI = BB->getTerminator();
9614 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9615 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9616 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9617 Worklist.push_back(BI->getSuccessor(!CondVal));
9618 continue;
9619 }
9620 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9621 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9622 // See if this is an explicit destination.
9623 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9624 if (SI->getCaseValue(i) == Cond) {
9625 Worklist.push_back(SI->getSuccessor(i));
9626 continue;
9627 }
9628
9629 // Otherwise it is the default destination.
9630 Worklist.push_back(SI->getSuccessor(0));
9631 continue;
9632 }
9633 }
9634
9635 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9636 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009637 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009638}
9639
Chris Lattner960a5432007-03-03 02:04:50 +00009640bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009641 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009642 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009643
9644 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9645 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009646
Chris Lattner4ed40f72005-07-07 20:40:38 +00009647 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009648 // Do a depth-first traversal of the function, populate the worklist with
9649 // the reachable instructions. Ignore blocks that are not reachable. Keep
9650 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009651 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009652 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009653
Chris Lattner4ed40f72005-07-07 20:40:38 +00009654 // Do a quick scan over the function. If we find any blocks that are
9655 // unreachable, remove any instructions inside of them. This prevents
9656 // the instcombine code from having to deal with some bad special cases.
9657 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9658 if (!Visited.count(BB)) {
9659 Instruction *Term = BB->getTerminator();
9660 while (Term != BB->begin()) { // Remove instrs bottom-up
9661 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009662
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009663 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009664 ++NumDeadInst;
9665
9666 if (!I->use_empty())
9667 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9668 I->eraseFromParent();
9669 }
9670 }
9671 }
Chris Lattnerca081252001-12-14 16:52:21 +00009672
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009673 while (!Worklist.empty()) {
9674 Instruction *I = RemoveOneFromWorkList();
9675 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009676
Chris Lattner1443bc52006-05-11 17:11:52 +00009677 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009678 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009679 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009680 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009681 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009682 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009683
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009684 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009685
9686 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009687 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009688 continue;
9689 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009690
Chris Lattner1443bc52006-05-11 17:11:52 +00009691 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009692 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009693 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009694
Chris Lattner1443bc52006-05-11 17:11:52 +00009695 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009696 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009697 ReplaceInstUsesWith(*I, C);
9698
Chris Lattner99f48c62002-09-02 04:59:56 +00009699 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009700 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009701 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009702 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009703 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009704
Chris Lattner39c98bb2004-12-08 23:43:58 +00009705 // See if we can trivially sink this instruction to a successor basic block.
9706 if (I->hasOneUse()) {
9707 BasicBlock *BB = I->getParent();
9708 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9709 if (UserParent != BB) {
9710 bool UserIsSuccessor = false;
9711 // See if the user is one of our successors.
9712 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9713 if (*SI == UserParent) {
9714 UserIsSuccessor = true;
9715 break;
9716 }
9717
9718 // If the user is one of our immediate successors, and if that successor
9719 // only has us as a predecessors (we'd have to split the critical edge
9720 // otherwise), we can keep going.
9721 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9722 next(pred_begin(UserParent)) == pred_end(UserParent))
9723 // Okay, the CFG is simple enough, try to sink this instruction.
9724 Changed |= TryToSinkInstruction(I, UserParent);
9725 }
9726 }
9727
Chris Lattnerca081252001-12-14 16:52:21 +00009728 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009729#ifndef NDEBUG
9730 std::string OrigI;
9731#endif
9732 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009733 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009734 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009735 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009736 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009737 DOUT << "IC: Old = " << *I
9738 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009739
Chris Lattner396dbfe2004-06-09 05:08:07 +00009740 // Everything uses the new instruction now.
9741 I->replaceAllUsesWith(Result);
9742
9743 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009744 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009745 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009746
Chris Lattner6e0123b2007-02-11 01:23:03 +00009747 // Move the name to the new instruction first.
9748 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009749
9750 // Insert the new instruction into the basic block...
9751 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009752 BasicBlock::iterator InsertPos = I;
9753
9754 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9755 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9756 ++InsertPos;
9757
9758 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009759
Chris Lattner63d75af2004-05-01 23:27:23 +00009760 // Make sure that we reprocess all operands now that we reduced their
9761 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009762 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009763
Chris Lattner396dbfe2004-06-09 05:08:07 +00009764 // Instructions can end up on the worklist more than once. Make sure
9765 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009766 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009767
9768 // Erase the old instruction.
9769 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009770 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009771#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009772 DOUT << "IC: Mod = " << OrigI
9773 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009774#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009775
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009776 // If the instruction was modified, it's possible that it is now dead.
9777 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009778 if (isInstructionTriviallyDead(I)) {
9779 // Make sure we process all operands now that we are reducing their
9780 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009781 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009782
Chris Lattner63d75af2004-05-01 23:27:23 +00009783 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009784 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009785 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009786 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009787 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009788 AddToWorkList(I);
9789 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009790 }
Chris Lattner053c0932002-05-14 15:24:07 +00009791 }
Chris Lattner260ab202002-04-18 17:39:14 +00009792 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009793 }
9794 }
9795
Chris Lattner960a5432007-03-03 02:04:50 +00009796 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009797 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009798}
9799
Chris Lattner960a5432007-03-03 02:04:50 +00009800
9801bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009802 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9803
Chris Lattner960a5432007-03-03 02:04:50 +00009804 bool EverMadeChange = false;
9805
9806 // Iterate while there is work to do.
9807 unsigned Iteration = 0;
9808 while (DoOneIteration(F, Iteration++))
9809 EverMadeChange = true;
9810 return EverMadeChange;
9811}
9812
Brian Gaeke38b79e82004-07-27 17:43:21 +00009813FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009814 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009815}
Brian Gaeke960707c2003-11-11 22:41:34 +00009816