blob: c63ba68bc02aab0585d246189a74dec27e8b0391 [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);
355
Reid Spencer74a528b2006-12-13 18:21:21 +0000356 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000357 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000358
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000359 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000360}
361
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000362// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000363// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000364static unsigned getComplexity(Value *V) {
365 if (isa<Instruction>(V)) {
366 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000367 return 3;
368 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000369 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000370 if (isa<Argument>(V)) return 3;
371 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000372}
Chris Lattner260ab202002-04-18 17:39:14 +0000373
Chris Lattner7fb29e12003-03-11 00:12:48 +0000374// isOnlyUse - Return true if this instruction will be deleted if we stop using
375// it.
376static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000377 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000378}
379
Chris Lattnere79e8542004-02-23 06:38:22 +0000380// getPromotedType - Return the specified type promoted as it would be to pass
381// though a va_arg area...
382static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000383 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
384 if (ITy->getBitWidth() < 32)
385 return Type::Int32Ty;
386 } else if (Ty == Type::FloatTy)
387 return Type::DoubleTy;
388 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000389}
390
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000391/// getBitCastOperand - If the specified operand is a CastInst or a constant
392/// expression bitcast, return the operand value, otherwise return null.
393static Value *getBitCastOperand(Value *V) {
394 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000395 return I->getOperand(0);
396 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000397 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000398 return CE->getOperand(0);
399 return 0;
400}
401
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000402/// This function is a wrapper around CastInst::isEliminableCastPair. It
403/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000404static Instruction::CastOps
405isEliminableCastPair(
406 const CastInst *CI, ///< The first cast instruction
407 unsigned opcode, ///< The opcode of the second cast instruction
408 const Type *DstTy, ///< The target type for the second cast instruction
409 TargetData *TD ///< The target data for pointer size
410) {
411
412 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
413 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000415 // Get the opcodes of the two Cast instructions
416 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
417 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000418
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000419 return Instruction::CastOps(
420 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
421 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000422}
423
424/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
425/// in any code being generated. It does not require codegen if V is simple
426/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000427static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
428 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 if (V->getType() == Ty || isa<Constant>(V)) return false;
430
Chris Lattner99155be2006-05-25 23:24:33 +0000431 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000432 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000433 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000434 return false;
435 return true;
436}
437
438/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
439/// InsertBefore instruction. This is specialized a bit to avoid inserting
440/// casts that are known to not do anything...
441///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000442Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
443 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000444 Instruction *InsertBefore) {
445 if (V->getType() == DestTy) return V;
446 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000447 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000448
Reid Spencer13bc5d72006-12-12 09:18:51 +0000449 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000450}
451
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452// SimplifyCommutative - This performs a few simplifications for commutative
453// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000454//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455// 1. Order operands such that they are listed from right (least complex) to
456// left (most complex). This puts constants before unary operators before
457// binary operators.
458//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000459// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
460// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000461//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000462bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000463 bool Changed = false;
464 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
465 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000466
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000467 if (!I.isAssociative()) return Changed;
468 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000469 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
470 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
471 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000472 Constant *Folded = ConstantExpr::get(I.getOpcode(),
473 cast<Constant>(I.getOperand(1)),
474 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000475 I.setOperand(0, Op->getOperand(0));
476 I.setOperand(1, Folded);
477 return true;
478 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
479 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
480 isOnlyUse(Op) && isOnlyUse(Op1)) {
481 Constant *C1 = cast<Constant>(Op->getOperand(1));
482 Constant *C2 = cast<Constant>(Op1->getOperand(1));
483
484 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000485 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000486 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
487 Op1->getOperand(0),
488 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000489 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 I.setOperand(0, New);
491 I.setOperand(1, Folded);
492 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000493 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000494 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000495 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000496}
Chris Lattnerca081252001-12-14 16:52:21 +0000497
Reid Spencer266e42b2006-12-23 06:05:41 +0000498/// SimplifyCompare - For a CmpInst this function just orders the operands
499/// so that theyare listed from right (least complex) to left (most complex).
500/// This puts constants before unary operators before binary operators.
501bool InstCombiner::SimplifyCompare(CmpInst &I) {
502 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
503 return false;
504 I.swapOperands();
505 // Compare instructions are not associative so there's nothing else we can do.
506 return true;
507}
508
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
510// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000511//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000512static inline Value *dyn_castNegVal(Value *V) {
513 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000514 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000515
Chris Lattner9ad0d552004-12-14 20:08:06 +0000516 // Constants can be considered to be negated values if they can be folded.
517 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
518 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000520}
521
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522static inline Value *dyn_castNotVal(Value *V) {
523 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000524 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525
526 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000528 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000529 return 0;
530}
531
Chris Lattner7fb29e12003-03-11 00:12:48 +0000532// dyn_castFoldableMul - If this value is a multiply that can be folded into
533// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534// non-constant operand of the multiply, and set CST to point to the multiplier.
535// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000536//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000537static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000538 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000539 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000540 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000541 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000543 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000544 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000546 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000547 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000548 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 return I->getOperand(0);
550 }
551 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000552 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000553}
Chris Lattner31ae8632002-08-14 17:51:49 +0000554
Chris Lattner0798af32005-01-13 20:14:25 +0000555/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
556/// expression, return it.
557static User *dyn_castGetElementPtr(Value *V) {
558 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
559 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
560 if (CE->getOpcode() == Instruction::GetElementPtr)
561 return cast<User>(V);
562 return false;
563}
564
Reid Spencer80263aa2007-03-25 05:33:51 +0000565/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000566static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000567 APInt Val(C->getValue());
568 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000569}
Reid Spencer80263aa2007-03-25 05:33:51 +0000570/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000571static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000572 APInt Val(C->getValue());
573 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000574}
575/// Add - Add two ConstantInts together
576static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
577 return ConstantInt::get(C1->getValue() + C2->getValue());
578}
579/// And - Bitwise AND two ConstantInts together
580static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
581 return ConstantInt::get(C1->getValue() & C2->getValue());
582}
583/// Subtract - Subtract one ConstantInt from another
584static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
585 return ConstantInt::get(C1->getValue() - C2->getValue());
586}
587/// Multiply - Multiply two ConstantInts together
588static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
589 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000590}
591
Chris Lattner4534dd592006-02-09 07:38:58 +0000592/// ComputeMaskedBits - Determine which of the bits specified in Mask are
593/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000594/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
595/// processing.
596/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
597/// we cannot optimize based on the assumption that it is zero without changing
598/// it to be an explicit zero. If we don't change it to zero, other code could
599/// optimized based on the contradictory assumption that it is non-zero.
600/// Because instcombine aggressively folds operations with undef args anyway,
601/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000602static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000603 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000604 assert(V && "No Value?");
605 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000606 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000607 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000608 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000609 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000610 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000611 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
612 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000613 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000614 KnownZero = ~KnownOne & Mask;
615 return;
616 }
617
Reid Spenceraa696402007-03-08 01:46:38 +0000618 if (Depth == 6 || Mask == 0)
619 return; // Limit search depth.
620
621 Instruction *I = dyn_cast<Instruction>(V);
622 if (!I) return;
623
Zhou Shengaf4341d2007-03-13 02:23:10 +0000624 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000625 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000626
627 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000628 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000631 APInt Mask2(Mask & ~KnownZero);
632 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
640 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000641 }
642 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000643 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000644 APInt Mask2(Mask & ~KnownOne);
645 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000646 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
647 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
648
649 // Output known-0 bits are only known if clear in both the LHS & RHS.
650 KnownZero &= KnownZero2;
651 // Output known-1 are known to be set if set in either the LHS | RHS.
652 KnownOne |= KnownOne2;
653 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000654 }
Reid Spenceraa696402007-03-08 01:46:38 +0000655 case Instruction::Xor: {
656 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
657 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
658 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
659 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
660
661 // Output known-0 bits are known if clear or set in both the LHS & RHS.
662 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
663 // Output known-1 are known to be set if set in only one of the LHS, RHS.
664 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
665 KnownZero = KnownZeroOut;
666 return;
667 }
668 case Instruction::Select:
669 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
670 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
671 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673
674 // Only known if known in both the LHS and RHS.
675 KnownOne &= KnownOne2;
676 KnownZero &= KnownZero2;
677 return;
678 case Instruction::FPTrunc:
679 case Instruction::FPExt:
680 case Instruction::FPToUI:
681 case Instruction::FPToSI:
682 case Instruction::SIToFP:
683 case Instruction::PtrToInt:
684 case Instruction::UIToFP:
685 case Instruction::IntToPtr:
686 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000687 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000688 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000689 uint32_t SrcBitWidth =
690 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000691 APInt MaskIn(Mask);
692 MaskIn.zext(SrcBitWidth);
693 KnownZero.zext(SrcBitWidth);
694 KnownOne.zext(SrcBitWidth);
695 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000696 KnownZero.trunc(BitWidth);
697 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000698 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000699 }
Reid Spenceraa696402007-03-08 01:46:38 +0000700 case Instruction::BitCast: {
701 const Type *SrcTy = I->getOperand(0)->getType();
702 if (SrcTy->isInteger()) {
703 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
704 return;
705 }
706 break;
707 }
708 case Instruction::ZExt: {
709 // Compute the bits in the result that are not present in the input.
710 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000711 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000712
Zhou Sheng57e3f732007-03-28 02:19:03 +0000713 APInt MaskIn(Mask);
714 MaskIn.trunc(SrcBitWidth);
715 KnownZero.trunc(SrcBitWidth);
716 KnownOne.trunc(SrcBitWidth);
717 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
719 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000720 KnownZero.zext(BitWidth);
721 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000722 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000723 return;
724 }
725 case Instruction::SExt: {
726 // Compute the bits in the result that are not present in the input.
727 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000728 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000729
Zhou Sheng57e3f732007-03-28 02:19:03 +0000730 APInt MaskIn(Mask);
731 MaskIn.trunc(SrcBitWidth);
732 KnownZero.trunc(SrcBitWidth);
733 KnownOne.trunc(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000736 KnownZero.zext(BitWidth);
737 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000738
739 // If the sign bit of the input is known set or clear, then we know the
740 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000741 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000742 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000743 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000744 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000745 return;
746 }
747 case Instruction::Shl:
748 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
749 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +0000750 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencerd8aad612007-03-25 02:03:12 +0000751 APInt Mask2(Mask.lshr(ShiftAmt));
752 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000753 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000754 KnownZero <<= ShiftAmt;
755 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000756 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000757 return;
758 }
759 break;
760 case Instruction::LShr:
761 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
762 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
763 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000764 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000765
766 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000767 APInt Mask2(Mask.shl(ShiftAmt));
768 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000772 // high bits known zero.
773 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000774 return;
775 }
776 break;
777 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000778 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000779 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
780 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000781 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000782
783 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000784 APInt Mask2(Mask.shl(ShiftAmt));
785 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000786 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
787 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
789
Zhou Sheng57e3f732007-03-28 02:19:03 +0000790 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
791 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000792 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000793 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000794 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000795 return;
796 }
797 break;
798 }
799}
800
Reid Spencerbb5741f2007-03-08 01:52:58 +0000801/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
802/// this predicate to simplify operations downstream. Mask is known to be zero
803/// for bits that V cannot have.
804static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000805 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000806 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
807 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
808 return (KnownZero & Mask) == Mask;
809}
810
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811/// ShrinkDemandedConstant - Check to see if the specified operand of the
812/// specified instruction is a constant integer. If so, check to see if there
813/// are any bits set in the constant that are not demanded. If so, shrink the
814/// constant and return true.
815static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000816 APInt Demanded) {
817 assert(I && "No instruction?");
818 assert(OpNo < I->getNumOperands() && "Operand index too large");
819
820 // If the operand is not a constant integer, nothing to do.
821 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
822 if (!OpC) return false;
823
824 // If there are no bits set that aren't demanded, nothing to do.
825 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
826 if ((~Demanded & OpC->getValue()) == 0)
827 return false;
828
829 // This instruction is producing bits that are not demanded. Shrink the RHS.
830 Demanded &= OpC->getValue();
831 I->setOperand(OpNo, ConstantInt::get(Demanded));
832 return true;
833}
834
Chris Lattneree0f2802006-02-12 02:07:56 +0000835// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
836// set of known zero and one bits, compute the maximum and minimum values that
837// could have the specified known zero and known one bits, returning them in
838// min/max.
839static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000840 const APInt& KnownZero,
841 const APInt& KnownOne,
842 APInt& Min, APInt& Max) {
843 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
844 assert(KnownZero.getBitWidth() == BitWidth &&
845 KnownOne.getBitWidth() == BitWidth &&
846 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
847 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000848 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000849
Chris Lattneree0f2802006-02-12 02:07:56 +0000850 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
851 // bit if it is unknown.
852 Min = KnownOne;
853 Max = KnownOne|UnknownBits;
854
Zhou Shengc2d33092007-03-28 05:15:57 +0000855 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000856 Min.set(BitWidth-1);
857 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000858 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000859}
860
861// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
862// a set of known zero and one bits, compute the maximum and minimum values that
863// could have the specified known zero and known one bits, returning them in
864// min/max.
865static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000866 const APInt& KnownZero,
867 const APInt& KnownOne,
868 APInt& Min,
869 APInt& Max) {
870 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
871 assert(KnownZero.getBitWidth() == BitWidth &&
872 KnownOne.getBitWidth() == BitWidth &&
873 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
874 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000875 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000876
877 // The minimum value is when the unknown bits are all zeros.
878 Min = KnownOne;
879 // The maximum value is when the unknown bits are all ones.
880 Max = KnownOne|UnknownBits;
881}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882
Reid Spencer1791f232007-03-12 17:25:59 +0000883/// SimplifyDemandedBits - This function attempts to replace V with a simpler
884/// value based on the demanded bits. When this function is called, it is known
885/// that only the bits set in DemandedMask of the result of V are ever used
886/// downstream. Consequently, depending on the mask and V, it may be possible
887/// to replace V with a constant or one of its operands. In such cases, this
888/// function does the replacement and returns true. In all other cases, it
889/// returns false after analyzing the expression and setting KnownOne and known
890/// to be one in the expression. KnownZero contains all the bits that are known
891/// to be zero in the expression. These are provided to potentially allow the
892/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
893/// the expression. KnownOne and KnownZero always follow the invariant that
894/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
895/// the bits in KnownOne and KnownZero may only be accurate for those bits set
896/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
897/// and KnownOne must all be the same.
898bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
899 APInt& KnownZero, APInt& KnownOne,
900 unsigned Depth) {
901 assert(V != 0 && "Null pointer of Value???");
902 assert(Depth <= 6 && "Limit Search Depth");
903 uint32_t BitWidth = DemandedMask.getBitWidth();
904 const IntegerType *VTy = cast<IntegerType>(V->getType());
905 assert(VTy->getBitWidth() == BitWidth &&
906 KnownZero.getBitWidth() == BitWidth &&
907 KnownOne.getBitWidth() == BitWidth &&
908 "Value *V, DemandedMask, KnownZero and KnownOne \
909 must have same BitWidth");
910 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
911 // We know all of the bits for a constant!
912 KnownOne = CI->getValue() & DemandedMask;
913 KnownZero = ~KnownOne & DemandedMask;
914 return false;
915 }
916
Zhou Shengb9128442007-03-14 03:21:24 +0000917 KnownZero.clear();
918 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000919 if (!V->hasOneUse()) { // Other users may use these bits.
920 if (Depth != 0) { // Not at the root.
921 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
922 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
923 return false;
924 }
925 // If this is the root being simplified, allow it to have multiple uses,
926 // just set the DemandedMask to all bits.
927 DemandedMask = APInt::getAllOnesValue(BitWidth);
928 } else if (DemandedMask == 0) { // Not demanding any bits from V.
929 if (V != UndefValue::get(VTy))
930 return UpdateValueUsesWith(V, UndefValue::get(VTy));
931 return false;
932 } else if (Depth == 6) { // Limit search depth.
933 return false;
934 }
935
936 Instruction *I = dyn_cast<Instruction>(V);
937 if (!I) return false; // Only analyze instructions.
938
Reid Spencer1791f232007-03-12 17:25:59 +0000939 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
940 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
941 switch (I->getOpcode()) {
942 default: break;
943 case Instruction::And:
944 // If either the LHS or the RHS are Zero, the result is zero.
945 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1))
947 return true;
948 assert((RHSKnownZero & RHSKnownOne) == 0 &&
949 "Bits known to be one AND zero?");
950
951 // If something is known zero on the RHS, the bits aren't demanded on the
952 // LHS.
953 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
954 LHSKnownZero, LHSKnownOne, Depth+1))
955 return true;
956 assert((LHSKnownZero & LHSKnownOne) == 0 &&
957 "Bits known to be one AND zero?");
958
959 // If all of the demanded bits are known 1 on one side, return the other.
960 // These bits cannot contribute to the result of the 'and'.
961 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
962 (DemandedMask & ~LHSKnownZero))
963 return UpdateValueUsesWith(I, I->getOperand(0));
964 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
965 (DemandedMask & ~RHSKnownZero))
966 return UpdateValueUsesWith(I, I->getOperand(1));
967
968 // If all of the demanded bits in the inputs are known zeros, return zero.
969 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
970 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
971
972 // If the RHS is a constant, see if we can simplify it.
973 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
974 return UpdateValueUsesWith(I, I);
975
976 // Output known-1 bits are only known if set in both the LHS & RHS.
977 RHSKnownOne &= LHSKnownOne;
978 // Output known-0 are known to be clear if zero in either the LHS | RHS.
979 RHSKnownZero |= LHSKnownZero;
980 break;
981 case Instruction::Or:
982 // If either the LHS or the RHS are One, the result is One.
983 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984 RHSKnownZero, RHSKnownOne, Depth+1))
985 return true;
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988 // If something is known one on the RHS, the bits aren't demanded on the
989 // LHS.
990 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
991 LHSKnownZero, LHSKnownOne, Depth+1))
992 return true;
993 assert((LHSKnownZero & LHSKnownOne) == 0 &&
994 "Bits known to be one AND zero?");
995
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'or'.
998 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
999 (DemandedMask & ~LHSKnownOne))
1000 return UpdateValueUsesWith(I, I->getOperand(0));
1001 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1002 (DemandedMask & ~RHSKnownOne))
1003 return UpdateValueUsesWith(I, I->getOperand(1));
1004
1005 // If all of the potentially set bits on one side are known to be set on
1006 // the other side, just use the 'other' side.
1007 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1008 (DemandedMask & (~RHSKnownZero)))
1009 return UpdateValueUsesWith(I, I->getOperand(0));
1010 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1011 (DemandedMask & (~LHSKnownZero)))
1012 return UpdateValueUsesWith(I, I->getOperand(1));
1013
1014 // If the RHS is a constant, see if we can simplify it.
1015 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1016 return UpdateValueUsesWith(I, I);
1017
1018 // Output known-0 bits are only known if clear in both the LHS & RHS.
1019 RHSKnownZero &= LHSKnownZero;
1020 // Output known-1 are known to be set if set in either the LHS | RHS.
1021 RHSKnownOne |= LHSKnownOne;
1022 break;
1023 case Instruction::Xor: {
1024 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1025 RHSKnownZero, RHSKnownOne, Depth+1))
1026 return true;
1027 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1028 "Bits known to be one AND zero?");
1029 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1030 LHSKnownZero, LHSKnownOne, Depth+1))
1031 return true;
1032 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1033 "Bits known to be one AND zero?");
1034
1035 // If all of the demanded bits are known zero on one side, return the other.
1036 // These bits cannot contribute to the result of the 'xor'.
1037 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1038 return UpdateValueUsesWith(I, I->getOperand(0));
1039 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1040 return UpdateValueUsesWith(I, I->getOperand(1));
1041
1042 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1043 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1044 (RHSKnownOne & LHSKnownOne);
1045 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1046 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1047 (RHSKnownOne & LHSKnownZero);
1048
1049 // If all of the demanded bits are known to be zero on one side or the
1050 // other, turn this into an *inclusive* or.
1051 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1052 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1053 Instruction *Or =
1054 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1055 I->getName());
1056 InsertNewInstBefore(Or, *I);
1057 return UpdateValueUsesWith(I, Or);
1058 }
1059
1060 // If all of the demanded bits on one side are known, and all of the set
1061 // bits on that side are also known to be set on the other side, turn this
1062 // into an AND, as we know the bits will be cleared.
1063 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1064 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1065 // all known
1066 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1067 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1068 Instruction *And =
1069 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1070 InsertNewInstBefore(And, *I);
1071 return UpdateValueUsesWith(I, And);
1072 }
1073 }
1074
1075 // If the RHS is a constant, see if we can simplify it.
1076 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1077 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1078 return UpdateValueUsesWith(I, I);
1079
1080 RHSKnownZero = KnownZeroOut;
1081 RHSKnownOne = KnownOneOut;
1082 break;
1083 }
1084 case Instruction::Select:
1085 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1086 RHSKnownZero, RHSKnownOne, Depth+1))
1087 return true;
1088 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1089 LHSKnownZero, LHSKnownOne, Depth+1))
1090 return true;
1091 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1092 "Bits known to be one AND zero?");
1093 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1094 "Bits known to be one AND zero?");
1095
1096 // If the operands are constants, see if we can simplify them.
1097 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1098 return UpdateValueUsesWith(I, I);
1099 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1100 return UpdateValueUsesWith(I, I);
1101
1102 // Only known if known in both the LHS and RHS.
1103 RHSKnownOne &= LHSKnownOne;
1104 RHSKnownZero &= LHSKnownZero;
1105 break;
1106 case Instruction::Trunc: {
1107 uint32_t truncBf =
1108 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +00001109 DemandedMask.zext(truncBf);
1110 RHSKnownZero.zext(truncBf);
1111 RHSKnownOne.zext(truncBf);
1112 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1113 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001114 return true;
1115 DemandedMask.trunc(BitWidth);
1116 RHSKnownZero.trunc(BitWidth);
1117 RHSKnownOne.trunc(BitWidth);
1118 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1119 "Bits known to be one AND zero?");
1120 break;
1121 }
1122 case Instruction::BitCast:
1123 if (!I->getOperand(0)->getType()->isInteger())
1124 return false;
1125
1126 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1127 RHSKnownZero, RHSKnownOne, Depth+1))
1128 return true;
1129 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1130 "Bits known to be one AND zero?");
1131 break;
1132 case Instruction::ZExt: {
1133 // Compute the bits in the result that are not present in the input.
1134 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001135 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001136
Zhou Sheng444af492007-03-29 04:45:55 +00001137 DemandedMask.trunc(SrcBitWidth);
1138 RHSKnownZero.trunc(SrcBitWidth);
1139 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001140 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001142 return true;
1143 DemandedMask.zext(BitWidth);
1144 RHSKnownZero.zext(BitWidth);
1145 RHSKnownOne.zext(BitWidth);
1146 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1147 "Bits known to be one AND zero?");
1148 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001149 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001150 break;
1151 }
1152 case Instruction::SExt: {
1153 // Compute the bits in the result that are not present in the input.
1154 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001155 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001156
Reid Spencer1791f232007-03-12 17:25:59 +00001157 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001158 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001159
Zhou Shenga4475572007-03-29 02:26:30 +00001160 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001161 // If any of the sign extended bits are demanded, we know that the sign
1162 // bit is demanded.
1163 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001164 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001165
Zhou Sheng444af492007-03-29 04:45:55 +00001166 InputDemandedBits.trunc(SrcBitWidth);
1167 RHSKnownZero.trunc(SrcBitWidth);
1168 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001169 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1170 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001171 return true;
1172 InputDemandedBits.zext(BitWidth);
1173 RHSKnownZero.zext(BitWidth);
1174 RHSKnownOne.zext(BitWidth);
1175 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1176 "Bits known to be one AND zero?");
1177
1178 // If the sign bit of the input is known set or clear, then we know the
1179 // top bits of the result.
1180
1181 // If the input sign bit is known zero, or if the NewBits are not demanded
1182 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001183 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001184 {
1185 // Convert to ZExt cast
1186 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1187 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001188 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001189 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001190 }
1191 break;
1192 }
1193 case Instruction::Add: {
1194 // Figure out what the input bits are. If the top bits of the and result
1195 // are not demanded, then the add doesn't demand them from its input
1196 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001197 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001198
1199 // If there is a constant on the RHS, there are a variety of xformations
1200 // we can do.
1201 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1202 // If null, this should be simplified elsewhere. Some of the xforms here
1203 // won't work if the RHS is zero.
1204 if (RHS->isZero())
1205 break;
1206
1207 // If the top bit of the output is demanded, demand everything from the
1208 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001209 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001210
1211 // Find information about known zero/one bits in the input.
1212 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1213 LHSKnownZero, LHSKnownOne, Depth+1))
1214 return true;
1215
1216 // If the RHS of the add has bits set that can't affect the input, reduce
1217 // the constant.
1218 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1219 return UpdateValueUsesWith(I, I);
1220
1221 // Avoid excess work.
1222 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1223 break;
1224
1225 // Turn it into OR if input bits are zero.
1226 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1227 Instruction *Or =
1228 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1229 I->getName());
1230 InsertNewInstBefore(Or, *I);
1231 return UpdateValueUsesWith(I, Or);
1232 }
1233
1234 // We can say something about the output known-zero and known-one bits,
1235 // depending on potential carries from the input constant and the
1236 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1237 // bits set and the RHS constant is 0x01001, then we know we have a known
1238 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1239
1240 // To compute this, we first compute the potential carry bits. These are
1241 // the bits which may be modified. I'm not aware of a better way to do
1242 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001243 const APInt& RHSVal = RHS->getValue();
1244 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001245
1246 // Now that we know which bits have carries, compute the known-1/0 sets.
1247
1248 // Bits are known one if they are known zero in one operand and one in the
1249 // other, and there is no input carry.
1250 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1251 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1252
1253 // Bits are known zero if they are known zero in both operands and there
1254 // is no input carry.
1255 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1256 } else {
1257 // If the high-bits of this ADD are not demanded, then it does not demand
1258 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001259 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001260 // Right fill the mask of bits for this ADD to demand the most
1261 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001262 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001263 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1265 return true;
1266 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1267 LHSKnownZero, LHSKnownOne, Depth+1))
1268 return true;
1269 }
1270 }
1271 break;
1272 }
1273 case Instruction::Sub:
1274 // If the high-bits of this SUB are not demanded, then it does not demand
1275 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001276 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001277 // Right fill the mask of bits for this SUB to demand the most
1278 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001279 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001280 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001281 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1282 LHSKnownZero, LHSKnownOne, Depth+1))
1283 return true;
1284 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1285 LHSKnownZero, LHSKnownOne, Depth+1))
1286 return true;
1287 }
1288 break;
1289 case Instruction::Shl:
1290 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001291 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001292 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1293 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001294 RHSKnownZero, RHSKnownOne, Depth+1))
1295 return true;
1296 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1297 "Bits known to be one AND zero?");
1298 RHSKnownZero <<= ShiftAmt;
1299 RHSKnownOne <<= ShiftAmt;
1300 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001301 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001302 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001303 }
1304 break;
1305 case Instruction::LShr:
1306 // For a logical shift right
1307 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001308 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001309
Reid Spencer1791f232007-03-12 17:25:59 +00001310 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001311 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1312 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001313 RHSKnownZero, RHSKnownOne, Depth+1))
1314 return true;
1315 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1316 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001317 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001319 if (ShiftAmt) {
1320 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001321 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001322 RHSKnownZero |= HighBits; // high bits known zero.
1323 }
Reid Spencer1791f232007-03-12 17:25:59 +00001324 }
1325 break;
1326 case Instruction::AShr:
1327 // If this is an arithmetic shift right and only the low-bit is set, we can
1328 // always convert this into a logical shr, even if the shift amount is
1329 // variable. The low bit of the shift cannot be an input sign bit unless
1330 // the shift amount is >= the size of the datatype, which is undefined.
1331 if (DemandedMask == 1) {
1332 // Perform the logical shift right.
1333 Value *NewVal = BinaryOperator::createLShr(
1334 I->getOperand(0), I->getOperand(1), I->getName());
1335 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1336 return UpdateValueUsesWith(I, NewVal);
1337 }
1338
1339 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001340 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001341
Reid Spencer1791f232007-03-12 17:25:59 +00001342 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001343 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001344 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001345 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001346 RHSKnownZero, RHSKnownOne, Depth+1))
1347 return true;
1348 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001351 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001352 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1353 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1354
1355 // Handle the sign bits.
1356 APInt SignBit(APInt::getSignBit(BitWidth));
1357 // Adjust to where it is now in the mask.
1358 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1359
1360 // If the input sign bit is known to be zero, or if none of the top bits
1361 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001362 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001363 (HighBits & ~DemandedMask) == HighBits) {
1364 // Perform the logical shift right.
1365 Value *NewVal = BinaryOperator::createLShr(
1366 I->getOperand(0), SA, I->getName());
1367 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1368 return UpdateValueUsesWith(I, NewVal);
1369 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1370 RHSKnownOne |= HighBits;
1371 }
1372 }
1373 break;
1374 }
1375
1376 // If the client is only demanding bits that we know, return the known
1377 // constant.
1378 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1379 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1380 return false;
1381}
1382
Chris Lattner2deeaea2006-10-05 06:55:50 +00001383
1384/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1385/// 64 or fewer elements. DemandedElts contains the set of elements that are
1386/// actually used by the caller. This method analyzes which elements of the
1387/// operand are undef and returns that information in UndefElts.
1388///
1389/// If the information about demanded elements can be used to simplify the
1390/// operation, the operation is simplified, then the resultant value is
1391/// returned. This returns null if no change was made.
1392Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1393 uint64_t &UndefElts,
1394 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001395 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001396 assert(VWidth <= 64 && "Vector too wide to analyze!");
1397 uint64_t EltMask = ~0ULL >> (64-VWidth);
1398 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1399 "Invalid DemandedElts!");
1400
1401 if (isa<UndefValue>(V)) {
1402 // If the entire vector is undefined, just return this info.
1403 UndefElts = EltMask;
1404 return 0;
1405 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1406 UndefElts = EltMask;
1407 return UndefValue::get(V->getType());
1408 }
1409
1410 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001411 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1412 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001413 Constant *Undef = UndefValue::get(EltTy);
1414
1415 std::vector<Constant*> Elts;
1416 for (unsigned i = 0; i != VWidth; ++i)
1417 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1418 Elts.push_back(Undef);
1419 UndefElts |= (1ULL << i);
1420 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1421 Elts.push_back(Undef);
1422 UndefElts |= (1ULL << i);
1423 } else { // Otherwise, defined.
1424 Elts.push_back(CP->getOperand(i));
1425 }
1426
1427 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001428 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001429 return NewCP != CP ? NewCP : 0;
1430 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001431 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001432 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001433 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001434 Constant *Zero = Constant::getNullValue(EltTy);
1435 Constant *Undef = UndefValue::get(EltTy);
1436 std::vector<Constant*> Elts;
1437 for (unsigned i = 0; i != VWidth; ++i)
1438 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1439 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001440 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001441 }
1442
1443 if (!V->hasOneUse()) { // Other users may use these bits.
1444 if (Depth != 0) { // Not at the root.
1445 // TODO: Just compute the UndefElts information recursively.
1446 return false;
1447 }
1448 return false;
1449 } else if (Depth == 10) { // Limit search depth.
1450 return false;
1451 }
1452
1453 Instruction *I = dyn_cast<Instruction>(V);
1454 if (!I) return false; // Only analyze instructions.
1455
1456 bool MadeChange = false;
1457 uint64_t UndefElts2;
1458 Value *TmpV;
1459 switch (I->getOpcode()) {
1460 default: break;
1461
1462 case Instruction::InsertElement: {
1463 // If this is a variable index, we don't know which element it overwrites.
1464 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001465 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001466 if (Idx == 0) {
1467 // Note that we can't propagate undef elt info, because we don't know
1468 // which elt is getting updated.
1469 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1470 UndefElts2, Depth+1);
1471 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1472 break;
1473 }
1474
1475 // If this is inserting an element that isn't demanded, remove this
1476 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001477 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001478 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1479 return AddSoonDeadInstToWorklist(*I, 0);
1480
1481 // Otherwise, the element inserted overwrites whatever was there, so the
1482 // input demanded set is simpler than the output set.
1483 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1484 DemandedElts & ~(1ULL << IdxNo),
1485 UndefElts, Depth+1);
1486 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1487
1488 // The inserted element is defined.
1489 UndefElts |= 1ULL << IdxNo;
1490 break;
1491 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001492 case Instruction::BitCast: {
1493 // Packed->packed casts only.
1494 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1495 if (!VTy) break;
1496 unsigned InVWidth = VTy->getNumElements();
1497 uint64_t InputDemandedElts = 0;
1498 unsigned Ratio;
1499
1500 if (VWidth == InVWidth) {
1501 // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1502 // elements as are demanded of us.
1503 Ratio = 1;
1504 InputDemandedElts = DemandedElts;
1505 } else if (VWidth > InVWidth) {
1506 // Untested so far.
1507 break;
1508
1509 // If there are more elements in the result than there are in the source,
1510 // then an input element is live if any of the corresponding output
1511 // elements are live.
1512 Ratio = VWidth/InVWidth;
1513 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1514 if (DemandedElts & (1ULL << OutIdx))
1515 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1516 }
1517 } else {
1518 // Untested so far.
1519 break;
1520
1521 // If there are more elements in the source than there are in the result,
1522 // then an input element is live if the corresponding output element is
1523 // live.
1524 Ratio = InVWidth/VWidth;
1525 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1526 if (DemandedElts & (1ULL << InIdx/Ratio))
1527 InputDemandedElts |= 1ULL << InIdx;
1528 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001529
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001530 // div/rem demand all inputs, because they don't want divide by zero.
1531 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1532 UndefElts2, Depth+1);
1533 if (TmpV) {
1534 I->setOperand(0, TmpV);
1535 MadeChange = true;
1536 }
1537
1538 UndefElts = UndefElts2;
1539 if (VWidth > InVWidth) {
1540 assert(0 && "Unimp");
1541 // If there are more elements in the result than there are in the source,
1542 // then an output element is undef if the corresponding input element is
1543 // undef.
1544 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1545 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1546 UndefElts |= 1ULL << OutIdx;
1547 } else if (VWidth < InVWidth) {
1548 assert(0 && "Unimp");
1549 // If there are more elements in the source than there are in the result,
1550 // then a result element is undef if all of the corresponding input
1551 // elements are undef.
1552 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1553 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1554 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1555 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1556 }
1557 break;
1558 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001559 case Instruction::And:
1560 case Instruction::Or:
1561 case Instruction::Xor:
1562 case Instruction::Add:
1563 case Instruction::Sub:
1564 case Instruction::Mul:
1565 // div/rem demand all inputs, because they don't want divide by zero.
1566 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1567 UndefElts, Depth+1);
1568 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1569 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1570 UndefElts2, Depth+1);
1571 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1572
1573 // Output elements are undefined if both are undefined. Consider things
1574 // like undef&0. The result is known zero, not undef.
1575 UndefElts &= UndefElts2;
1576 break;
1577
1578 case Instruction::Call: {
1579 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1580 if (!II) break;
1581 switch (II->getIntrinsicID()) {
1582 default: break;
1583
1584 // Binary vector operations that work column-wise. A dest element is a
1585 // function of the corresponding input elements from the two inputs.
1586 case Intrinsic::x86_sse_sub_ss:
1587 case Intrinsic::x86_sse_mul_ss:
1588 case Intrinsic::x86_sse_min_ss:
1589 case Intrinsic::x86_sse_max_ss:
1590 case Intrinsic::x86_sse2_sub_sd:
1591 case Intrinsic::x86_sse2_mul_sd:
1592 case Intrinsic::x86_sse2_min_sd:
1593 case Intrinsic::x86_sse2_max_sd:
1594 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1595 UndefElts, Depth+1);
1596 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1597 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1598 UndefElts2, Depth+1);
1599 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1600
1601 // If only the low elt is demanded and this is a scalarizable intrinsic,
1602 // scalarize it now.
1603 if (DemandedElts == 1) {
1604 switch (II->getIntrinsicID()) {
1605 default: break;
1606 case Intrinsic::x86_sse_sub_ss:
1607 case Intrinsic::x86_sse_mul_ss:
1608 case Intrinsic::x86_sse2_sub_sd:
1609 case Intrinsic::x86_sse2_mul_sd:
1610 // TODO: Lower MIN/MAX/ABS/etc
1611 Value *LHS = II->getOperand(1);
1612 Value *RHS = II->getOperand(2);
1613 // Extract the element as scalars.
1614 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1615 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1616
1617 switch (II->getIntrinsicID()) {
1618 default: assert(0 && "Case stmts out of sync!");
1619 case Intrinsic::x86_sse_sub_ss:
1620 case Intrinsic::x86_sse2_sub_sd:
1621 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1622 II->getName()), *II);
1623 break;
1624 case Intrinsic::x86_sse_mul_ss:
1625 case Intrinsic::x86_sse2_mul_sd:
1626 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1627 II->getName()), *II);
1628 break;
1629 }
1630
1631 Instruction *New =
1632 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1633 II->getName());
1634 InsertNewInstBefore(New, *II);
1635 AddSoonDeadInstToWorklist(*II, 0);
1636 return New;
1637 }
1638 }
1639
1640 // Output elements are undefined if both are undefined. Consider things
1641 // like undef&0. The result is known zero, not undef.
1642 UndefElts &= UndefElts2;
1643 break;
1644 }
1645 break;
1646 }
1647 }
1648 return MadeChange ? I : 0;
1649}
1650
Reid Spencer266e42b2006-12-23 06:05:41 +00001651/// @returns true if the specified compare instruction is
1652/// true when both operands are equal...
1653/// @brief Determine if the ICmpInst returns true if both operands are equal
1654static bool isTrueWhenEqual(ICmpInst &ICI) {
1655 ICmpInst::Predicate pred = ICI.getPredicate();
1656 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1657 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1658 pred == ICmpInst::ICMP_SLE;
1659}
1660
Chris Lattnerb8b97502003-08-13 19:01:45 +00001661/// AssociativeOpt - Perform an optimization on an associative operator. This
1662/// function is designed to check a chain of associative operators for a
1663/// potential to apply a certain optimization. Since the optimization may be
1664/// applicable if the expression was reassociated, this checks the chain, then
1665/// reassociates the expression as necessary to expose the optimization
1666/// opportunity. This makes use of a special Functor, which must define
1667/// 'shouldApply' and 'apply' methods.
1668///
1669template<typename Functor>
1670Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1671 unsigned Opcode = Root.getOpcode();
1672 Value *LHS = Root.getOperand(0);
1673
1674 // Quick check, see if the immediate LHS matches...
1675 if (F.shouldApply(LHS))
1676 return F.apply(Root);
1677
1678 // Otherwise, if the LHS is not of the same opcode as the root, return.
1679 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001680 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001681 // Should we apply this transform to the RHS?
1682 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1683
1684 // If not to the RHS, check to see if we should apply to the LHS...
1685 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1686 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1687 ShouldApply = true;
1688 }
1689
1690 // If the functor wants to apply the optimization to the RHS of LHSI,
1691 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1692 if (ShouldApply) {
1693 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001694
Chris Lattnerb8b97502003-08-13 19:01:45 +00001695 // Now all of the instructions are in the current basic block, go ahead
1696 // and perform the reassociation.
1697 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1698
1699 // First move the selected RHS to the LHS of the root...
1700 Root.setOperand(0, LHSI->getOperand(1));
1701
1702 // Make what used to be the LHS of the root be the user of the root...
1703 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001704 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001705 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1706 return 0;
1707 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001708 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001709 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001710 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1711 BasicBlock::iterator ARI = &Root; ++ARI;
1712 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1713 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001714
1715 // Now propagate the ExtraOperand down the chain of instructions until we
1716 // get to LHSI.
1717 while (TmpLHSI != LHSI) {
1718 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001719 // Move the instruction to immediately before the chain we are
1720 // constructing to avoid breaking dominance properties.
1721 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1722 BB->getInstList().insert(ARI, NextLHSI);
1723 ARI = NextLHSI;
1724
Chris Lattnerb8b97502003-08-13 19:01:45 +00001725 Value *NextOp = NextLHSI->getOperand(1);
1726 NextLHSI->setOperand(1, ExtraOperand);
1727 TmpLHSI = NextLHSI;
1728 ExtraOperand = NextOp;
1729 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001730
Chris Lattnerb8b97502003-08-13 19:01:45 +00001731 // Now that the instructions are reassociated, have the functor perform
1732 // the transformation...
1733 return F.apply(Root);
1734 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001735
Chris Lattnerb8b97502003-08-13 19:01:45 +00001736 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1737 }
1738 return 0;
1739}
1740
1741
1742// AddRHS - Implements: X + X --> X << 1
1743struct AddRHS {
1744 Value *RHS;
1745 AddRHS(Value *rhs) : RHS(rhs) {}
1746 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1747 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001748 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001749 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001750 }
1751};
1752
1753// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1754// iff C1&C2 == 0
1755struct AddMaskingAnd {
1756 Constant *C2;
1757 AddMaskingAnd(Constant *c) : C2(c) {}
1758 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001759 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001760 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001761 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001762 }
1763 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001764 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001765 }
1766};
1767
Chris Lattner86102b82005-01-01 16:22:27 +00001768static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001769 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001770 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001771 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001772 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001773
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001774 return IC->InsertNewInstBefore(CastInst::create(
1775 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001776 }
1777
Chris Lattner183b3362004-04-09 19:05:30 +00001778 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001779 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1780 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001781
Chris Lattner183b3362004-04-09 19:05:30 +00001782 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1783 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001784 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1785 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001786 }
1787
1788 Value *Op0 = SO, *Op1 = ConstOperand;
1789 if (!ConstIsRHS)
1790 std::swap(Op0, Op1);
1791 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001792 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1793 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001794 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1795 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1796 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001797 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001798 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001799 abort();
1800 }
Chris Lattner86102b82005-01-01 16:22:27 +00001801 return IC->InsertNewInstBefore(New, I);
1802}
1803
1804// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1805// constant as the other operand, try to fold the binary operator into the
1806// select arguments. This also works for Cast instructions, which obviously do
1807// not have a second operand.
1808static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1809 InstCombiner *IC) {
1810 // Don't modify shared select instructions
1811 if (!SI->hasOneUse()) return 0;
1812 Value *TV = SI->getOperand(1);
1813 Value *FV = SI->getOperand(2);
1814
1815 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001816 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001817 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001818
Chris Lattner86102b82005-01-01 16:22:27 +00001819 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1820 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1821
1822 return new SelectInst(SI->getCondition(), SelectTrueVal,
1823 SelectFalseVal);
1824 }
1825 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001826}
1827
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001828
1829/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1830/// node as operand #0, see if we can fold the instruction into the PHI (which
1831/// is only possible if all operands to the PHI are constants).
1832Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1833 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001834 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001835 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001836
Chris Lattner04689872006-09-09 22:02:56 +00001837 // Check to see if all of the operands of the PHI are constants. If there is
1838 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001839 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001840 BasicBlock *NonConstBB = 0;
1841 for (unsigned i = 0; i != NumPHIValues; ++i)
1842 if (!isa<Constant>(PN->getIncomingValue(i))) {
1843 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001844 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001845 NonConstBB = PN->getIncomingBlock(i);
1846
1847 // If the incoming non-constant value is in I's block, we have an infinite
1848 // loop.
1849 if (NonConstBB == I.getParent())
1850 return 0;
1851 }
1852
1853 // If there is exactly one non-constant value, we can insert a copy of the
1854 // operation in that block. However, if this is a critical edge, we would be
1855 // inserting the computation one some other paths (e.g. inside a loop). Only
1856 // do this if the pred block is unconditionally branching into the phi block.
1857 if (NonConstBB) {
1858 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1859 if (!BI || !BI->isUnconditional()) return 0;
1860 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001861
1862 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001863 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001864 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001865 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001866 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001867
1868 // Next, add all of the operands to the PHI.
1869 if (I.getNumOperands() == 2) {
1870 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001871 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001872 Value *InV;
1873 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001874 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1875 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1876 else
1877 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001878 } else {
1879 assert(PN->getIncomingBlock(i) == NonConstBB);
1880 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1881 InV = BinaryOperator::create(BO->getOpcode(),
1882 PN->getIncomingValue(i), C, "phitmp",
1883 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001884 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1885 InV = CmpInst::create(CI->getOpcode(),
1886 CI->getPredicate(),
1887 PN->getIncomingValue(i), C, "phitmp",
1888 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001889 else
1890 assert(0 && "Unknown binop!");
1891
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001892 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001893 }
1894 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001895 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001896 } else {
1897 CastInst *CI = cast<CastInst>(&I);
1898 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001899 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001900 Value *InV;
1901 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001902 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001903 } else {
1904 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001905 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1906 I.getType(), "phitmp",
1907 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001908 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001909 }
1910 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001911 }
1912 }
1913 return ReplaceInstUsesWith(I, NewPN);
1914}
1915
Chris Lattner113f4f42002-06-25 16:13:24 +00001916Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001917 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001918 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001919
Chris Lattnercf4a9962004-04-10 22:01:55 +00001920 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001921 // X + undef -> undef
1922 if (isa<UndefValue>(RHS))
1923 return ReplaceInstUsesWith(I, RHS);
1924
Chris Lattnercf4a9962004-04-10 22:01:55 +00001925 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001926 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001927 if (RHSC->isNullValue())
1928 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001929 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1930 if (CFP->isExactlyValue(-0.0))
1931 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001932 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001933
Chris Lattnercf4a9962004-04-10 22:01:55 +00001934 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001935 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001936 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00001937 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00001938 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001939 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001940
1941 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1942 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001943 if (!isa<VectorType>(I.getType())) {
1944 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1945 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1946 KnownZero, KnownOne))
1947 return &I;
1948 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001949 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001950
1951 if (isa<PHINode>(LHS))
1952 if (Instruction *NV = FoldOpIntoPhi(I))
1953 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001954
Chris Lattner330628a2006-01-06 17:59:59 +00001955 ConstantInt *XorRHS = 0;
1956 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001957 if (isa<ConstantInt>(RHSC) &&
1958 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00001959 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001960 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00001961
Zhou Sheng56cda952007-04-02 08:20:41 +00001962 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00001963 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1964 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001965 do {
1966 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001967 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1968 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001969 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1970 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001971 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00001972 if (!MaskedValueIsZero(XorLHS,
1973 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001974 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001975 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001976 }
1977 }
1978 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001979 C0080Val = APIntOps::lshr(C0080Val, Size);
1980 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1981 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001982
Reid Spencera5c18bf2007-03-28 01:36:16 +00001983 // FIXME: This shouldn't be necessary. When the backends can handle types
1984 // with funny bit widths then this whole cascade of if statements should
1985 // be removed. It is just here to get the size of the "middle" type back
1986 // up to something that the back ends can handle.
1987 const Type *MiddleType = 0;
1988 switch (Size) {
1989 default: break;
1990 case 32: MiddleType = Type::Int32Ty; break;
1991 case 16: MiddleType = Type::Int16Ty; break;
1992 case 8: MiddleType = Type::Int8Ty; break;
1993 }
1994 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001995 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001996 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001997 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001998 }
1999 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002000 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002001
Chris Lattnerb8b97502003-08-13 19:01:45 +00002002 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002003 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002004 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002005
2006 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2007 if (RHSI->getOpcode() == Instruction::Sub)
2008 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2009 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2010 }
2011 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2012 if (LHSI->getOpcode() == Instruction::Sub)
2013 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2014 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2015 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002016 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002017
Chris Lattner147e9752002-05-08 22:46:53 +00002018 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002019 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002020 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002021
2022 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002023 if (!isa<Constant>(RHS))
2024 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002025 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002026
Misha Brukmanb1c93172005-04-21 23:48:37 +00002027
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002028 ConstantInt *C2;
2029 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2030 if (X == RHS) // X*C + X --> X * (C+1)
2031 return BinaryOperator::createMul(RHS, AddOne(C2));
2032
2033 // X*C1 + X*C2 --> X * (C1+C2)
2034 ConstantInt *C1;
2035 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00002036 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002037 }
2038
2039 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002040 if (dyn_castFoldableMul(RHS, C2) == LHS)
2041 return BinaryOperator::createMul(LHS, AddOne(C2));
2042
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002043 // X + ~X --> -1 since ~X = -X-1
2044 if (dyn_castNotVal(LHS) == RHS ||
2045 dyn_castNotVal(RHS) == LHS)
2046 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2047
Chris Lattner57c8d992003-02-18 19:57:07 +00002048
Chris Lattnerb8b97502003-08-13 19:01:45 +00002049 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002050 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002051 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2052 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002053
Chris Lattnerb9cde762003-10-02 15:11:26 +00002054 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002055 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002056 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2057 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002058
Chris Lattnerbff91d92004-10-08 05:07:56 +00002059 // (X & FF00) + xx00 -> (X+xx00) & FF00
2060 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002061 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002062 if (Anded == CRHS) {
2063 // See if all bits from the first bit set in the Add RHS up are included
2064 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002065 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002066
2067 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002068 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002069
2070 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002071 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002072
Chris Lattnerbff91d92004-10-08 05:07:56 +00002073 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2074 // Okay, the xform is safe. Insert the new add pronto.
2075 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2076 LHS->getName()), I);
2077 return BinaryOperator::createAnd(NewAdd, C2);
2078 }
2079 }
2080 }
2081
Chris Lattnerd4252a72004-07-30 07:50:03 +00002082 // Try to fold constant add into select arguments.
2083 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002084 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002085 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002086 }
2087
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002088 // add (cast *A to intptrtype) B ->
2089 // cast (GEP (cast *A to sbyte*) B) ->
2090 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002091 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002092 CastInst *CI = dyn_cast<CastInst>(LHS);
2093 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002094 if (!CI) {
2095 CI = dyn_cast<CastInst>(RHS);
2096 Other = LHS;
2097 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002098 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002099 (CI->getType()->getPrimitiveSizeInBits() ==
2100 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002101 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002102 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002103 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002104 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002105 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002106 }
2107 }
2108
Chris Lattner113f4f42002-06-25 16:13:24 +00002109 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002110}
2111
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002112// isSignBit - Return true if the value represented by the constant only has the
2113// highest order bit set.
2114static bool isSignBit(ConstantInt *CI) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002115 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002116 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002117}
2118
Chris Lattner113f4f42002-06-25 16:13:24 +00002119Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002121
Chris Lattnere6794492002-08-12 21:17:25 +00002122 if (Op0 == Op1) // sub X, X -> 0
2123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002124
Chris Lattnere6794492002-08-12 21:17:25 +00002125 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002126 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002127 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002128
Chris Lattner81a7a232004-10-16 18:11:37 +00002129 if (isa<UndefValue>(Op0))
2130 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2131 if (isa<UndefValue>(Op1))
2132 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2133
Chris Lattner8f2f5982003-11-05 01:06:05 +00002134 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2135 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 if (C->isAllOnesValue())
2137 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002138
Chris Lattner8f2f5982003-11-05 01:06:05 +00002139 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002140 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002141 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002142 return BinaryOperator::createAdd(X, AddOne(C));
2143
Chris Lattner27df1db2007-01-15 07:02:54 +00002144 // -(X >>u 31) -> (X >>s 31)
2145 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002146 if (C->isZero()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002147 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002148 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002149 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002150 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002151 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002152 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002153 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002154 return BinaryOperator::create(Instruction::AShr,
2155 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002156 }
2157 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002158 }
2159 else if (SI->getOpcode() == Instruction::AShr) {
2160 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2161 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002162 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002163 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002164 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002165 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002166 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002167 }
2168 }
2169 }
Chris Lattner022167f2004-03-13 00:11:49 +00002170 }
Chris Lattner183b3362004-04-09 19:05:30 +00002171
2172 // Try to fold constant sub into select arguments.
2173 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002174 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002175 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002176
2177 if (isa<PHINode>(Op0))
2178 if (Instruction *NV = FoldOpIntoPhi(I))
2179 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002180 }
2181
Chris Lattnera9be4492005-04-07 16:15:25 +00002182 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2183 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002184 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002185 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002186 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002187 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002188 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002189 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2190 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2191 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002192 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002193 Op1I->getOperand(0));
2194 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002195 }
2196
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002197 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002198 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2199 // is not used by anyone else...
2200 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002201 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002202 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002203 // Swap the two operands of the subexpr...
2204 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2205 Op1I->setOperand(0, IIOp1);
2206 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002207
Chris Lattner3082c5a2003-02-18 19:28:33 +00002208 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002209 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002210 }
2211
2212 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2213 //
2214 if (Op1I->getOpcode() == Instruction::And &&
2215 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2216 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2217
Chris Lattner396dbfe2004-06-09 05:08:07 +00002218 Value *NewNot =
2219 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002220 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002221 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002222
Reid Spencer3c514952006-10-16 23:08:08 +00002223 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002224 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002225 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002226 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002227 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002228 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002229 ConstantExpr::getNeg(DivRHS));
2230
Chris Lattner57c8d992003-02-18 19:57:07 +00002231 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002232 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002233 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002234 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002235 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002236 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002237 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002238 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002239
Chris Lattner7a002fe2006-12-02 00:13:08 +00002240 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002241 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2242 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002243 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2244 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2245 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2246 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002247 } else if (Op0I->getOpcode() == Instruction::Sub) {
2248 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2249 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002250 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002251
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002252 ConstantInt *C1;
2253 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002254 if (X == Op1) // X*C - X --> X * (C-1)
2255 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002256
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002257 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2258 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002259 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002260 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002261 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002262}
2263
Reid Spencer266e42b2006-12-23 06:05:41 +00002264/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002265/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002266static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2267 switch (pred) {
2268 case ICmpInst::ICMP_SLT:
2269 // True if LHS s< RHS and RHS == 0
2270 return RHS->isNullValue();
2271 case ICmpInst::ICMP_SLE:
2272 // True if LHS s<= RHS and RHS == -1
2273 return RHS->isAllOnesValue();
2274 case ICmpInst::ICMP_UGE:
2275 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002276 return RHS->getValue() ==
2277 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002278 case ICmpInst::ICMP_UGT:
2279 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002280 return RHS->getValue() ==
2281 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002282 default:
2283 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002284 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002285}
2286
Chris Lattner113f4f42002-06-25 16:13:24 +00002287Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002288 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002289 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002290
Chris Lattner81a7a232004-10-16 18:11:37 +00002291 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2292 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2293
Chris Lattnere6794492002-08-12 21:17:25 +00002294 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002295 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2296 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002297
2298 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002299 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002300 if (SI->getOpcode() == Instruction::Shl)
2301 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002302 return BinaryOperator::createMul(SI->getOperand(0),
2303 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002304
Chris Lattnercce81be2003-09-11 22:24:54 +00002305 if (CI->isNullValue())
2306 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2307 if (CI->equalsInt(1)) // X * 1 == X
2308 return ReplaceInstUsesWith(I, Op0);
2309 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002310 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002311
Zhou Sheng4961cf12007-03-29 01:57:21 +00002312 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002313 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002314 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002315 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002316 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002317 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002318 if (Op1F->isNullValue())
2319 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002320
Chris Lattner3082c5a2003-02-18 19:28:33 +00002321 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2322 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2323 if (Op1F->getValue() == 1.0)
2324 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2325 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002326
2327 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2328 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2329 isa<ConstantInt>(Op0I->getOperand(1))) {
2330 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2331 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2332 Op1, "tmp");
2333 InsertNewInstBefore(Add, I);
2334 Value *C1C2 = ConstantExpr::getMul(Op1,
2335 cast<Constant>(Op0I->getOperand(1)));
2336 return BinaryOperator::createAdd(Add, C1C2);
2337
2338 }
Chris Lattner183b3362004-04-09 19:05:30 +00002339
2340 // Try to fold constant mul into select arguments.
2341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002342 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002343 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002344
2345 if (isa<PHINode>(Op0))
2346 if (Instruction *NV = FoldOpIntoPhi(I))
2347 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002348 }
2349
Chris Lattner934a64cf2003-03-10 23:23:04 +00002350 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2351 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002352 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002353
Chris Lattner2635b522004-02-23 05:39:21 +00002354 // If one of the operands of the multiply is a cast from a boolean value, then
2355 // we know the bool is either zero or one, so this is a 'masking' multiply.
2356 // See if we can simplify things based on how the boolean was originally
2357 // formed.
2358 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002359 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002360 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002361 BoolCast = CI;
2362 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002363 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002364 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002365 BoolCast = CI;
2366 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002367 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002368 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2369 const Type *SCOpTy = SCIOp0->getType();
2370
Reid Spencer266e42b2006-12-23 06:05:41 +00002371 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002372 // multiply into a shift/and combination.
2373 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002374 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002375 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002376 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002377 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002378 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002379 InsertNewInstBefore(
2380 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002381 BoolCast->getOperand(0)->getName()+
2382 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002383
2384 // If the multiply type is not the same as the source type, sign extend
2385 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002386 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002387 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2388 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002389 Instruction::CastOps opcode =
2390 (SrcBits == DstBits ? Instruction::BitCast :
2391 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2392 V = InsertCastBefore(opcode, V, I.getType(), I);
2393 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002394
Chris Lattner2635b522004-02-23 05:39:21 +00002395 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002396 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002397 }
2398 }
2399 }
2400
Chris Lattner113f4f42002-06-25 16:13:24 +00002401 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002402}
2403
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002404/// This function implements the transforms on div instructions that work
2405/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2406/// used by the visitors to those instructions.
2407/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002408Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002410
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002411 // undef / X -> 0
2412 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002413 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002414
2415 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002416 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002417 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002418
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002419 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002420 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2421 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002422 // same basic block, then we replace the select with Y, and the condition
2423 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002424 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002425 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002426 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2427 if (ST->isNullValue()) {
2428 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2429 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002430 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002431 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2432 I.setOperand(1, SI->getOperand(2));
2433 else
2434 UpdateValueUsesWith(SI, SI->getOperand(2));
2435 return &I;
2436 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002437
Chris Lattnerd79dc792006-09-09 20:26:32 +00002438 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2439 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2440 if (ST->isNullValue()) {
2441 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2442 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002443 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002444 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2445 I.setOperand(1, SI->getOperand(1));
2446 else
2447 UpdateValueUsesWith(SI, SI->getOperand(1));
2448 return &I;
2449 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002450 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002451
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002452 return 0;
2453}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002454
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002455/// This function implements the transforms common to both integer division
2456/// instructions (udiv and sdiv). It is called by the visitors to those integer
2457/// division instructions.
2458/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002459Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002460 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2461
2462 if (Instruction *Common = commonDivTransforms(I))
2463 return Common;
2464
2465 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2466 // div X, 1 == X
2467 if (RHS->equalsInt(1))
2468 return ReplaceInstUsesWith(I, Op0);
2469
2470 // (X / C1) / C2 -> X / (C1*C2)
2471 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2472 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2473 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2474 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002475 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002476 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002477
Reid Spencer6d392062007-03-23 20:05:17 +00002478 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002479 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2481 return R;
2482 if (isa<PHINode>(Op0))
2483 if (Instruction *NV = FoldOpIntoPhi(I))
2484 return NV;
2485 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002486 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002487
Chris Lattner3082c5a2003-02-18 19:28:33 +00002488 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002489 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002490 if (LHS->equalsInt(0))
2491 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2492
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002493 return 0;
2494}
2495
2496Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2497 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2498
2499 // Handle the integer div common cases
2500 if (Instruction *Common = commonIDivTransforms(I))
2501 return Common;
2502
2503 // X udiv C^2 -> X >> C
2504 // Check to see if this is an unsigned division with an exact power of 2,
2505 // if so, convert to a right shift.
2506 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002507 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002508 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002509 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002510 }
2511
2512 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002513 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002514 if (RHSI->getOpcode() == Instruction::Shl &&
2515 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002516 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002517 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002518 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002519 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002520 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002521 Constant *C2V = ConstantInt::get(NTy, C2);
2522 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002523 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002524 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002525 }
2526 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002527 }
2528
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002529 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2530 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002531 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002532 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002533 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002534 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002535 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002536 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002537 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002538 // Construct the "on true" case of the select
2539 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2540 Instruction *TSI = BinaryOperator::createLShr(
2541 Op0, TC, SI->getName()+".t");
2542 TSI = InsertNewInstBefore(TSI, I);
2543
2544 // Construct the "on false" case of the select
2545 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2546 Instruction *FSI = BinaryOperator::createLShr(
2547 Op0, FC, SI->getName()+".f");
2548 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002549
Reid Spencer3939b1a2007-03-05 23:36:13 +00002550 // construct the select instruction and return it.
2551 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002552 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002553 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002554 return 0;
2555}
2556
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002557Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2558 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2559
2560 // Handle the integer div common cases
2561 if (Instruction *Common = commonIDivTransforms(I))
2562 return Common;
2563
2564 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2565 // sdiv X, -1 == -X
2566 if (RHS->isAllOnesValue())
2567 return BinaryOperator::createNeg(Op0);
2568
2569 // -X/C -> X/-C
2570 if (Value *LHSNeg = dyn_castNegVal(Op0))
2571 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2572 }
2573
2574 // If the sign bits of both operands are zero (i.e. we can prove they are
2575 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002576 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002577 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002578 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2579 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2580 }
2581 }
2582
2583 return 0;
2584}
2585
2586Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2587 return commonDivTransforms(I);
2588}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002589
Chris Lattner85dda9a2006-03-02 06:50:58 +00002590/// GetFactor - If we can prove that the specified value is at least a multiple
2591/// of some factor, return that factor.
2592static Constant *GetFactor(Value *V) {
2593 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2594 return CI;
2595
2596 // Unless we can be tricky, we know this is a multiple of 1.
2597 Constant *Result = ConstantInt::get(V->getType(), 1);
2598
2599 Instruction *I = dyn_cast<Instruction>(V);
2600 if (!I) return Result;
2601
2602 if (I->getOpcode() == Instruction::Mul) {
2603 // Handle multiplies by a constant, etc.
2604 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2605 GetFactor(I->getOperand(1)));
2606 } else if (I->getOpcode() == Instruction::Shl) {
2607 // (X<<C) -> X * (1 << C)
2608 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2609 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2610 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2611 }
2612 } else if (I->getOpcode() == Instruction::And) {
2613 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2614 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002615 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002616 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2617 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002618 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002619 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002620 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002621 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002622 if (!CI->isIntegerCast())
2623 return Result;
2624 Value *Op = CI->getOperand(0);
2625 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002626 }
2627 return Result;
2628}
2629
Reid Spencer7eb55b32006-11-02 01:53:59 +00002630/// This function implements the transforms on rem instructions that work
2631/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2632/// is used by the visitors to those instructions.
2633/// @brief Transforms common to all three rem instructions
2634Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002636
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002637 // 0 % X == 0, we don't need to preserve faults!
2638 if (Constant *LHS = dyn_cast<Constant>(Op0))
2639 if (LHS->isNullValue())
2640 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2641
2642 if (isa<UndefValue>(Op0)) // undef % X -> 0
2643 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2644 if (isa<UndefValue>(Op1))
2645 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002646
2647 // Handle cases involving: rem X, (select Cond, Y, Z)
2648 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2649 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2650 // the same basic block, then we replace the select with Y, and the
2651 // condition of the select with false (if the cond value is in the same
2652 // BB). If the select has uses other than the div, this allows them to be
2653 // simplified also.
2654 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2655 if (ST->isNullValue()) {
2656 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2657 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002658 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002659 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2660 I.setOperand(1, SI->getOperand(2));
2661 else
2662 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002663 return &I;
2664 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002665 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2666 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2667 if (ST->isNullValue()) {
2668 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2669 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002670 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002671 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2672 I.setOperand(1, SI->getOperand(1));
2673 else
2674 UpdateValueUsesWith(SI, SI->getOperand(1));
2675 return &I;
2676 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002677 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002678
Reid Spencer7eb55b32006-11-02 01:53:59 +00002679 return 0;
2680}
2681
2682/// This function implements the transforms common to both integer remainder
2683/// instructions (urem and srem). It is called by the visitors to those integer
2684/// remainder instructions.
2685/// @brief Common integer remainder transforms
2686Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2687 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2688
2689 if (Instruction *common = commonRemTransforms(I))
2690 return common;
2691
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002692 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002693 // X % 0 == undef, we don't need to preserve faults!
2694 if (RHS->equalsInt(0))
2695 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2696
Chris Lattner3082c5a2003-02-18 19:28:33 +00002697 if (RHS->equalsInt(1)) // X % 1 == 0
2698 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2699
Chris Lattnerb70f1412006-02-28 05:49:21 +00002700 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2701 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2702 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2703 return R;
2704 } else if (isa<PHINode>(Op0I)) {
2705 if (Instruction *NV = FoldOpIntoPhi(I))
2706 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002707 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002708 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2709 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002710 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002711 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002712 }
2713
Reid Spencer7eb55b32006-11-02 01:53:59 +00002714 return 0;
2715}
2716
2717Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2719
2720 if (Instruction *common = commonIRemTransforms(I))
2721 return common;
2722
2723 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2724 // X urem C^2 -> X and C
2725 // Check to see if this is an unsigned remainder with an exact power of 2,
2726 // if so, convert to a bitwise and.
2727 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002728 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002729 return BinaryOperator::createAnd(Op0, SubOne(C));
2730 }
2731
Chris Lattner2e90b732006-02-05 07:54:04 +00002732 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002733 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2734 if (RHSI->getOpcode() == Instruction::Shl &&
2735 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002736 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002737 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2738 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2739 "tmp"), I);
2740 return BinaryOperator::createAnd(Op0, Add);
2741 }
2742 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002743 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002744
Reid Spencer7eb55b32006-11-02 01:53:59 +00002745 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2746 // where C1&C2 are powers of two.
2747 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2748 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2749 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2750 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002751 if ((STO->getValue().isPowerOf2()) &&
2752 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002753 Value *TrueAnd = InsertNewInstBefore(
2754 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2755 Value *FalseAnd = InsertNewInstBefore(
2756 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2757 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2758 }
2759 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002760 }
2761
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002762 return 0;
2763}
2764
Reid Spencer7eb55b32006-11-02 01:53:59 +00002765Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2767
2768 if (Instruction *common = commonIRemTransforms(I))
2769 return common;
2770
2771 if (Value *RHSNeg = dyn_castNegVal(Op1))
2772 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002773 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002774 // X % -Y -> X % Y
2775 AddUsesToWorkList(I);
2776 I.setOperand(1, RHSNeg);
2777 return &I;
2778 }
2779
2780 // If the top bits of both operands are zero (i.e. we can prove they are
2781 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002782 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002783 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2784 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2785 return BinaryOperator::createURem(Op0, Op1, I.getName());
2786 }
2787
2788 return 0;
2789}
2790
2791Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002792 return commonRemTransforms(I);
2793}
2794
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002795// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002796static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002797 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002798 if (isSigned) {
2799 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002800 APInt Val(APInt::getSignedMaxValue(TypeBits));
2801 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002802 }
Reid Spenceref599b02007-03-19 21:10:28 +00002803 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002804}
2805
2806// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002807static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2808 if (isSigned) {
2809 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002810 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2811 APInt Val(APInt::getSignedMinValue(TypeBits));
2812 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002813 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002814 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002815}
2816
Chris Lattner35167c32004-06-09 07:59:58 +00002817// isOneBitSet - Return true if there is exactly one bit set in the specified
2818// constant.
2819static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002820 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002821}
2822
Chris Lattner8fc5af42004-09-23 21:46:38 +00002823// isHighOnes - Return true if the constant is of the form 1+0+.
2824// This is the same as lowones(~X).
2825static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002826 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002827}
2828
Reid Spencer266e42b2006-12-23 06:05:41 +00002829/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002830/// are carefully arranged to allow folding of expressions such as:
2831///
2832/// (A < B) | (A > B) --> (A != B)
2833///
Reid Spencer266e42b2006-12-23 06:05:41 +00002834/// Note that this is only valid if the first and second predicates have the
2835/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002836///
Reid Spencer266e42b2006-12-23 06:05:41 +00002837/// Three bits are used to represent the condition, as follows:
2838/// 0 A > B
2839/// 1 A == B
2840/// 2 A < B
2841///
2842/// <=> Value Definition
2843/// 000 0 Always false
2844/// 001 1 A > B
2845/// 010 2 A == B
2846/// 011 3 A >= B
2847/// 100 4 A < B
2848/// 101 5 A != B
2849/// 110 6 A <= B
2850/// 111 7 Always true
2851///
2852static unsigned getICmpCode(const ICmpInst *ICI) {
2853 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002854 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002855 case ICmpInst::ICMP_UGT: return 1; // 001
2856 case ICmpInst::ICMP_SGT: return 1; // 001
2857 case ICmpInst::ICMP_EQ: return 2; // 010
2858 case ICmpInst::ICMP_UGE: return 3; // 011
2859 case ICmpInst::ICMP_SGE: return 3; // 011
2860 case ICmpInst::ICMP_ULT: return 4; // 100
2861 case ICmpInst::ICMP_SLT: return 4; // 100
2862 case ICmpInst::ICMP_NE: return 5; // 101
2863 case ICmpInst::ICMP_ULE: return 6; // 110
2864 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002865 // True -> 7
2866 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002867 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002868 return 0;
2869 }
2870}
2871
Reid Spencer266e42b2006-12-23 06:05:41 +00002872/// getICmpValue - This is the complement of getICmpCode, which turns an
2873/// opcode and two operands into either a constant true or false, or a brand
2874/// new /// ICmp instruction. The sign is passed in to determine which kind
2875/// of predicate to use in new icmp instructions.
2876static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2877 switch (code) {
2878 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002879 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002880 case 1:
2881 if (sign)
2882 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2883 else
2884 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2885 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2886 case 3:
2887 if (sign)
2888 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2889 else
2890 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2891 case 4:
2892 if (sign)
2893 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2894 else
2895 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2896 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2897 case 6:
2898 if (sign)
2899 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2900 else
2901 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002902 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002903 }
2904}
2905
Reid Spencer266e42b2006-12-23 06:05:41 +00002906static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2907 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2908 (ICmpInst::isSignedPredicate(p1) &&
2909 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2910 (ICmpInst::isSignedPredicate(p2) &&
2911 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2912}
2913
2914namespace {
2915// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2916struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002917 InstCombiner &IC;
2918 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002919 ICmpInst::Predicate pred;
2920 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2921 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2922 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002923 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002924 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2925 if (PredicatesFoldable(pred, ICI->getPredicate()))
2926 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2927 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002928 return false;
2929 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002930 Instruction *apply(Instruction &Log) const {
2931 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2932 if (ICI->getOperand(0) != LHS) {
2933 assert(ICI->getOperand(1) == LHS);
2934 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002935 }
2936
Chris Lattnerd1bce952007-03-13 14:27:42 +00002937 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002938 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002939 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002940 unsigned Code;
2941 switch (Log.getOpcode()) {
2942 case Instruction::And: Code = LHSCode & RHSCode; break;
2943 case Instruction::Or: Code = LHSCode | RHSCode; break;
2944 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002945 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002946 }
2947
Chris Lattnerd1bce952007-03-13 14:27:42 +00002948 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2949 ICmpInst::isSignedPredicate(ICI->getPredicate());
2950
2951 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002952 if (Instruction *I = dyn_cast<Instruction>(RV))
2953 return I;
2954 // Otherwise, it's a constant boolean value...
2955 return IC.ReplaceInstUsesWith(Log, RV);
2956 }
2957};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002958} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002959
Chris Lattnerba1cb382003-09-19 17:17:26 +00002960// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2961// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002962// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002963Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002964 ConstantInt *OpRHS,
2965 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002966 BinaryOperator &TheAnd) {
2967 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002968 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002969 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002970 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002971
Chris Lattnerba1cb382003-09-19 17:17:26 +00002972 switch (Op->getOpcode()) {
2973 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002974 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002975 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002976 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002977 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002978 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002979 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002980 }
2981 break;
2982 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002983 if (Together == AndRHS) // (X | C) & C --> C
2984 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002985
Chris Lattner86102b82005-01-01 16:22:27 +00002986 if (Op->hasOneUse() && Together != OpRHS) {
2987 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002988 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002989 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002990 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002991 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002992 }
2993 break;
2994 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002995 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002996 // Adding a one to a single bit bit-field should be turned into an XOR
2997 // of the bit. First thing to check is to see if this AND is with a
2998 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002999 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003000
3001 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003002 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003003 // Ok, at this point, we know that we are masking the result of the
3004 // ADD down to exactly one bit. If the constant we are adding has
3005 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003006 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003007
Chris Lattnerba1cb382003-09-19 17:17:26 +00003008 // Check to see if any bits below the one bit set in AndRHSV are set.
3009 if ((AddRHS & (AndRHSV-1)) == 0) {
3010 // If not, the only thing that can effect the output of the AND is
3011 // the bit specified by AndRHSV. If that bit is set, the effect of
3012 // the XOR is to toggle the bit. If it is clear, then the ADD has
3013 // no effect.
3014 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3015 TheAnd.setOperand(0, X);
3016 return &TheAnd;
3017 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003018 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003019 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003020 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003021 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003022 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003023 }
3024 }
3025 }
3026 }
3027 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003028
3029 case Instruction::Shl: {
3030 // We know that the AND will not produce any of the bits shifted in, so if
3031 // the anded constant includes them, clear them now!
3032 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003033 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003034 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003035 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3036 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003037
Zhou Shengb3a80b12007-03-29 08:15:12 +00003038 if (CI->getValue() == ShlMask) {
3039 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003040 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3041 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003042 TheAnd.setOperand(1, CI);
3043 return &TheAnd;
3044 }
3045 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003046 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003047 case Instruction::LShr:
3048 {
Chris Lattner2da29172003-09-19 19:05:02 +00003049 // We know that the AND will not produce any of the bits shifted in, so if
3050 // the anded constant includes them, clear them now! This only applies to
3051 // unsigned shifts, because a signed shr may bring in set bits!
3052 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003053 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003054 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003055 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3056 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003057
Zhou Shengb3a80b12007-03-29 08:15:12 +00003058 if (CI->getValue() == ShrMask) {
3059 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003060 return ReplaceInstUsesWith(TheAnd, Op);
3061 } else if (CI != AndRHS) {
3062 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3063 return &TheAnd;
3064 }
3065 break;
3066 }
3067 case Instruction::AShr:
3068 // Signed shr.
3069 // See if this is shifting in some sign extension, then masking it out
3070 // with an and.
3071 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003072 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003073 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003074 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3075 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003076 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003077 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003078 // Make the argument unsigned.
3079 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003080 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003081 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003082 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003083 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003084 }
Chris Lattner2da29172003-09-19 19:05:02 +00003085 }
3086 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003087 }
3088 return 0;
3089}
3090
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003091
Chris Lattner6862fbd2004-09-29 17:40:11 +00003092/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3093/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003094/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3095/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003096/// insert new instructions.
3097Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003098 bool isSigned, bool Inside,
3099 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003100 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003101 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003102 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003103
Chris Lattner6862fbd2004-09-29 17:40:11 +00003104 if (Inside) {
3105 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003106 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003107
Reid Spencer266e42b2006-12-23 06:05:41 +00003108 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003109 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003110 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003111 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3112 return new ICmpInst(pred, V, Hi);
3113 }
3114
3115 // Emit V-Lo <u Hi-Lo
3116 Constant *NegLo = ConstantExpr::getNeg(Lo);
3117 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003118 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003119 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3120 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003121 }
3122
3123 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003124 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003125
Reid Spencerf4071162007-03-21 23:19:50 +00003126 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003127 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003128 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003129 ICmpInst::Predicate pred = (isSigned ?
3130 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3131 return new ICmpInst(pred, V, Hi);
3132 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003133
Reid Spencerf4071162007-03-21 23:19:50 +00003134 // Emit V-Lo >u Hi-1-Lo
3135 // Note that Hi has already had one subtracted from it, above.
3136 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003137 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003138 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003139 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3140 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003141}
3142
Chris Lattnerb4b25302005-09-18 07:22:02 +00003143// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3144// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3145// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3146// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003147static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003148 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003149 uint32_t BitWidth = Val->getType()->getBitWidth();
3150 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003151
3152 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003153 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003154 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003155 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003156 return true;
3157}
3158
Chris Lattnerb4b25302005-09-18 07:22:02 +00003159/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3160/// where isSub determines whether the operator is a sub. If we can fold one of
3161/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003162///
3163/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3164/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3165/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3166///
3167/// return (A +/- B).
3168///
3169Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003170 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003171 Instruction &I) {
3172 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3173 if (!LHSI || LHSI->getNumOperands() != 2 ||
3174 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3175
3176 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3177
3178 switch (LHSI->getOpcode()) {
3179 default: return 0;
3180 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003181 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003182 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003183 if ((Mask->getValue().countLeadingZeros() +
3184 Mask->getValue().countPopulation()) ==
3185 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003186 break;
3187
3188 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3189 // part, we don't need any explicit masks to take them out of A. If that
3190 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003191 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003192 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003193 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003194 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003195 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003196 break;
3197 }
3198 }
Chris Lattneraf517572005-09-18 04:24:45 +00003199 return 0;
3200 case Instruction::Or:
3201 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003202 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003203 if ((Mask->getValue().countLeadingZeros() +
3204 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003205 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003206 break;
3207 return 0;
3208 }
3209
3210 Instruction *New;
3211 if (isSub)
3212 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3213 else
3214 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3215 return InsertNewInstBefore(New, I);
3216}
3217
Chris Lattner113f4f42002-06-25 16:13:24 +00003218Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003219 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003221
Chris Lattner81a7a232004-10-16 18:11:37 +00003222 if (isa<UndefValue>(Op1)) // X & undef -> 0
3223 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3224
Chris Lattner86102b82005-01-01 16:22:27 +00003225 // and X, X = X
3226 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003227 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003228
Chris Lattner5b2edb12006-02-12 08:02:11 +00003229 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003230 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003231 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003232 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3233 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3234 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003235 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003236 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003237 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003238 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003239 if (CP->isAllOnesValue())
3240 return ReplaceInstUsesWith(I, I.getOperand(0));
3241 }
3242 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003243
Zhou Sheng75b871f2007-01-11 12:24:14 +00003244 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003245 const APInt& AndRHSMask = AndRHS->getValue();
3246 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003247
Chris Lattnerba1cb382003-09-19 17:17:26 +00003248 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003249 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003250 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003251 Value *Op0LHS = Op0I->getOperand(0);
3252 Value *Op0RHS = Op0I->getOperand(1);
3253 switch (Op0I->getOpcode()) {
3254 case Instruction::Xor:
3255 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003256 // If the mask is only needed on one incoming arm, push it up.
3257 if (Op0I->hasOneUse()) {
3258 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3259 // Not masking anything out for the LHS, move to RHS.
3260 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3261 Op0RHS->getName()+".masked");
3262 InsertNewInstBefore(NewRHS, I);
3263 return BinaryOperator::create(
3264 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003265 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003266 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003267 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3268 // Not masking anything out for the RHS, move to LHS.
3269 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3270 Op0LHS->getName()+".masked");
3271 InsertNewInstBefore(NewLHS, I);
3272 return BinaryOperator::create(
3273 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3274 }
3275 }
3276
Chris Lattner86102b82005-01-01 16:22:27 +00003277 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003278 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003279 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3280 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3281 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3282 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3283 return BinaryOperator::createAnd(V, AndRHS);
3284 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3285 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003286 break;
3287
3288 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003289 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3290 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3291 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3292 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3293 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003294 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003295 }
3296
Chris Lattner16464b32003-07-23 19:25:52 +00003297 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003298 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003299 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003300 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003301 // If this is an integer truncation or change from signed-to-unsigned, and
3302 // if the source is an and/or with immediate, transform it. This
3303 // frequently occurs for bitfield accesses.
3304 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003305 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003306 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003307 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003308 if (CastOp->getOpcode() == Instruction::And) {
3309 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003310 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3311 // This will fold the two constants together, which may allow
3312 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003313 Instruction *NewCast = CastInst::createTruncOrBitCast(
3314 CastOp->getOperand(0), I.getType(),
3315 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003316 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003317 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003318 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003319 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003320 return BinaryOperator::createAnd(NewCast, C3);
3321 } else if (CastOp->getOpcode() == Instruction::Or) {
3322 // Change: and (cast (or X, C1) to T), C2
3323 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003324 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003325 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3326 return ReplaceInstUsesWith(I, AndRHS);
3327 }
3328 }
Chris Lattner33217db2003-07-23 19:36:21 +00003329 }
Chris Lattner183b3362004-04-09 19:05:30 +00003330
3331 // Try to fold constant and into select arguments.
3332 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003333 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003334 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003335 if (isa<PHINode>(Op0))
3336 if (Instruction *NV = FoldOpIntoPhi(I))
3337 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003338 }
3339
Chris Lattnerbb74e222003-03-10 23:06:50 +00003340 Value *Op0NotVal = dyn_castNotVal(Op0);
3341 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003342
Chris Lattner023a4832004-06-18 06:07:51 +00003343 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3344 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3345
Misha Brukman9c003d82004-07-30 12:50:08 +00003346 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003347 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003348 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3349 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003350 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003351 return BinaryOperator::createNot(Or);
3352 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003353
3354 {
3355 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003356 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3357 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3358 return ReplaceInstUsesWith(I, Op1);
3359 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3360 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3361 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003362
3363 if (Op0->hasOneUse() &&
3364 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3365 if (A == Op1) { // (A^B)&A -> A&(A^B)
3366 I.swapOperands(); // Simplify below
3367 std::swap(Op0, Op1);
3368 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3369 cast<BinaryOperator>(Op0)->swapOperands();
3370 I.swapOperands(); // Simplify below
3371 std::swap(Op0, Op1);
3372 }
3373 }
3374 if (Op1->hasOneUse() &&
3375 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3376 if (B == Op0) { // B&(A^B) -> B&(B^A)
3377 cast<BinaryOperator>(Op1)->swapOperands();
3378 std::swap(A, B);
3379 }
3380 if (A == Op0) { // A&(A^B) -> A & ~B
3381 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3382 InsertNewInstBefore(NotB, I);
3383 return BinaryOperator::createAnd(A, NotB);
3384 }
3385 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003386 }
3387
Reid Spencer266e42b2006-12-23 06:05:41 +00003388 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3389 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3390 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003391 return R;
3392
Chris Lattner623826c2004-09-28 21:48:02 +00003393 Value *LHSVal, *RHSVal;
3394 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003395 ICmpInst::Predicate LHSCC, RHSCC;
3396 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3397 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3398 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3399 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3400 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3401 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3402 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3403 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003404 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003405 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3406 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3407 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3408 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003409 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003410 std::swap(LHS, RHS);
3411 std::swap(LHSCst, RHSCst);
3412 std::swap(LHSCC, RHSCC);
3413 }
3414
Reid Spencer266e42b2006-12-23 06:05:41 +00003415 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003416 // comparing a value against two constants and and'ing the result
3417 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003418 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3419 // (from the FoldICmpLogical check above), that the two constants
3420 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003421 assert(LHSCst != RHSCst && "Compares not folded above?");
3422
3423 switch (LHSCC) {
3424 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003425 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003426 switch (RHSCC) {
3427 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003428 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3429 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3430 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003431 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003432 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3433 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3434 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003435 return ReplaceInstUsesWith(I, LHS);
3436 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003437 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003438 switch (RHSCC) {
3439 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003440 case ICmpInst::ICMP_ULT:
3441 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3442 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3443 break; // (X != 13 & X u< 15) -> no change
3444 case ICmpInst::ICMP_SLT:
3445 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3446 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3447 break; // (X != 13 & X s< 15) -> no change
3448 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3449 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3450 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003451 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003452 case ICmpInst::ICMP_NE:
3453 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003454 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3455 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3456 LHSVal->getName()+".off");
3457 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003458 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3459 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003460 }
3461 break; // (X != 13 & X != 15) -> no change
3462 }
3463 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003464 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003465 switch (RHSCC) {
3466 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003467 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3468 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003469 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003470 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3471 break;
3472 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3473 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003474 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003475 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3476 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003477 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003478 break;
3479 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003480 switch (RHSCC) {
3481 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003482 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3483 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003484 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003485 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3486 break;
3487 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3488 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003489 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003490 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3491 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003492 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003493 break;
3494 case ICmpInst::ICMP_UGT:
3495 switch (RHSCC) {
3496 default: assert(0 && "Unknown integer condition code!");
3497 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3498 return ReplaceInstUsesWith(I, LHS);
3499 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3500 return ReplaceInstUsesWith(I, RHS);
3501 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3502 break;
3503 case ICmpInst::ICMP_NE:
3504 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3505 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3506 break; // (X u> 13 & X != 15) -> no change
3507 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3508 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3509 true, I);
3510 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3511 break;
3512 }
3513 break;
3514 case ICmpInst::ICMP_SGT:
3515 switch (RHSCC) {
3516 default: assert(0 && "Unknown integer condition code!");
3517 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3518 return ReplaceInstUsesWith(I, LHS);
3519 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3520 return ReplaceInstUsesWith(I, RHS);
3521 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3522 break;
3523 case ICmpInst::ICMP_NE:
3524 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3525 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3526 break; // (X s> 13 & X != 15) -> no change
3527 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3528 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3529 true, I);
3530 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3531 break;
3532 }
3533 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003534 }
3535 }
3536 }
3537
Chris Lattner3af10532006-05-05 06:39:07 +00003538 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003539 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3540 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3541 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3542 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003543 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003544 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003545 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3546 I.getType(), TD) &&
3547 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3548 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003549 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3550 Op1C->getOperand(0),
3551 I.getName());
3552 InsertNewInstBefore(NewOp, I);
3553 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3554 }
Chris Lattner3af10532006-05-05 06:39:07 +00003555 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003556
3557 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003558 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3559 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3560 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003561 SI0->getOperand(1) == SI1->getOperand(1) &&
3562 (SI0->hasOneUse() || SI1->hasOneUse())) {
3563 Instruction *NewOp =
3564 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3565 SI1->getOperand(0),
3566 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003567 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3568 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003569 }
Chris Lattner3af10532006-05-05 06:39:07 +00003570 }
3571
Chris Lattner113f4f42002-06-25 16:13:24 +00003572 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003573}
3574
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003575/// CollectBSwapParts - Look to see if the specified value defines a single byte
3576/// in the result. If it does, and if the specified byte hasn't been filled in
3577/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003578static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003579 Instruction *I = dyn_cast<Instruction>(V);
3580 if (I == 0) return true;
3581
3582 // If this is an or instruction, it is an inner node of the bswap.
3583 if (I->getOpcode() == Instruction::Or)
3584 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3585 CollectBSwapParts(I->getOperand(1), ByteValues);
3586
Zhou Shengb25806f2007-03-30 09:29:48 +00003587 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003588 // If this is a shift by a constant int, and it is "24", then its operand
3589 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003590 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003591 // Not shifting the entire input by N-1 bytes?
Zhou Shengb25806f2007-03-30 09:29:48 +00003592 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003593 8*(ByteValues.size()-1))
3594 return true;
3595
3596 unsigned DestNo;
3597 if (I->getOpcode() == Instruction::Shl) {
3598 // X << 24 defines the top byte with the lowest of the input bytes.
3599 DestNo = ByteValues.size()-1;
3600 } else {
3601 // X >>u 24 defines the low byte with the highest of the input bytes.
3602 DestNo = 0;
3603 }
3604
3605 // If the destination byte value is already defined, the values are or'd
3606 // together, which isn't a bswap (unless it's an or of the same bits).
3607 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3608 return true;
3609 ByteValues[DestNo] = I->getOperand(0);
3610 return false;
3611 }
3612
3613 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3614 // don't have this.
3615 Value *Shift = 0, *ShiftLHS = 0;
3616 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3617 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3618 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3619 return true;
3620 Instruction *SI = cast<Instruction>(Shift);
3621
3622 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Shengb25806f2007-03-30 09:29:48 +00003623 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3624 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003625 return true;
3626
3627 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3628 unsigned DestByte;
Zhou Shengb25806f2007-03-30 09:29:48 +00003629 if (AndAmt->getValue().getActiveBits() > 64)
3630 return true;
3631 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003632 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Shengb25806f2007-03-30 09:29:48 +00003633 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003634 break;
3635 // Unknown mask for bswap.
3636 if (DestByte == ByteValues.size()) return true;
3637
Reid Spencere0fc4df2006-10-20 07:07:24 +00003638 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003639 unsigned SrcByte;
3640 if (SI->getOpcode() == Instruction::Shl)
3641 SrcByte = DestByte - ShiftBytes;
3642 else
3643 SrcByte = DestByte + ShiftBytes;
3644
3645 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3646 if (SrcByte != ByteValues.size()-DestByte-1)
3647 return true;
3648
3649 // If the destination byte value is already defined, the values are or'd
3650 // together, which isn't a bswap (unless it's an or of the same bits).
3651 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3652 return true;
3653 ByteValues[DestByte] = SI->getOperand(0);
3654 return false;
3655}
3656
3657/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3658/// If so, insert the new bswap intrinsic and return it.
3659Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003660 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3661 if (!ITy || ITy->getBitWidth() % 16)
3662 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003663
3664 /// ByteValues - For each byte of the result, we keep track of which value
3665 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003666 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003667 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003668
3669 // Try to find all the pieces corresponding to the bswap.
3670 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3671 CollectBSwapParts(I.getOperand(1), ByteValues))
3672 return 0;
3673
3674 // Check to see if all of the bytes come from the same value.
3675 Value *V = ByteValues[0];
3676 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3677
3678 // Check to make sure that all of the bytes come from the same value.
3679 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3680 if (ByteValues[i] != V)
3681 return 0;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003682 const Type *Tys[] = { ITy, ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003683 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003684 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003685 return new CallInst(F, V);
3686}
3687
3688
Chris Lattner113f4f42002-06-25 16:13:24 +00003689Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003690 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003692
Chris Lattner3a8248f2007-03-24 23:56:43 +00003693 if (isa<UndefValue>(Op1)) // X | undef -> -1
3694 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003695
Chris Lattner5b2edb12006-02-12 08:02:11 +00003696 // or X, X = X
3697 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003698 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003699
Chris Lattner5b2edb12006-02-12 08:02:11 +00003700 // See if we can simplify any instructions used by the instruction whose sole
3701 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003702 if (!isa<VectorType>(I.getType())) {
3703 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3704 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3705 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3706 KnownZero, KnownOne))
3707 return &I;
3708 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003709
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003710 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003711 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003712 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003713 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3714 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003715 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003716 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003717 Or->takeName(Op0);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003718 return BinaryOperator::createAnd(Or,
3719 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003720 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003721
Chris Lattnerd4252a72004-07-30 07:50:03 +00003722 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3723 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003724 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003725 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003726 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003727 return BinaryOperator::createXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003728 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003729 }
Chris Lattner183b3362004-04-09 19:05:30 +00003730
3731 // Try to fold constant and into select arguments.
3732 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003733 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003734 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003735 if (isa<PHINode>(Op0))
3736 if (Instruction *NV = FoldOpIntoPhi(I))
3737 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003738 }
3739
Chris Lattner330628a2006-01-06 17:59:59 +00003740 Value *A = 0, *B = 0;
3741 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003742
3743 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3744 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3745 return ReplaceInstUsesWith(I, Op1);
3746 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3747 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3748 return ReplaceInstUsesWith(I, Op0);
3749
Chris Lattnerb7845d62006-07-10 20:25:24 +00003750 // (A | B) | C and A | (B | C) -> bswap if possible.
3751 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003752 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003753 match(Op1, m_Or(m_Value(), m_Value())) ||
3754 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3755 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003756 if (Instruction *BSwap = MatchBSwap(I))
3757 return BSwap;
3758 }
3759
Chris Lattnerb62f5082005-05-09 04:58:36 +00003760 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3761 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003762 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003763 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3764 InsertNewInstBefore(NOr, I);
3765 NOr->takeName(Op0);
3766 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003767 }
3768
3769 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3770 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003771 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003772 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3773 InsertNewInstBefore(NOr, I);
3774 NOr->takeName(Op0);
3775 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003776 }
3777
Chris Lattner1150df92007-04-08 07:47:01 +00003778 // (A & C)|(B & D)
3779 Value *C, *D;
3780 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3781 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner7621a032007-04-08 07:55:22 +00003782 Value *V1 = 0, *V2 = 0, *V3 = 0;
3783 C1 = dyn_cast<ConstantInt>(C);
3784 C2 = dyn_cast<ConstantInt>(D);
3785 if (C1 && C2) { // (A & C1)|(B & C2)
3786 // If we have: ((V + N) & C1) | (V & C2)
3787 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3788 // replace with V+N.
3789 if (C1->getValue() == ~C2->getValue()) {
3790 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3791 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3792 // Add commutes, try both ways.
3793 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3794 return ReplaceInstUsesWith(I, A);
3795 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3796 return ReplaceInstUsesWith(I, A);
3797 }
3798 // Or commutes, try both ways.
3799 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3800 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3801 // Add commutes, try both ways.
3802 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3803 return ReplaceInstUsesWith(I, B);
3804 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3805 return ReplaceInstUsesWith(I, B);
3806 }
3807 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00003808 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00003809 }
3810
Chris Lattner1150df92007-04-08 07:47:01 +00003811 // Check to see if we have any common things being and'ed. If so, find the
3812 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00003813 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3814 if (A == B) // (A & C)|(A & D) == A & (C|D)
3815 V1 = A, V2 = C, V3 = D;
3816 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3817 V1 = A, V2 = B, V3 = C;
3818 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3819 V1 = C, V2 = A, V3 = D;
3820 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3821 V1 = C, V2 = A, V3 = B;
3822
3823 if (V1) {
3824 Value *Or =
3825 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3826 return BinaryOperator::createAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00003827 }
Chris Lattner1150df92007-04-08 07:47:01 +00003828
3829 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
Chris Lattnerc8d37882007-04-08 08:01:49 +00003830 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner1150df92007-04-08 07:47:01 +00003831 // Try all combination of terms to find V3 and ~V3.
3832 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3833 if (V3 == B)
3834 V1 = D, V2 = C;
3835 else if (V3 == D)
3836 V1 = B, V2 = C;
3837 }
3838 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3839 if (V3 == A)
3840 V1 = C, V2 = D;
3841 else if (V3 == C)
3842 V1 = A, V2 = D;
3843 }
3844 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3845 if (V3 == B)
3846 V1 = D, V2 = A;
3847 else if (V3 == D)
3848 V1 = B, V2 = A;
3849 }
3850 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3851 if (V3 == A)
3852 V1 = C, V2 = B;
3853 else if (V3 == C)
3854 V1 = A, V2 = B;
3855 }
3856 if (V1) {
3857 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3858 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3859 return BinaryOperator::createXor(A, V2);
3860 }
3861 }
3862 }
Chris Lattner15212982005-09-18 03:42:07 +00003863 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003864
3865 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003866 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3867 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3868 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003869 SI0->getOperand(1) == SI1->getOperand(1) &&
3870 (SI0->hasOneUse() || SI1->hasOneUse())) {
3871 Instruction *NewOp =
3872 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3873 SI1->getOperand(0),
3874 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003875 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3876 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003877 }
3878 }
Chris Lattner812aab72003-08-12 19:11:07 +00003879
Chris Lattnerd4252a72004-07-30 07:50:03 +00003880 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3881 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003882 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003883 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003884 } else {
3885 A = 0;
3886 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003887 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003888 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3889 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003890 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003891 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003892
Misha Brukman9c003d82004-07-30 12:50:08 +00003893 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003894 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3895 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3896 I.getName()+".demorgan"), I);
3897 return BinaryOperator::createNot(And);
3898 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003899 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003900
Reid Spencer266e42b2006-12-23 06:05:41 +00003901 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3902 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3903 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003904 return R;
3905
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003906 Value *LHSVal, *RHSVal;
3907 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003908 ICmpInst::Predicate LHSCC, RHSCC;
3909 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3910 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3911 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3912 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3913 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3914 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3915 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3916 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003917 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003918 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3919 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3920 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3921 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003922 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003923 std::swap(LHS, RHS);
3924 std::swap(LHSCst, RHSCst);
3925 std::swap(LHSCC, RHSCC);
3926 }
3927
Reid Spencer266e42b2006-12-23 06:05:41 +00003928 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003929 // comparing a value against two constants and or'ing the result
3930 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003931 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3932 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003933 // equal.
3934 assert(LHSCst != RHSCst && "Compares not folded above?");
3935
3936 switch (LHSCC) {
3937 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003938 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003939 switch (RHSCC) {
3940 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003941 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003942 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3943 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3944 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3945 LHSVal->getName()+".off");
3946 InsertNewInstBefore(Add, I);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003947 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003948 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003949 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003950 break; // (X == 13 | X == 15) -> no change
3951 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3952 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003953 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003954 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3955 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3956 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003957 return ReplaceInstUsesWith(I, RHS);
3958 }
3959 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003960 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003961 switch (RHSCC) {
3962 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003963 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3964 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3965 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003966 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003967 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3968 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3969 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003970 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003971 }
3972 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003973 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003974 switch (RHSCC) {
3975 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003976 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003977 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003978 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3979 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3980 false, I);
3981 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3982 break;
3983 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3984 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003985 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003986 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3987 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003988 }
3989 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003990 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003991 switch (RHSCC) {
3992 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003993 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3994 break;
3995 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3996 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3997 false, I);
3998 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3999 break;
4000 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4001 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4002 return ReplaceInstUsesWith(I, RHS);
4003 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4004 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004005 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004006 break;
4007 case ICmpInst::ICMP_UGT:
4008 switch (RHSCC) {
4009 default: assert(0 && "Unknown integer condition code!");
4010 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4011 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4012 return ReplaceInstUsesWith(I, LHS);
4013 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4014 break;
4015 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4016 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004017 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004018 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4019 break;
4020 }
4021 break;
4022 case ICmpInst::ICMP_SGT:
4023 switch (RHSCC) {
4024 default: assert(0 && "Unknown integer condition code!");
4025 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4026 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4027 return ReplaceInstUsesWith(I, LHS);
4028 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4029 break;
4030 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4031 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004032 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004033 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4034 break;
4035 }
4036 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004037 }
4038 }
4039 }
Chris Lattner3af10532006-05-05 06:39:07 +00004040
4041 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004042 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004043 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004044 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4045 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004046 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004047 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004048 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4049 I.getType(), TD) &&
4050 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4051 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004052 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4053 Op1C->getOperand(0),
4054 I.getName());
4055 InsertNewInstBefore(NewOp, I);
4056 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4057 }
Chris Lattner3af10532006-05-05 06:39:07 +00004058 }
Chris Lattner3af10532006-05-05 06:39:07 +00004059
Chris Lattner15212982005-09-18 03:42:07 +00004060
Chris Lattner113f4f42002-06-25 16:13:24 +00004061 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004062}
4063
Chris Lattnerc2076352004-02-16 01:20:27 +00004064// XorSelf - Implements: X ^ X --> 0
4065struct XorSelf {
4066 Value *RHS;
4067 XorSelf(Value *rhs) : RHS(rhs) {}
4068 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4069 Instruction *apply(BinaryOperator &Xor) const {
4070 return &Xor;
4071 }
4072};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004073
4074
Chris Lattner113f4f42002-06-25 16:13:24 +00004075Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004076 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004077 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004078
Chris Lattner81a7a232004-10-16 18:11:37 +00004079 if (isa<UndefValue>(Op1))
4080 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4081
Chris Lattnerc2076352004-02-16 01:20:27 +00004082 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4083 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4084 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004085 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004086 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004087
4088 // See if we can simplify any instructions used by the instruction whose sole
4089 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004090 if (!isa<VectorType>(I.getType())) {
4091 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4092 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4093 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4094 KnownZero, KnownOne))
4095 return &I;
4096 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004097
Zhou Sheng75b871f2007-01-11 12:24:14 +00004098 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004099 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4100 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004101 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004102 return new ICmpInst(ICI->getInversePredicate(),
4103 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004104
Reid Spencer266e42b2006-12-23 06:05:41 +00004105 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004106 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004107 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4108 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004109 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4110 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004111 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004112 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004113 }
Chris Lattner023a4832004-06-18 06:07:51 +00004114
4115 // ~(~X & Y) --> (X | ~Y)
4116 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4117 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4118 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4119 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004120 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004121 Op0I->getOperand(1)->getName()+".not");
4122 InsertNewInstBefore(NotY, I);
4123 return BinaryOperator::createOr(Op0NotVal, NotY);
4124 }
4125 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004126
Chris Lattner97638592003-07-23 21:37:07 +00004127 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004128 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004129 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004130 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004131 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4132 return BinaryOperator::createSub(
4133 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004134 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004135 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004136 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004137 // (X + C) ^ signbit -> (X + C + signbit)
4138 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4139 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004140
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004141 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004142 } else if (Op0I->getOpcode() == Instruction::Or) {
4143 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004144 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004145 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4146 // Anything in both C1 and C2 is known to be zero, remove it from
4147 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004148 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004149 NewRHS = ConstantExpr::getAnd(NewRHS,
4150 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004151 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004152 I.setOperand(0, Op0I->getOperand(0));
4153 I.setOperand(1, NewRHS);
4154 return &I;
4155 }
Chris Lattner97638592003-07-23 21:37:07 +00004156 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004157 }
Chris Lattner183b3362004-04-09 19:05:30 +00004158
4159 // Try to fold constant and into select arguments.
4160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004162 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004163 if (isa<PHINode>(Op0))
4164 if (Instruction *NV = FoldOpIntoPhi(I))
4165 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004166 }
4167
Chris Lattnerbb74e222003-03-10 23:06:50 +00004168 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004169 if (X == Op1)
4170 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004171 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004172
Chris Lattnerbb74e222003-03-10 23:06:50 +00004173 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004174 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004175 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004176
Chris Lattner07418422007-03-18 22:51:34 +00004177
4178 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4179 if (Op1I) {
4180 Value *A, *B;
4181 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4182 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004183 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004184 I.swapOperands();
4185 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004186 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004187 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004188 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004189 }
Chris Lattner07418422007-03-18 22:51:34 +00004190 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4191 if (Op0 == A) // A^(A^B) == B
4192 return ReplaceInstUsesWith(I, B);
4193 else if (Op0 == B) // A^(B^A) == B
4194 return ReplaceInstUsesWith(I, A);
4195 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004196 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004197 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004198 std::swap(A, B);
4199 }
Chris Lattner07418422007-03-18 22:51:34 +00004200 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004201 I.swapOperands(); // Simplified below.
4202 std::swap(Op0, Op1);
4203 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004204 }
Chris Lattner07418422007-03-18 22:51:34 +00004205 }
4206
4207 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4208 if (Op0I) {
4209 Value *A, *B;
4210 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4211 if (A == Op1) // (B|A)^B == (A|B)^B
4212 std::swap(A, B);
4213 if (B == Op1) { // (A|B)^B == A & ~B
4214 Instruction *NotB =
4215 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4216 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004217 }
Chris Lattner07418422007-03-18 22:51:34 +00004218 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4219 if (Op1 == A) // (A^B)^A == B
4220 return ReplaceInstUsesWith(I, B);
4221 else if (Op1 == B) // (B^A)^A == B
4222 return ReplaceInstUsesWith(I, A);
4223 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4224 if (A == Op1) // (A&B)^A -> (B&A)^A
4225 std::swap(A, B);
4226 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004227 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004228 Instruction *N =
4229 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004230 return BinaryOperator::createAnd(N, Op1);
4231 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004232 }
Chris Lattner07418422007-03-18 22:51:34 +00004233 }
4234
4235 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4236 if (Op0I && Op1I && Op0I->isShift() &&
4237 Op0I->getOpcode() == Op1I->getOpcode() &&
4238 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4239 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4240 Instruction *NewOp =
4241 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4242 Op1I->getOperand(0),
4243 Op0I->getName()), I);
4244 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4245 Op1I->getOperand(1));
4246 }
4247
4248 if (Op0I && Op1I) {
4249 Value *A, *B, *C, *D;
4250 // (A & B)^(A | B) -> A ^ B
4251 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4252 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4253 if ((A == C && B == D) || (A == D && B == C))
4254 return BinaryOperator::createXor(A, B);
4255 }
4256 // (A | B)^(A & B) -> A ^ B
4257 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4258 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4259 if ((A == C && B == D) || (A == D && B == C))
4260 return BinaryOperator::createXor(A, B);
4261 }
4262
4263 // (A & B)^(C & D)
4264 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4265 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4266 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4267 // (X & Y)^(X & Y) -> (Y^Z) & X
4268 Value *X = 0, *Y = 0, *Z = 0;
4269 if (A == C)
4270 X = A, Y = B, Z = D;
4271 else if (A == D)
4272 X = A, Y = B, Z = C;
4273 else if (B == C)
4274 X = B, Y = A, Z = D;
4275 else if (B == D)
4276 X = B, Y = A, Z = C;
4277
4278 if (X) {
4279 Instruction *NewOp =
4280 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4281 return BinaryOperator::createAnd(NewOp, X);
4282 }
4283 }
4284 }
4285
Reid Spencer266e42b2006-12-23 06:05:41 +00004286 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4287 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4288 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004289 return R;
4290
Chris Lattner3af10532006-05-05 06:39:07 +00004291 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004292 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004293 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004294 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4295 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004296 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004297 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004298 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4299 I.getType(), TD) &&
4300 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4301 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004302 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4303 Op1C->getOperand(0),
4304 I.getName());
4305 InsertNewInstBefore(NewOp, I);
4306 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4307 }
Chris Lattner3af10532006-05-05 06:39:07 +00004308 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004309
Chris Lattner113f4f42002-06-25 16:13:24 +00004310 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004311}
4312
Chris Lattner6862fbd2004-09-29 17:40:11 +00004313/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4314/// overflowed for this type.
4315static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004316 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004317 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004318
Reid Spencerf4071162007-03-21 23:19:50 +00004319 if (IsSigned)
4320 if (In2->getValue().isNegative())
4321 return Result->getValue().sgt(In1->getValue());
4322 else
4323 return Result->getValue().slt(In1->getValue());
4324 else
4325 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004326}
4327
Chris Lattner0798af32005-01-13 20:14:25 +00004328/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4329/// code necessary to compute the offset from the base pointer (without adding
4330/// in the base pointer). Return the result as a signed integer of intptr size.
4331static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4332 TargetData &TD = IC.getTargetData();
4333 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004334 const Type *IntPtrTy = TD.getIntPtrType();
4335 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004336
4337 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004338 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004339
Chris Lattner0798af32005-01-13 20:14:25 +00004340 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4341 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004342 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004343 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004344 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4345 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004346 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004347 Scale = ConstantExpr::getMul(OpC, Scale);
4348 if (Constant *RC = dyn_cast<Constant>(Result))
4349 Result = ConstantExpr::getAdd(RC, Scale);
4350 else {
4351 // Emit an add instruction.
4352 Result = IC.InsertNewInstBefore(
4353 BinaryOperator::createAdd(Result, Scale,
4354 GEP->getName()+".offs"), I);
4355 }
4356 }
4357 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004358 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004359 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004360 Op->getName()+".c"), I);
4361 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004362 // We'll let instcombine(mul) convert this to a shl if possible.
4363 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4364 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004365
4366 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004367 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004368 GEP->getName()+".offs"), I);
4369 }
4370 }
4371 return Result;
4372}
4373
Reid Spencer266e42b2006-12-23 06:05:41 +00004374/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004375/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004376Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4377 ICmpInst::Predicate Cond,
4378 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004379 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004380
4381 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4382 if (isa<PointerType>(CI->getOperand(0)->getType()))
4383 RHS = CI->getOperand(0);
4384
Chris Lattner0798af32005-01-13 20:14:25 +00004385 Value *PtrBase = GEPLHS->getOperand(0);
4386 if (PtrBase == RHS) {
4387 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004388 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4389 // each index is zero or not.
4390 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004391 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004392 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4393 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004394 bool EmitIt = true;
4395 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4396 if (isa<UndefValue>(C)) // undef index -> undef.
4397 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4398 if (C->isNullValue())
4399 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004400 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4401 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004402 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004403 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004404 ConstantInt::get(Type::Int1Ty,
4405 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004406 }
4407
4408 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004409 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004410 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004411 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4412 if (InVal == 0)
4413 InVal = Comp;
4414 else {
4415 InVal = InsertNewInstBefore(InVal, I);
4416 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004417 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004418 InVal = BinaryOperator::createOr(InVal, Comp);
4419 else // True if all are equal
4420 InVal = BinaryOperator::createAnd(InVal, Comp);
4421 }
4422 }
4423 }
4424
4425 if (InVal)
4426 return InVal;
4427 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004428 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004429 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4430 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004431 }
Chris Lattner0798af32005-01-13 20:14:25 +00004432
Reid Spencer266e42b2006-12-23 06:05:41 +00004433 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004434 // the result to fold to a constant!
4435 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4436 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4437 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004438 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4439 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004440 }
4441 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004442 // If the base pointers are different, but the indices are the same, just
4443 // compare the base pointer.
4444 if (PtrBase != GEPRHS->getOperand(0)) {
4445 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004446 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004447 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004448 if (IndicesTheSame)
4449 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4450 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4451 IndicesTheSame = false;
4452 break;
4453 }
4454
4455 // If all indices are the same, just compare the base pointers.
4456 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004457 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4458 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004459
4460 // Otherwise, the base pointers are different and the indices are
4461 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004462 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004463 }
Chris Lattner0798af32005-01-13 20:14:25 +00004464
Chris Lattner81e84172005-01-13 22:25:21 +00004465 // If one of the GEPs has all zero indices, recurse.
4466 bool AllZeros = true;
4467 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4468 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4469 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4470 AllZeros = false;
4471 break;
4472 }
4473 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004474 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4475 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004476
4477 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004478 AllZeros = true;
4479 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4480 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4481 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4482 AllZeros = false;
4483 break;
4484 }
4485 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004486 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004487
Chris Lattner4fa89822005-01-14 00:20:05 +00004488 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4489 // If the GEPs only differ by one index, compare it.
4490 unsigned NumDifferences = 0; // Keep track of # differences.
4491 unsigned DiffOperand = 0; // The operand that differs.
4492 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4493 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004494 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4495 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004496 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004497 NumDifferences = 2;
4498 break;
4499 } else {
4500 if (NumDifferences++) break;
4501 DiffOperand = i;
4502 }
4503 }
4504
4505 if (NumDifferences == 0) // SAME GEP?
4506 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004507 ConstantInt::get(Type::Int1Ty,
4508 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004509 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004510 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4511 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004512 // Make sure we do a signed comparison here.
4513 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004514 }
4515 }
4516
Reid Spencer266e42b2006-12-23 06:05:41 +00004517 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004518 // the result to fold to a constant!
4519 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4520 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4521 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4522 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4523 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004524 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004525 }
4526 }
4527 return 0;
4528}
4529
Reid Spencer266e42b2006-12-23 06:05:41 +00004530Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4531 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004532 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004533
Chris Lattner6ee923f2007-01-14 19:42:17 +00004534 // Fold trivial predicates.
4535 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4536 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4537 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4538 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4539
4540 // Simplify 'fcmp pred X, X'
4541 if (Op0 == Op1) {
4542 switch (I.getPredicate()) {
4543 default: assert(0 && "Unknown predicate!");
4544 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4545 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4546 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4547 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4548 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4549 case FCmpInst::FCMP_OLT: // True if ordered and less than
4550 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4551 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4552
4553 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4554 case FCmpInst::FCMP_ULT: // True if unordered or less than
4555 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4556 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4557 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4558 I.setPredicate(FCmpInst::FCMP_UNO);
4559 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4560 return &I;
4561
4562 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4563 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4564 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4565 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4566 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4567 I.setPredicate(FCmpInst::FCMP_ORD);
4568 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4569 return &I;
4570 }
4571 }
4572
Reid Spencer266e42b2006-12-23 06:05:41 +00004573 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004574 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004575
Reid Spencer266e42b2006-12-23 06:05:41 +00004576 // Handle fcmp with constant RHS
4577 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4578 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4579 switch (LHSI->getOpcode()) {
4580 case Instruction::PHI:
4581 if (Instruction *NV = FoldOpIntoPhi(I))
4582 return NV;
4583 break;
4584 case Instruction::Select:
4585 // If either operand of the select is a constant, we can fold the
4586 // comparison into the select arms, which will cause one to be
4587 // constant folded and the select turned into a bitwise or.
4588 Value *Op1 = 0, *Op2 = 0;
4589 if (LHSI->hasOneUse()) {
4590 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4591 // Fold the known value into the constant operand.
4592 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4593 // Insert a new FCmp of the other select operand.
4594 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4595 LHSI->getOperand(2), RHSC,
4596 I.getName()), I);
4597 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4598 // Fold the known value into the constant operand.
4599 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4600 // Insert a new FCmp of the other select operand.
4601 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4602 LHSI->getOperand(1), RHSC,
4603 I.getName()), I);
4604 }
4605 }
4606
4607 if (Op1)
4608 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4609 break;
4610 }
4611 }
4612
4613 return Changed ? &I : 0;
4614}
4615
4616Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4617 bool Changed = SimplifyCompare(I);
4618 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4619 const Type *Ty = Op0->getType();
4620
4621 // icmp X, X
4622 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004623 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4624 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004625
4626 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004627 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004628
4629 // icmp of GlobalValues can never equal each other as long as they aren't
4630 // external weak linkage type.
4631 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4632 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4633 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004634 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4635 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004636
4637 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004638 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004639 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4640 isa<ConstantPointerNull>(Op0)) &&
4641 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004642 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004643 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4644 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004645
Reid Spencer266e42b2006-12-23 06:05:41 +00004646 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004647 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004648 switch (I.getPredicate()) {
4649 default: assert(0 && "Invalid icmp instruction!");
4650 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004651 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004652 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004653 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004654 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004655 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004656 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004657
Reid Spencer266e42b2006-12-23 06:05:41 +00004658 case ICmpInst::ICMP_UGT:
4659 case ICmpInst::ICMP_SGT:
4660 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004661 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004662 case ICmpInst::ICMP_ULT:
4663 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004664 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4665 InsertNewInstBefore(Not, I);
4666 return BinaryOperator::createAnd(Not, Op1);
4667 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004668 case ICmpInst::ICMP_UGE:
4669 case ICmpInst::ICMP_SGE:
4670 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004671 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004672 case ICmpInst::ICMP_ULE:
4673 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004674 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4675 InsertNewInstBefore(Not, I);
4676 return BinaryOperator::createOr(Not, Op1);
4677 }
4678 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004679 }
4680
Chris Lattner2dd01742004-06-09 04:24:29 +00004681 // See if we are doing a comparison between a constant and an instruction that
4682 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004683 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004684 switch (I.getPredicate()) {
4685 default: break;
4686 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4687 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004688 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004689 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4690 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4691 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4692 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00004693 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4694 if (CI->isMinValue(true))
4695 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4696 ConstantInt::getAllOnesValue(Op0->getType()));
4697
Reid Spencer266e42b2006-12-23 06:05:41 +00004698 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004699
Reid Spencer266e42b2006-12-23 06:05:41 +00004700 case ICmpInst::ICMP_SLT:
4701 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004702 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004703 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4704 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4705 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4706 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4707 break;
4708
4709 case ICmpInst::ICMP_UGT:
4710 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004711 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004712 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4713 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4714 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4715 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00004716
4717 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4718 if (CI->isMaxValue(true))
4719 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4720 ConstantInt::getNullValue(Op0->getType()));
Reid Spencer266e42b2006-12-23 06:05:41 +00004721 break;
4722
4723 case ICmpInst::ICMP_SGT:
4724 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004725 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004726 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4727 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4728 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4729 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4730 break;
4731
4732 case ICmpInst::ICMP_ULE:
4733 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004734 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004735 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4736 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4737 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4738 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4739 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004740
Reid Spencer266e42b2006-12-23 06:05:41 +00004741 case ICmpInst::ICMP_SLE:
4742 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004743 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004744 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4745 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4746 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4747 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4748 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004749
Reid Spencer266e42b2006-12-23 06:05:41 +00004750 case ICmpInst::ICMP_UGE:
4751 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004752 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004753 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4754 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4755 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4756 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4757 break;
4758
4759 case ICmpInst::ICMP_SGE:
4760 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004761 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004762 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4763 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4764 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4765 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4766 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004767 }
4768
Reid Spencer266e42b2006-12-23 06:05:41 +00004769 // If we still have a icmp le or icmp ge instruction, turn it into the
4770 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004771 // already been handled above, this requires little checking.
4772 //
Reid Spencer624766f2007-03-25 19:55:33 +00004773 switch (I.getPredicate()) {
4774 default: break;
4775 case ICmpInst::ICMP_ULE:
4776 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4777 case ICmpInst::ICMP_SLE:
4778 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4779 case ICmpInst::ICMP_UGE:
4780 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4781 case ICmpInst::ICMP_SGE:
4782 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4783 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004784
4785 // See if we can fold the comparison based on bits known to be zero or one
4786 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004787 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4788 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4789 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004790 KnownZero, KnownOne, 0))
4791 return &I;
4792
4793 // Given the known and unknown bits, compute a range that the LHS could be
4794 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004795 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004796 // Compute the Min, Max and RHS values based on the known bits. For the
4797 // EQ and NE we use unsigned values.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00004798 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4799 const APInt& RHSVal = CI->getValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00004800 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004801 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4802 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004803 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004804 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4805 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004806 }
4807 switch (I.getPredicate()) { // LE/GE have been folded already.
4808 default: assert(0 && "Unknown icmp opcode!");
4809 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004810 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004811 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004812 break;
4813 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004814 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004816 break;
4817 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004818 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004819 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004820 if (Min.uge(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004821 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004822 break;
4823 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004824 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004825 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004826 if (Max.ule(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004828 break;
4829 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004830 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004831 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004832 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004833 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004834 break;
4835 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004836 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004837 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004838 if (Max.sle(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004839 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004840 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004841 }
4842 }
4843
Reid Spencer266e42b2006-12-23 06:05:41 +00004844 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004845 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004846 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004847 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00004848 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4849 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004850 }
4851
Chris Lattnera74deaf2007-04-03 17:43:25 +00004852 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00004853 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4854 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4855 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004856 case Instruction::GetElementPtr:
4857 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004858 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00004859 bool isAllZeros = true;
4860 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4861 if (!isa<Constant>(LHSI->getOperand(i)) ||
4862 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4863 isAllZeros = false;
4864 break;
4865 }
4866 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004867 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00004868 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4869 }
4870 break;
4871
Chris Lattner77c32c32005-04-23 15:31:55 +00004872 case Instruction::PHI:
4873 if (Instruction *NV = FoldOpIntoPhi(I))
4874 return NV;
4875 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00004876 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00004877 // If either operand of the select is a constant, we can fold the
4878 // comparison into the select arms, which will cause one to be
4879 // constant folded and the select turned into a bitwise or.
4880 Value *Op1 = 0, *Op2 = 0;
4881 if (LHSI->hasOneUse()) {
4882 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4883 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004884 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4885 // Insert a new ICmp of the other select operand.
4886 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4887 LHSI->getOperand(2), RHSC,
4888 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004889 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4890 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004891 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4892 // Insert a new ICmp of the other select operand.
4893 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4894 LHSI->getOperand(1), RHSC,
4895 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004896 }
4897 }
Jeff Cohen82639852005-04-23 21:38:35 +00004898
Chris Lattner77c32c32005-04-23 15:31:55 +00004899 if (Op1)
4900 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4901 break;
4902 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00004903 case Instruction::Malloc:
4904 // If we have (malloc != null), and if the malloc has a single use, we
4905 // can assume it is successful and remove the malloc.
4906 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4907 AddToWorkList(LHSI);
4908 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4909 !isTrueWhenEqual(I)));
4910 }
4911 break;
4912 }
Chris Lattner77c32c32005-04-23 15:31:55 +00004913 }
4914
Reid Spencer266e42b2006-12-23 06:05:41 +00004915 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00004916 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004917 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004918 return NI;
4919 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004920 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4921 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004922 return NI;
4923
Reid Spencer266e42b2006-12-23 06:05:41 +00004924 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00004925 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4926 // now.
4927 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4928 if (isa<PointerType>(Op0->getType()) &&
4929 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004930 // We keep moving the cast from the left operand over to the right
4931 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00004932 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004933
Chris Lattner64d87b02007-01-06 01:45:59 +00004934 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4935 // so eliminate it as well.
4936 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4937 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004938
Chris Lattner16930792003-11-03 04:25:02 +00004939 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00004940 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00004941 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004942 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004943 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00004944 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00004945 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004946 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004947 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00004948 }
Chris Lattner64d87b02007-01-06 01:45:59 +00004949 }
4950
4951 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004952 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00004953 // This comes up when you have code like
4954 // int X = A < B;
4955 // if (X) ...
4956 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004957 // with a constant or another cast from the same type.
4958 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004959 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004960 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004961 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004962
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004963 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00004964 Value *A, *B, *C, *D;
4965 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4966 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4967 Value *OtherVal = A == Op1 ? B : A;
4968 return new ICmpInst(I.getPredicate(), OtherVal,
4969 Constant::getNullValue(A->getType()));
4970 }
4971
4972 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4973 // A^c1 == C^c2 --> A == C^(c1^c2)
4974 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4975 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
4976 if (Op1->hasOneUse()) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004977 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner17c7c032007-01-05 03:04:57 +00004978 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
4979 return new ICmpInst(I.getPredicate(), A,
4980 InsertNewInstBefore(Xor, I));
4981 }
4982
4983 // A^B == A^D -> B == D
4984 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4985 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4986 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4987 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4988 }
4989 }
4990
4991 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4992 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004993 // A == (A^B) -> B == 0
4994 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00004995 return new ICmpInst(I.getPredicate(), OtherVal,
4996 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00004997 }
4998 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004999 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005000 return new ICmpInst(I.getPredicate(), B,
5001 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005002 }
5003 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005004 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005005 return new ICmpInst(I.getPredicate(), B,
5006 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005007 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005008
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005009 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5010 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5011 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5012 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5013 Value *X = 0, *Y = 0, *Z = 0;
5014
5015 if (A == C) {
5016 X = B; Y = D; Z = A;
5017 } else if (A == D) {
5018 X = B; Y = C; Z = A;
5019 } else if (B == C) {
5020 X = A; Y = D; Z = B;
5021 } else if (B == D) {
5022 X = A; Y = C; Z = B;
5023 }
5024
5025 if (X) { // Build (X^Y) & Z
5026 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5027 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5028 I.setOperand(0, Op1);
5029 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5030 return &I;
5031 }
5032 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005033 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005034 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005035}
5036
Chris Lattnera74deaf2007-04-03 17:43:25 +00005037/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5038///
5039Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5040 Instruction *LHSI,
5041 ConstantInt *RHS) {
5042 const APInt &RHSV = RHS->getValue();
5043
5044 switch (LHSI->getOpcode()) {
Duncan Sandsf01a47c2007-04-04 06:42:45 +00005045 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00005046 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5047 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5048 // fold the xor.
5049 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5050 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5051 Value *CompareVal = LHSI->getOperand(0);
5052
5053 // If the sign bit of the XorCST is not set, there is no change to
5054 // the operation, just stop using the Xor.
5055 if (!XorCST->getValue().isNegative()) {
5056 ICI.setOperand(0, CompareVal);
5057 AddToWorkList(LHSI);
5058 return &ICI;
5059 }
5060
5061 // Was the old condition true if the operand is positive?
5062 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5063
5064 // If so, the new one isn't.
5065 isTrueIfPositive ^= true;
5066
5067 if (isTrueIfPositive)
5068 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5069 else
5070 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5071 }
5072 }
5073 break;
5074 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5075 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5076 LHSI->getOperand(0)->hasOneUse()) {
5077 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5078
5079 // If the LHS is an AND of a truncating cast, we can widen the
5080 // and/compare to be the input width without changing the value
5081 // produced, eliminating a cast.
5082 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5083 // We can do this transformation if either the AND constant does not
5084 // have its sign bit set or if it is an equality comparison.
5085 // Extending a relational comparison when we're checking the sign
5086 // bit would not work.
5087 if (Cast->hasOneUse() &&
5088 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5089 RHSV.isPositive())) {
5090 uint32_t BitWidth =
5091 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5092 APInt NewCST = AndCST->getValue();
5093 NewCST.zext(BitWidth);
5094 APInt NewCI = RHSV;
5095 NewCI.zext(BitWidth);
5096 Instruction *NewAnd =
5097 BinaryOperator::createAnd(Cast->getOperand(0),
5098 ConstantInt::get(NewCST),LHSI->getName());
5099 InsertNewInstBefore(NewAnd, ICI);
5100 return new ICmpInst(ICI.getPredicate(), NewAnd,
5101 ConstantInt::get(NewCI));
5102 }
5103 }
5104
5105 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5106 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5107 // happens a LOT in code produced by the C front-end, for bitfield
5108 // access.
5109 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5110 if (Shift && !Shift->isShift())
5111 Shift = 0;
5112
5113 ConstantInt *ShAmt;
5114 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5115 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5116 const Type *AndTy = AndCST->getType(); // Type of the and.
5117
5118 // We can fold this as long as we can't shift unknown bits
5119 // into the mask. This can only happen with signed shift
5120 // rights, as they sign-extend.
5121 if (ShAmt) {
5122 bool CanFold = Shift->isLogicalShift();
5123 if (!CanFold) {
5124 // To test for the bad case of the signed shr, see if any
5125 // of the bits shifted in could be tested after the mask.
5126 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5127 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5128
5129 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5130 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5131 AndCST->getValue()) == 0)
5132 CanFold = true;
5133 }
5134
5135 if (CanFold) {
5136 Constant *NewCst;
5137 if (Shift->getOpcode() == Instruction::Shl)
5138 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5139 else
5140 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5141
5142 // Check to see if we are shifting out any of the bits being
5143 // compared.
5144 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5145 // If we shifted bits out, the fold is not going to work out.
5146 // As a special case, check to see if this means that the
5147 // result is always true or false now.
5148 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5149 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5150 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5151 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5152 } else {
5153 ICI.setOperand(1, NewCst);
5154 Constant *NewAndCST;
5155 if (Shift->getOpcode() == Instruction::Shl)
5156 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5157 else
5158 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5159 LHSI->setOperand(1, NewAndCST);
5160 LHSI->setOperand(0, Shift->getOperand(0));
5161 AddToWorkList(Shift); // Shift is dead.
5162 AddUsesToWorkList(ICI);
5163 return &ICI;
5164 }
5165 }
5166 }
5167
5168 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5169 // preferable because it allows the C<<Y expression to be hoisted out
5170 // of a loop if Y is invariant and X is not.
5171 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5172 ICI.isEquality() && !Shift->isArithmeticShift() &&
5173 isa<Instruction>(Shift->getOperand(0))) {
5174 // Compute C << Y.
5175 Value *NS;
5176 if (Shift->getOpcode() == Instruction::LShr) {
5177 NS = BinaryOperator::createShl(AndCST,
5178 Shift->getOperand(1), "tmp");
5179 } else {
5180 // Insert a logical shift.
5181 NS = BinaryOperator::createLShr(AndCST,
5182 Shift->getOperand(1), "tmp");
5183 }
5184 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5185
5186 // Compute X & (C << Y).
5187 Instruction *NewAnd =
5188 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5189 InsertNewInstBefore(NewAnd, ICI);
5190
5191 ICI.setOperand(0, NewAnd);
5192 return &ICI;
5193 }
5194 }
5195 break;
5196
5197 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5198 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5199 if (ICI.isEquality()) {
5200 uint32_t TypeBits = RHSV.getBitWidth();
5201
5202 // Check that the shift amount is in range. If not, don't perform
5203 // undefined shifts. When the shift is visited it will be
5204 // simplified.
5205 if (ShAmt->uge(TypeBits))
5206 break;
5207
5208 // If we are comparing against bits always shifted out, the
5209 // comparison cannot succeed.
5210 Constant *Comp =
5211 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5212 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5213 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5214 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5215 return ReplaceInstUsesWith(ICI, Cst);
5216 }
5217
5218 if (LHSI->hasOneUse()) {
5219 // Otherwise strength reduce the shift into an and.
5220 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5221 Constant *Mask =
5222 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5223
5224 Instruction *AndI =
5225 BinaryOperator::createAnd(LHSI->getOperand(0),
5226 Mask, LHSI->getName()+".mask");
5227 Value *And = InsertNewInstBefore(AndI, ICI);
5228 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnere5bbb3c2007-04-03 23:29:39 +00005229 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00005230 }
5231 }
5232 }
5233 break;
5234
5235 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5236 case Instruction::AShr:
5237 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5238 if (ICI.isEquality()) {
5239 // Check that the shift amount is in range. If not, don't perform
5240 // undefined shifts. When the shift is visited it will be
5241 // simplified.
5242 uint32_t TypeBits = RHSV.getBitWidth();
5243 if (ShAmt->uge(TypeBits))
5244 break;
5245 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5246
5247 // If we are comparing against bits always shifted out, the
5248 // comparison cannot succeed.
5249 APInt Comp = RHSV << ShAmtVal;
5250 if (LHSI->getOpcode() == Instruction::LShr)
5251 Comp = Comp.lshr(ShAmtVal);
5252 else
5253 Comp = Comp.ashr(ShAmtVal);
5254
5255 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5256 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5257 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5258 return ReplaceInstUsesWith(ICI, Cst);
5259 }
5260
5261 if (LHSI->hasOneUse() || RHSV == 0) {
5262 // Otherwise strength reduce the shift into an and.
5263 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5264 Constant *Mask = ConstantInt::get(Val);
5265
5266 Instruction *AndI =
5267 BinaryOperator::createAnd(LHSI->getOperand(0),
5268 Mask, LHSI->getName()+".mask");
5269 Value *And = InsertNewInstBefore(AndI, ICI);
5270 return new ICmpInst(ICI.getPredicate(), And,
5271 ConstantExpr::getShl(RHS, ShAmt));
5272 }
5273 }
5274 }
5275 break;
5276
5277 case Instruction::SDiv:
5278 case Instruction::UDiv:
5279 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5280 // Fold this div into the comparison, producing a range check.
5281 // Determine, based on the divide type, what the range is being
5282 // checked. If there is an overflow on the low or high side, remember
5283 // it, otherwise compute the range [low, hi) bounding the new value.
5284 // See: InsertRangeTest above for the kinds of replacements possible.
5285 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5286 // FIXME: If the operand types don't match the type of the divide
5287 // then don't attempt this transform. The code below doesn't have the
5288 // logic to deal with a signed divide and an unsigned compare (and
5289 // vice versa). This is because (x /s C1) <s C2 produces different
5290 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5291 // (x /u C1) <u C2. Simply casting the operands and result won't
5292 // work. :( The if statement below tests that condition and bails
5293 // if it finds it.
5294 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5295 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5296 break;
5297 if (DivRHS->isZero())
5298 break; // Don't hack on div by zero
5299
5300 // Initialize the variables that will indicate the nature of the
5301 // range check.
5302 bool LoOverflow = false, HiOverflow = false;
5303 ConstantInt *LoBound = 0, *HiBound = 0;
5304
5305 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5306 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5307 // C2 (CI). By solving for X we can turn this into a range check
5308 // instead of computing a divide.
5309 ConstantInt *Prod = Multiply(RHS, DivRHS);
5310
5311 // Determine if the product overflows by seeing if the product is
5312 // not equal to the divide. Make sure we do the same kind of divide
5313 // as in the LHS instruction that we're folding.
5314 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5315 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5316
5317 // Get the ICmp opcode
5318 ICmpInst::Predicate predicate = ICI.getPredicate();
5319
5320 if (!DivIsSigned) { // udiv
5321 LoBound = Prod;
5322 LoOverflow = ProdOV;
5323 HiOverflow = ProdOV ||
5324 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5325 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5326 if (RHSV == 0) { // (X / pos) op 0
5327 // Can't overflow.
5328 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5329 HiBound = DivRHS;
5330 } else if (RHSV.isPositive()) { // (X / pos) op pos
5331 LoBound = Prod;
5332 LoOverflow = ProdOV;
5333 HiOverflow = ProdOV ||
5334 AddWithOverflow(HiBound, Prod, DivRHS, true);
5335 } else { // (X / pos) op neg
5336 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5337 LoOverflow = AddWithOverflow(LoBound, Prod,
5338 cast<ConstantInt>(DivRHSH), true);
5339 HiBound = AddOne(Prod);
5340 HiOverflow = ProdOV;
5341 }
5342 } else { // Divisor is < 0.
5343 if (RHSV == 0) { // (X / neg) op 0
5344 LoBound = AddOne(DivRHS);
5345 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5346 if (HiBound == DivRHS)
5347 LoBound = 0; // - INTMIN = INTMIN
5348 } else if (RHSV.isPositive()) { // (X / neg) op pos
5349 HiOverflow = LoOverflow = ProdOV;
5350 if (!LoOverflow)
5351 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5352 true);
5353 HiBound = AddOne(Prod);
5354 } else { // (X / neg) op neg
5355 LoBound = Prod;
5356 LoOverflow = HiOverflow = ProdOV;
5357 HiBound = Subtract(Prod, DivRHS);
5358 }
5359
5360 // Dividing by a negate swaps the condition.
5361 predicate = ICmpInst::getSwappedPredicate(predicate);
5362 }
5363
5364 if (LoBound) {
5365 Value *X = LHSI->getOperand(0);
5366 switch (predicate) {
5367 default: assert(0 && "Unhandled icmp opcode!");
5368 case ICmpInst::ICMP_EQ:
5369 if (LoOverflow && HiOverflow)
5370 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5371 else if (HiOverflow)
5372 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5373 ICmpInst::ICMP_UGE, X, LoBound);
5374 else if (LoOverflow)
5375 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5376 ICmpInst::ICMP_ULT, X, HiBound);
5377 else
5378 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5379 true, ICI);
5380 case ICmpInst::ICMP_NE:
5381 if (LoOverflow && HiOverflow)
5382 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5383 else if (HiOverflow)
5384 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5385 ICmpInst::ICMP_ULT, X, LoBound);
5386 else if (LoOverflow)
5387 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5388 ICmpInst::ICMP_UGE, X, HiBound);
5389 else
5390 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5391 false, ICI);
5392 case ICmpInst::ICMP_ULT:
5393 case ICmpInst::ICMP_SLT:
5394 if (LoOverflow)
5395 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5396 return new ICmpInst(predicate, X, LoBound);
5397 case ICmpInst::ICMP_UGT:
5398 case ICmpInst::ICMP_SGT:
5399 if (HiOverflow)
5400 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5401 if (predicate == ICmpInst::ICMP_UGT)
5402 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5403 else
5404 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5405 }
5406 }
5407 }
5408 break;
5409 }
5410
5411 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5412 if (ICI.isEquality()) {
5413 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5414
5415 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5416 // the second operand is a constant, simplify a bit.
5417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5418 switch (BO->getOpcode()) {
5419 case Instruction::SRem:
5420 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5421 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5422 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5423 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5424 Instruction *NewRem =
5425 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5426 BO->getName());
5427 InsertNewInstBefore(NewRem, ICI);
5428 return new ICmpInst(ICI.getPredicate(), NewRem,
5429 Constant::getNullValue(BO->getType()));
5430 }
5431 }
5432 break;
5433 case Instruction::Add:
5434 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5435 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5436 if (BO->hasOneUse())
5437 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5438 Subtract(RHS, BOp1C));
5439 } else if (RHSV == 0) {
5440 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5441 // efficiently invertible, or if the add has just this one use.
5442 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5443
5444 if (Value *NegVal = dyn_castNegVal(BOp1))
5445 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5446 else if (Value *NegVal = dyn_castNegVal(BOp0))
5447 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5448 else if (BO->hasOneUse()) {
5449 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5450 InsertNewInstBefore(Neg, ICI);
5451 Neg->takeName(BO);
5452 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5453 }
5454 }
5455 break;
5456 case Instruction::Xor:
5457 // For the xor case, we can xor two constants together, eliminating
5458 // the explicit xor.
5459 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5460 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5461 ConstantExpr::getXor(RHS, BOC));
5462
5463 // FALLTHROUGH
5464 case Instruction::Sub:
5465 // Replace (([sub|xor] A, B) != 0) with (A != B)
5466 if (RHSV == 0)
5467 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5468 BO->getOperand(1));
5469 break;
5470
5471 case Instruction::Or:
5472 // If bits are being or'd in that are not present in the constant we
5473 // are comparing against, then the comparison could never succeed!
5474 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5475 Constant *NotCI = ConstantExpr::getNot(RHS);
5476 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5477 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5478 isICMP_NE));
5479 }
5480 break;
5481
5482 case Instruction::And:
5483 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5484 // If bits are being compared against that are and'd out, then the
5485 // comparison can never succeed!
5486 if ((RHSV & ~BOC->getValue()) != 0)
5487 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5488 isICMP_NE));
5489
5490 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5491 if (RHS == BOC && RHSV.isPowerOf2())
5492 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5493 ICmpInst::ICMP_NE, LHSI,
5494 Constant::getNullValue(RHS->getType()));
5495
5496 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5497 if (isSignBit(BOC)) {
5498 Value *X = BO->getOperand(0);
5499 Constant *Zero = Constant::getNullValue(X->getType());
5500 ICmpInst::Predicate pred = isICMP_NE ?
5501 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5502 return new ICmpInst(pred, X, Zero);
5503 }
5504
5505 // ((X & ~7) == 0) --> X < 8
5506 if (RHSV == 0 && isHighOnes(BOC)) {
5507 Value *X = BO->getOperand(0);
5508 Constant *NegX = ConstantExpr::getNeg(BOC);
5509 ICmpInst::Predicate pred = isICMP_NE ?
5510 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5511 return new ICmpInst(pred, X, NegX);
5512 }
5513 }
5514 default: break;
5515 }
5516 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5517 // Handle icmp {eq|ne} <intrinsic>, intcst.
5518 if (II->getIntrinsicID() == Intrinsic::bswap) {
5519 AddToWorkList(II);
5520 ICI.setOperand(0, II->getOperand(1));
5521 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5522 return &ICI;
5523 }
5524 }
5525 } else { // Not a ICMP_EQ/ICMP_NE
5526 // If the LHS is a cast from an integral value of the same size, then
5527 // since we know the RHS is a constant, try to simlify.
5528 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5529 Value *CastOp = Cast->getOperand(0);
5530 const Type *SrcTy = CastOp->getType();
5531 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5532 if (SrcTy->isInteger() &&
5533 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5534 // If this is an unsigned comparison, try to make the comparison use
5535 // smaller constant values.
5536 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5537 // X u< 128 => X s> -1
5538 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5539 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5540 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5541 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5542 // X u> 127 => X s< 0
5543 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5544 Constant::getNullValue(SrcTy));
5545 }
5546 }
5547 }
5548 }
5549 return 0;
5550}
5551
5552/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5553/// We only handle extending casts so far.
5554///
Reid Spencer266e42b2006-12-23 06:05:41 +00005555Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5556 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005557 Value *LHSCIOp = LHSCI->getOperand(0);
5558 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005559 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005560 Value *RHSCIOp;
5561
Reid Spencer266e42b2006-12-23 06:05:41 +00005562 // We only handle extension cast instructions, so far. Enforce this.
5563 if (LHSCI->getOpcode() != Instruction::ZExt &&
5564 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005565 return 0;
5566
Reid Spencer266e42b2006-12-23 06:05:41 +00005567 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5568 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005569
Reid Spencer266e42b2006-12-23 06:05:41 +00005570 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005571 // Not an extension from the same type?
5572 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005573 if (RHSCIOp->getType() != LHSCIOp->getType())
5574 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005575
5576 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5577 // and the other is a zext), then we can't handle this.
5578 if (CI->getOpcode() != LHSCI->getOpcode())
5579 return 0;
5580
5581 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5582 // then we can't handle this.
5583 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5584 return 0;
5585
5586 // Okay, just insert a compare of the reduced operands now!
5587 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005588 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005589
Reid Spencer266e42b2006-12-23 06:05:41 +00005590 // If we aren't dealing with a constant on the RHS, exit early
5591 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5592 if (!CI)
5593 return 0;
5594
5595 // Compute the constant that would happen if we truncated to SrcTy then
5596 // reextended to DestTy.
5597 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5598 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5599
5600 // If the re-extended constant didn't change...
5601 if (Res2 == CI) {
5602 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5603 // For example, we might have:
5604 // %A = sext short %X to uint
5605 // %B = icmp ugt uint %A, 1330
5606 // It is incorrect to transform this into
5607 // %B = icmp ugt short %X, 1330
5608 // because %A may have negative value.
5609 //
5610 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5611 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005612 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005613 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5614 else
5615 return 0;
5616 }
5617
5618 // The re-extended constant changed so the constant cannot be represented
5619 // in the shorter type. Consequently, we cannot emit a simple comparison.
5620
5621 // First, handle some easy cases. We know the result cannot be equal at this
5622 // point so handle the ICI.isEquality() cases
5623 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005624 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005625 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005626 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005627
5628 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5629 // should have been folded away previously and not enter in here.
5630 Value *Result;
5631 if (isSignedCmp) {
5632 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005633 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005634 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005635 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005636 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005637 } else {
5638 // We're performing an unsigned comparison.
5639 if (isSignedExt) {
5640 // We're performing an unsigned comp with a sign extended value.
5641 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005642 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005643 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5644 NegOne, ICI.getName()), ICI);
5645 } else {
5646 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005647 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005648 }
5649 }
5650
5651 // Finally, return the value computed.
5652 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5653 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5654 return ReplaceInstUsesWith(ICI, Result);
5655 } else {
5656 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5657 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5658 "ICmp should be folded!");
5659 if (Constant *CI = dyn_cast<Constant>(Result))
5660 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5661 else
5662 return BinaryOperator::createNot(Result);
5663 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005664}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005665
Reid Spencer2341c222007-02-02 02:16:23 +00005666Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5667 return commonShiftTransforms(I);
5668}
5669
5670Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5671 return commonShiftTransforms(I);
5672}
5673
5674Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5675 return commonShiftTransforms(I);
5676}
5677
5678Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5679 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005680 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005681
5682 // shl X, 0 == X and shr X, 0 == X
5683 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005684 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005685 Op0 == Constant::getNullValue(Op0->getType()))
5686 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005687
Reid Spencer266e42b2006-12-23 06:05:41 +00005688 if (isa<UndefValue>(Op0)) {
5689 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005690 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005691 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005692 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5693 }
5694 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005695 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5696 return ReplaceInstUsesWith(I, Op0);
5697 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005698 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005699 }
5700
Chris Lattnerd4dee402006-11-10 23:38:52 +00005701 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5702 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005703 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005704 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005705 return ReplaceInstUsesWith(I, CSI);
5706
Chris Lattner183b3362004-04-09 19:05:30 +00005707 // Try to fold constant and into select arguments.
5708 if (isa<Constant>(Op0))
5709 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005710 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005711 return R;
5712
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005713 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005714 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005715 if (MaskedValueIsZero(Op0,
5716 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005717 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005718 }
5719 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005720
Reid Spencere0fc4df2006-10-20 07:07:24 +00005721 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005722 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5723 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005724 return 0;
5725}
5726
Reid Spencere0fc4df2006-10-20 07:07:24 +00005727Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005728 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005729 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005730
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005731 // See if we can simplify any instructions used by the instruction whose sole
5732 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005733 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5734 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5735 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005736 KnownZero, KnownOne))
5737 return &I;
5738
Chris Lattner14553932006-01-06 07:12:35 +00005739 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5740 // of a signed value.
5741 //
Zhou Shengb25806f2007-03-30 09:29:48 +00005742 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005743 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005744 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5745 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005746 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005747 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005748 }
Chris Lattner14553932006-01-06 07:12:35 +00005749 }
5750
5751 // ((X*C1) << C2) == (X * (C1 << C2))
5752 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5753 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5754 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5755 return BinaryOperator::createMul(BO->getOperand(0),
5756 ConstantExpr::getShl(BOOp, Op1));
5757
5758 // Try to fold constant and into select arguments.
5759 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5760 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5761 return R;
5762 if (isa<PHINode>(Op0))
5763 if (Instruction *NV = FoldOpIntoPhi(I))
5764 return NV;
5765
5766 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005767 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5768 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5769 Value *V1, *V2;
5770 ConstantInt *CC;
5771 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005772 default: break;
5773 case Instruction::Add:
5774 case Instruction::And:
5775 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005776 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005777 // These operators commute.
5778 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005779 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5780 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005781 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005782 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005783 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005784 Op0BO->getName());
5785 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005786 Instruction *X =
5787 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5788 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005789 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005790 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005791 return BinaryOperator::createAnd(X, ConstantInt::get(
5792 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005793 }
Chris Lattner14553932006-01-06 07:12:35 +00005794
Chris Lattner797dee72005-09-18 06:30:59 +00005795 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005796 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005797 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005798 match(Op0BOOp1,
5799 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005800 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5801 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005802 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005803 Op0BO->getOperand(0), Op1,
5804 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005805 InsertNewInstBefore(YS, I); // (Y << C)
5806 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005807 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005808 V1->getName()+".mask");
5809 InsertNewInstBefore(XM, I); // X & (CC << C)
5810
5811 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5812 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005813 }
Chris Lattner14553932006-01-06 07:12:35 +00005814
Reid Spencer2f34b982007-02-02 14:41:37 +00005815 // FALL THROUGH.
5816 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005817 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005818 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5819 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005820 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005821 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005822 Op0BO->getOperand(1), Op1,
5823 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005824 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005825 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005826 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005827 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005828 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005829 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005830 return BinaryOperator::createAnd(X, ConstantInt::get(
5831 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005832 }
Chris Lattner14553932006-01-06 07:12:35 +00005833
Chris Lattner1df0e982006-05-31 21:14:00 +00005834 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005835 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5836 match(Op0BO->getOperand(0),
5837 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005838 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005839 cast<BinaryOperator>(Op0BO->getOperand(0))
5840 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005841 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005842 Op0BO->getOperand(1), Op1,
5843 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005844 InsertNewInstBefore(YS, I); // (Y << C)
5845 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005846 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005847 V1->getName()+".mask");
5848 InsertNewInstBefore(XM, I); // X & (CC << C)
5849
Chris Lattner1df0e982006-05-31 21:14:00 +00005850 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005851 }
Chris Lattner14553932006-01-06 07:12:35 +00005852
Chris Lattner27cb9db2005-09-18 05:12:10 +00005853 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005854 }
Chris Lattner14553932006-01-06 07:12:35 +00005855 }
5856
5857
5858 // If the operand is an bitwise operator with a constant RHS, and the
5859 // shift is the only use, we can pull it out of the shift.
5860 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5861 bool isValid = true; // Valid only for And, Or, Xor
5862 bool highBitSet = false; // Transform if high bit of constant set?
5863
5864 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005865 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005866 case Instruction::Add:
5867 isValid = isLeftShift;
5868 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005869 case Instruction::Or:
5870 case Instruction::Xor:
5871 highBitSet = false;
5872 break;
5873 case Instruction::And:
5874 highBitSet = true;
5875 break;
Chris Lattner14553932006-01-06 07:12:35 +00005876 }
5877
5878 // If this is a signed shift right, and the high bit is modified
5879 // by the logical operation, do not perform the transformation.
5880 // The highBitSet boolean indicates the value of the high bit of
5881 // the constant which would cause it to be modified for this
5882 // operation.
5883 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005884 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005885 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005886 }
5887
5888 if (isValid) {
5889 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5890
5891 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005892 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005893 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005894 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005895
5896 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5897 NewRHS);
5898 }
5899 }
5900 }
5901 }
5902
Chris Lattnereb372a02006-01-06 07:52:12 +00005903 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005904 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5905 if (ShiftOp && !ShiftOp->isShift())
5906 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005907
Reid Spencere0fc4df2006-10-20 07:07:24 +00005908 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005909 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00005910 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5911 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00005912 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5913 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5914 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005915
Zhou Sheng56cda952007-04-02 08:20:41 +00005916 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005917 if (AmtSum > TypeBits)
5918 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005919
5920 const IntegerType *Ty = cast<IntegerType>(I.getType());
5921
5922 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005923 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005924 return BinaryOperator::create(I.getOpcode(), X,
5925 ConstantInt::get(Ty, AmtSum));
5926 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5927 I.getOpcode() == Instruction::AShr) {
5928 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5929 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5930 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5931 I.getOpcode() == Instruction::LShr) {
5932 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5933 Instruction *Shift =
5934 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5935 InsertNewInstBefore(Shift, I);
5936
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005937 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005938 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005939 }
5940
Chris Lattner3e009e82007-02-05 00:57:54 +00005941 // Okay, if we get here, one shift must be left, and the other shift must be
5942 // right. See if the amounts are equal.
5943 if (ShiftAmt1 == ShiftAmt2) {
5944 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5945 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005946 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005947 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005948 }
5949 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5950 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005951 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005952 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005953 }
5954 // We can simplify ((X << C) >>s C) into a trunc + sext.
5955 // NOTE: we could do this for any C, but that would make 'unusual' integer
5956 // types. For now, just stick to ones well-supported by the code
5957 // generators.
5958 const Type *SExtType = 0;
5959 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005960 case 1 :
5961 case 8 :
5962 case 16 :
5963 case 32 :
5964 case 64 :
5965 case 128:
5966 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5967 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005968 default: break;
5969 }
5970 if (SExtType) {
5971 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5972 InsertNewInstBefore(NewTrunc, I);
5973 return new SExtInst(NewTrunc, Ty);
5974 }
5975 // Otherwise, we can't handle it yet.
5976 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00005977 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005978
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005979 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005980 if (I.getOpcode() == Instruction::Shl) {
5981 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5982 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005983 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005984 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005985 InsertNewInstBefore(Shift, I);
5986
Reid Spencer52830322007-03-25 21:11:44 +00005987 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5988 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005989 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005990
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005991 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005992 if (I.getOpcode() == Instruction::LShr) {
5993 assert(ShiftOp->getOpcode() == Instruction::Shl);
5994 Instruction *Shift =
5995 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5996 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005997
Reid Spencer769a5a82007-03-26 17:18:58 +00005998 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005999 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006000 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006001
6002 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6003 } else {
6004 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00006005 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006006
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006007 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006008 if (I.getOpcode() == Instruction::Shl) {
6009 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6010 ShiftOp->getOpcode() == Instruction::AShr);
6011 Instruction *Shift =
6012 BinaryOperator::create(ShiftOp->getOpcode(), X,
6013 ConstantInt::get(Ty, ShiftDiff));
6014 InsertNewInstBefore(Shift, I);
6015
Reid Spencer52830322007-03-25 21:11:44 +00006016 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006017 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006018 }
6019
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006020 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006021 if (I.getOpcode() == Instruction::LShr) {
6022 assert(ShiftOp->getOpcode() == Instruction::Shl);
6023 Instruction *Shift =
6024 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6025 InsertNewInstBefore(Shift, I);
6026
Reid Spencer441486c2007-03-26 23:45:51 +00006027 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006028 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006029 }
6030
6031 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006032 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006033 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006034 return 0;
6035}
6036
Chris Lattner48a44f72002-05-02 17:06:02 +00006037
Chris Lattner8f663e82005-10-29 04:36:15 +00006038/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6039/// expression. If so, decompose it, returning some value X, such that Val is
6040/// X*Scale+Offset.
6041///
6042static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006043 int &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006044 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006045 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006046 Offset = CI->getZExtValue();
6047 Scale = 1;
6048 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006049 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6050 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006051 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006052 if (I->getOpcode() == Instruction::Shl) {
6053 // This is a value scaled by '1 << the shift amt'.
6054 Scale = 1U << CUI->getZExtValue();
6055 Offset = 0;
6056 return I->getOperand(0);
6057 } else if (I->getOpcode() == Instruction::Mul) {
6058 // This value is scaled by 'CUI'.
6059 Scale = CUI->getZExtValue();
6060 Offset = 0;
6061 return I->getOperand(0);
6062 } else if (I->getOpcode() == Instruction::Add) {
6063 // We have X+C. Check to see if we really have (X*C2)+C1,
6064 // where C1 is divisible by C2.
6065 unsigned SubScale;
6066 Value *SubVal =
6067 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6068 Offset += CUI->getZExtValue();
6069 if (SubScale > 1 && (Offset % SubScale == 0)) {
6070 Scale = SubScale;
6071 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006072 }
6073 }
6074 }
6075 }
6076 }
6077
6078 // Otherwise, we can't look past this.
6079 Scale = 1;
6080 Offset = 0;
6081 return Val;
6082}
6083
6084
Chris Lattner216be912005-10-24 06:03:58 +00006085/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6086/// try to eliminate the cast by moving the type information into the alloc.
6087Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6088 AllocationInst &AI) {
6089 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006090 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006091
Chris Lattnerac87beb2005-10-24 06:22:12 +00006092 // Remove any uses of AI that are dead.
6093 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006094
Chris Lattnerac87beb2005-10-24 06:22:12 +00006095 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6096 Instruction *User = cast<Instruction>(*UI++);
6097 if (isInstructionTriviallyDead(User)) {
6098 while (UI != E && *UI == User)
6099 ++UI; // If this instruction uses AI more than once, don't break UI.
6100
Chris Lattnerac87beb2005-10-24 06:22:12 +00006101 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006102 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006103 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006104 }
6105 }
6106
Chris Lattner216be912005-10-24 06:03:58 +00006107 // Get the type really allocated and the type casted to.
6108 const Type *AllocElTy = AI.getAllocatedType();
6109 const Type *CastElTy = PTy->getElementType();
6110 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006111
Chris Lattner945e4372007-02-14 05:52:17 +00006112 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6113 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006114 if (CastElTyAlign < AllocElTyAlign) return 0;
6115
Chris Lattner46705b22005-10-24 06:35:18 +00006116 // If the allocation has multiple uses, only promote it if we are strictly
6117 // increasing the alignment of the resultant allocation. If we keep it the
6118 // same, we open the door to infinite loops of various kinds.
6119 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6120
Chris Lattner216be912005-10-24 06:03:58 +00006121 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6122 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006123 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006124
Chris Lattner8270c332005-10-29 03:19:53 +00006125 // See if we can satisfy the modulus by pulling a scale out of the array
6126 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006127 unsigned ArraySizeScale;
6128 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00006129 Value *NumElements = // See if the array size is a decomposable linear expr.
6130 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6131
Chris Lattner8270c332005-10-29 03:19:53 +00006132 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6133 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006134 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6135 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006136
Chris Lattner8270c332005-10-29 03:19:53 +00006137 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6138 Value *Amt = 0;
6139 if (Scale == 1) {
6140 Amt = NumElements;
6141 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006142 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006143 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6144 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00006145 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006146 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006147 else if (Scale != 1) {
6148 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6149 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006150 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006151 }
6152
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006153 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6154 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattner8f663e82005-10-29 04:36:15 +00006155 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6156 Amt = InsertNewInstBefore(Tmp, AI);
6157 }
6158
Chris Lattner216be912005-10-24 06:03:58 +00006159 AllocationInst *New;
6160 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006161 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006162 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006163 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006164 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006165 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006166
6167 // If the allocation has multiple uses, insert a cast and change all things
6168 // that used it to use the new cast. This will also hack on CI, but it will
6169 // die soon.
6170 if (!AI.hasOneUse()) {
6171 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006172 // New is the allocation instruction, pointer typed. AI is the original
6173 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6174 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006175 InsertNewInstBefore(NewCast, AI);
6176 AI.replaceAllUsesWith(NewCast);
6177 }
Chris Lattner216be912005-10-24 06:03:58 +00006178 return ReplaceInstUsesWith(CI, New);
6179}
6180
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006181/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006182/// and return it as type Ty without inserting any new casts and without
6183/// changing the computed value. This is used by code that tries to decide
6184/// whether promoting or shrinking integer operations to wider or smaller types
6185/// will allow us to eliminate a truncate or extend.
6186///
6187/// This is a truncation operation if Ty is smaller than V->getType(), or an
6188/// extension operation if Ty is larger.
6189static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006190 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006191 // We can always evaluate constants in another type.
6192 if (isa<ConstantInt>(V))
6193 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006194
6195 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006196 if (!I) return false;
6197
6198 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006199
6200 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006201 case Instruction::Add:
6202 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006203 case Instruction::And:
6204 case Instruction::Or:
6205 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006206 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006207 // These operators can all arbitrarily be extended or truncated.
6208 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6209 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006210
Chris Lattner960acb02006-11-29 07:18:39 +00006211 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006212 if (!I->hasOneUse()) return false;
6213 // If we are truncating the result of this SHL, and if it's a shift of a
6214 // constant amount, we can always perform a SHL in a smaller type.
6215 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006216 uint32_t BitWidth = Ty->getBitWidth();
6217 if (BitWidth < OrigTy->getBitWidth() &&
6218 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006219 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6220 }
6221 break;
6222 case Instruction::LShr:
6223 if (!I->hasOneUse()) return false;
6224 // If this is a truncate of a logical shr, we can truncate it to a smaller
6225 // lshr iff we know that the bits we would otherwise be shifting in are
6226 // already zeros.
6227 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006228 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6229 uint32_t BitWidth = Ty->getBitWidth();
6230 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006231 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00006232 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6233 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006234 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6235 }
6236 }
Chris Lattner960acb02006-11-29 07:18:39 +00006237 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006238 case Instruction::Trunc:
6239 case Instruction::ZExt:
6240 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006241 // If this is a cast from the destination type, we can trivially eliminate
6242 // it, and this will remove a cast overall.
6243 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006244 // If the first operand is itself a cast, and is eliminable, do not count
6245 // this as an eliminable cast. We would prefer to eliminate those two
6246 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006247 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006248 return true;
6249
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006250 ++NumCastsRemoved;
6251 return true;
6252 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006253 break;
6254 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006255 // TODO: Can handle more cases here.
6256 break;
6257 }
6258
6259 return false;
6260}
6261
6262/// EvaluateInDifferentType - Given an expression that
6263/// CanEvaluateInDifferentType returns true for, actually insert the code to
6264/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006265Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006266 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006267 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006268 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006269
6270 // Otherwise, it must be an instruction.
6271 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006272 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006273 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006274 case Instruction::Add:
6275 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006276 case Instruction::And:
6277 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006278 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006279 case Instruction::AShr:
6280 case Instruction::LShr:
6281 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006282 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006283 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6284 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6285 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006286 break;
6287 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006288 case Instruction::Trunc:
6289 case Instruction::ZExt:
6290 case Instruction::SExt:
6291 case Instruction::BitCast:
6292 // If the source type of the cast is the type we're trying for then we can
6293 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006294 if (I->getOperand(0)->getType() == Ty)
6295 return I->getOperand(0);
6296
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006297 // Some other kind of cast, which shouldn't happen, so just ..
6298 // FALL THROUGH
6299 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006300 // TODO: Can handle more cases here.
6301 assert(0 && "Unreachable!");
6302 break;
6303 }
6304
6305 return InsertNewInstBefore(Res, *I);
6306}
6307
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006308/// @brief Implement the transforms common to all CastInst visitors.
6309Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006310 Value *Src = CI.getOperand(0);
6311
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006312 // Casting undef to anything results in undef so might as just replace it and
6313 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006314 if (isa<UndefValue>(Src)) // cast undef -> undef
6315 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6316
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006317 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6318 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006319 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006320 if (Instruction::CastOps opc =
6321 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6322 // The first cast (CSrc) is eliminable so we need to fix up or replace
6323 // the second cast (CI). CSrc will then have a good chance of being dead.
6324 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006325 }
6326 }
Chris Lattner03841652004-05-25 04:29:21 +00006327
Chris Lattnerd0d51602003-06-21 23:12:02 +00006328 // If casting the result of a getelementptr instruction with no offset, turn
6329 // this into a cast of the original pointer!
6330 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006331 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006332 bool AllZeroOperands = true;
6333 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6334 if (!isa<Constant>(GEP->getOperand(i)) ||
6335 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6336 AllZeroOperands = false;
6337 break;
6338 }
6339 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006340 // Changing the cast operand is usually not a good idea but it is safe
6341 // here because the pointer operand is being replaced with another
6342 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006343 CI.setOperand(0, GEP->getOperand(0));
6344 return &CI;
6345 }
6346 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006347
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006348 // If we are casting a malloc or alloca to a pointer to a type of the same
6349 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006350 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006351 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6352 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006353
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006354 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006355 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6356 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6357 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006358
6359 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006360 if (isa<PHINode>(Src))
6361 if (Instruction *NV = FoldOpIntoPhi(CI))
6362 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006363
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006364 return 0;
6365}
6366
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006367/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6368/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006369/// cases.
6370/// @brief Implement the transforms common to CastInst with integer operands
6371Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6372 if (Instruction *Result = commonCastTransforms(CI))
6373 return Result;
6374
6375 Value *Src = CI.getOperand(0);
6376 const Type *SrcTy = Src->getType();
6377 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006378 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6379 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006380
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381 // See if we can simplify any instructions used by the LHS whose sole
6382 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006383 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6384 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006385 KnownZero, KnownOne))
6386 return &CI;
6387
6388 // If the source isn't an instruction or has more than one use then we
6389 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006390 Instruction *SrcI = dyn_cast<Instruction>(Src);
6391 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006392 return 0;
6393
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006394 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006395 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006396 if (!isa<BitCastInst>(CI) &&
6397 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6398 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006399 // If this cast is a truncate, evaluting in a different type always
6400 // eliminates the cast, so it is always a win. If this is a noop-cast
6401 // this just removes a noop cast which isn't pointful, but simplifies
6402 // the code. If this is a zero-extension, we need to do an AND to
6403 // maintain the clear top-part of the computation, so we require that
6404 // the input have eliminated at least one cast. If this is a sign
6405 // extension, we insert two new casts (to do the extension) so we
6406 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006407 bool DoXForm;
6408 switch (CI.getOpcode()) {
6409 default:
6410 // All the others use floating point so we shouldn't actually
6411 // get here because of the check above.
6412 assert(0 && "Unknown cast type");
6413 case Instruction::Trunc:
6414 DoXForm = true;
6415 break;
6416 case Instruction::ZExt:
6417 DoXForm = NumCastsRemoved >= 1;
6418 break;
6419 case Instruction::SExt:
6420 DoXForm = NumCastsRemoved >= 2;
6421 break;
6422 case Instruction::BitCast:
6423 DoXForm = false;
6424 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006425 }
6426
6427 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006428 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6429 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006430 assert(Res->getType() == DestTy);
6431 switch (CI.getOpcode()) {
6432 default: assert(0 && "Unknown cast type!");
6433 case Instruction::Trunc:
6434 case Instruction::BitCast:
6435 // Just replace this cast with the result.
6436 return ReplaceInstUsesWith(CI, Res);
6437 case Instruction::ZExt: {
6438 // We need to emit an AND to clear the high bits.
6439 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00006440 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6441 SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006442 return BinaryOperator::createAnd(Res, C);
6443 }
6444 case Instruction::SExt:
6445 // We need to emit a cast to truncate, then a cast to sext.
6446 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006447 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6448 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006449 }
6450 }
6451 }
6452
6453 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6454 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6455
6456 switch (SrcI->getOpcode()) {
6457 case Instruction::Add:
6458 case Instruction::Mul:
6459 case Instruction::And:
6460 case Instruction::Or:
6461 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00006462 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006463 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6464 // Don't insert two casts if they cannot be eliminated. We allow
6465 // two casts to be inserted if the sizes are the same. This could
6466 // only be converting signedness, which is a noop.
6467 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006468 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6469 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006470 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006471 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6472 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6473 return BinaryOperator::create(
6474 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006475 }
6476 }
6477
6478 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6479 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6480 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006481 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006482 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006483 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006484 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6485 }
6486 break;
6487 case Instruction::SDiv:
6488 case Instruction::UDiv:
6489 case Instruction::SRem:
6490 case Instruction::URem:
6491 // If we are just changing the sign, rewrite.
6492 if (DestBitSize == SrcBitSize) {
6493 // Don't insert two casts if they cannot be eliminated. We allow
6494 // two casts to be inserted if the sizes are the same. This could
6495 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006496 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6497 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006498 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6499 Op0, DestTy, SrcI);
6500 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6501 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006502 return BinaryOperator::create(
6503 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6504 }
6505 }
6506 break;
6507
6508 case Instruction::Shl:
6509 // Allow changing the sign of the source operand. Do not allow
6510 // changing the size of the shift, UNLESS the shift amount is a
6511 // constant. We must not change variable sized shifts to a smaller
6512 // size, because it is undefined to shift more bits out than exist
6513 // in the value.
6514 if (DestBitSize == SrcBitSize ||
6515 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006516 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6517 Instruction::BitCast : Instruction::Trunc);
6518 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006519 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006520 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006521 }
6522 break;
6523 case Instruction::AShr:
6524 // If this is a signed shr, and if all bits shifted in are about to be
6525 // truncated off, turn it into an unsigned shr to allow greater
6526 // simplifications.
6527 if (DestBitSize < SrcBitSize &&
6528 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006529 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006530 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6531 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006532 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006533 }
6534 }
6535 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006536 }
6537 return 0;
6538}
6539
Chris Lattner74ff60f2007-04-11 06:57:46 +00006540Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006541 if (Instruction *Result = commonIntCastTransforms(CI))
6542 return Result;
6543
6544 Value *Src = CI.getOperand(0);
6545 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006546 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6547 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006548
6549 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6550 switch (SrcI->getOpcode()) {
6551 default: break;
6552 case Instruction::LShr:
6553 // We can shrink lshr to something smaller if we know the bits shifted in
6554 // are already zeros.
6555 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006556 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00006557
6558 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006559 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006560 Value* SrcIOp0 = SrcI->getOperand(0);
6561 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006562 if (ShAmt >= DestBitWidth) // All zeros.
6563 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6564
6565 // Okay, we can shrink this. Truncate the input, then return a new
6566 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006567 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6568 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6569 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006570 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006571 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006572 } else { // This is a variable shr.
6573
6574 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6575 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6576 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006577 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006578 Value *One = ConstantInt::get(SrcI->getType(), 1);
6579
Reid Spencer2341c222007-02-02 02:16:23 +00006580 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006581 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006582 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006583 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6584 SrcI->getOperand(0),
6585 "tmp"), CI);
6586 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006587 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006588 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006589 }
6590 break;
6591 }
6592 }
6593
6594 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006595}
6596
Chris Lattner74ff60f2007-04-11 06:57:46 +00006597Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006598 // If one of the common conversion will work ..
6599 if (Instruction *Result = commonIntCastTransforms(CI))
6600 return Result;
6601
6602 Value *Src = CI.getOperand(0);
6603
6604 // If this is a cast of a cast
6605 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006606 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6607 // types and if the sizes are just right we can convert this into a logical
6608 // 'and' which will be much cheaper than the pair of casts.
6609 if (isa<TruncInst>(CSrc)) {
6610 // Get the sizes of the types involved
6611 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00006612 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6613 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6614 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006615 // If we're actually extending zero bits and the trunc is a no-op
6616 if (MidSize < DstSize && SrcSize == DstSize) {
6617 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006618 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006619 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006620 Instruction *And =
6621 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6622 // Unfortunately, if the type changed, we need to cast it back.
6623 if (And->getType() != CI.getType()) {
6624 And->setName(CSrc->getName()+".mask");
6625 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006626 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006627 }
6628 return And;
6629 }
6630 }
6631 }
6632
Chris Lattner7ddbff02007-04-11 05:45:39 +00006633 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6634 // If we are just checking for a icmp eq of a single bit and zext'ing it
6635 // to an integer, then shift the bit to the appropriate place and then
6636 // cast to integer to avoid the comparison.
6637 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00006638 const APInt &Op1CV = Op1C->getValue();
Chris Lattnerd0f79422007-04-11 06:53:04 +00006639
6640 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6641 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6642 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6643 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6644 Value *In = ICI->getOperand(0);
6645 Value *Sh = ConstantInt::get(In->getType(),
6646 In->getType()->getPrimitiveSizeInBits()-1);
6647 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6648 In->getName()+".lobit"),
6649 CI);
6650 if (In->getType() != CI.getType())
6651 In = CastInst::createIntegerCast(In, CI.getType(),
6652 false/*ZExt*/, "tmp", &CI);
6653
6654 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6655 Constant *One = ConstantInt::get(In->getType(), 1);
6656 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
6657 In->getName()+".not"),
6658 CI);
6659 }
6660
6661 return ReplaceInstUsesWith(CI, In);
6662 }
6663
6664
6665
Chris Lattner20f23722007-04-11 06:12:58 +00006666 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6667 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6668 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6669 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6670 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6671 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6672 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6673 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner7ddbff02007-04-11 05:45:39 +00006674 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6675 // This only works for EQ and NE
6676 ICI->isEquality()) {
6677 // If Op1C some other power of two, convert:
6678 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6679 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6680 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6681 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6682
6683 APInt KnownZeroMask(~KnownZero);
6684 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6685 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6686 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6687 // (X&4) == 2 --> false
6688 // (X&4) != 2 --> true
6689 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6690 Res = ConstantExpr::getZExt(Res, CI.getType());
6691 return ReplaceInstUsesWith(CI, Res);
6692 }
6693
6694 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6695 Value *In = ICI->getOperand(0);
6696 if (ShiftAmt) {
6697 // Perform a logical shr by shiftamt.
6698 // Insert the shift to put the result in the low bit.
6699 In = InsertNewInstBefore(
6700 BinaryOperator::createLShr(In,
6701 ConstantInt::get(In->getType(), ShiftAmt),
6702 In->getName()+".lobit"), CI);
6703 }
6704
6705 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6706 Constant *One = ConstantInt::get(In->getType(), 1);
6707 In = BinaryOperator::createXor(In, One, "tmp");
6708 InsertNewInstBefore(cast<Instruction>(In), CI);
6709 }
6710
6711 if (CI.getType() == In->getType())
6712 return ReplaceInstUsesWith(CI, In);
6713 else
6714 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6715 }
6716 }
6717 }
6718 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006719 return 0;
6720}
6721
Chris Lattner74ff60f2007-04-11 06:57:46 +00006722Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00006723 if (Instruction *I = commonIntCastTransforms(CI))
6724 return I;
6725
Chris Lattner74ff60f2007-04-11 06:57:46 +00006726 Value *Src = CI.getOperand(0);
6727
6728 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6729 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6730 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6731 // If we are just checking for a icmp eq of a single bit and zext'ing it
6732 // to an integer, then shift the bit to the appropriate place and then
6733 // cast to integer to avoid the comparison.
6734 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6735 const APInt &Op1CV = Op1C->getValue();
6736
6737 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6738 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6739 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6740 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6741 Value *In = ICI->getOperand(0);
6742 Value *Sh = ConstantInt::get(In->getType(),
6743 In->getType()->getPrimitiveSizeInBits()-1);
6744 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
6745 In->getName()+".lobit"),
6746 CI);
6747 if (In->getType() != CI.getType())
6748 In = CastInst::createIntegerCast(In, CI.getType(),
6749 true/*SExt*/, "tmp", &CI);
6750
6751 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6752 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6753 In->getName()+".not"), CI);
6754
6755 return ReplaceInstUsesWith(CI, In);
6756 }
6757 }
6758 }
6759
Chris Lattner20f23722007-04-11 06:12:58 +00006760 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006761}
6762
6763Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6764 return commonCastTransforms(CI);
6765}
6766
6767Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6768 return commonCastTransforms(CI);
6769}
6770
6771Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006772 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006773}
6774
6775Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006776 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006777}
6778
6779Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6780 return commonCastTransforms(CI);
6781}
6782
6783Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6784 return commonCastTransforms(CI);
6785}
6786
6787Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006788 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006789}
6790
6791Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6792 return commonCastTransforms(CI);
6793}
6794
6795Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6796
6797 // If the operands are integer typed then apply the integer transforms,
6798 // otherwise just apply the common ones.
6799 Value *Src = CI.getOperand(0);
6800 const Type *SrcTy = Src->getType();
6801 const Type *DestTy = CI.getType();
6802
Chris Lattner03c49532007-01-15 02:27:26 +00006803 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006804 if (Instruction *Result = commonIntCastTransforms(CI))
6805 return Result;
6806 } else {
6807 if (Instruction *Result = commonCastTransforms(CI))
6808 return Result;
6809 }
6810
6811
6812 // Get rid of casts from one type to the same type. These are useless and can
6813 // be replaced by the operand.
6814 if (DestTy == Src->getType())
6815 return ReplaceInstUsesWith(CI, Src);
6816
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006817 // If the source and destination are pointers, and this cast is equivalent to
6818 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6819 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006820 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6821 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6822 const Type *DstElTy = DstPTy->getElementType();
6823 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006824
Reid Spencerc635f472006-12-31 05:48:39 +00006825 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006826 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006827 while (SrcElTy != DstElTy &&
6828 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6829 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6830 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006831 ++NumZeros;
6832 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006833
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006834 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006835 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006836 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6837 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006838 }
6839 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006840 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006841
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006842 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6843 if (SVI->hasOneUse()) {
6844 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6845 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006846 if (isa<VectorType>(DestTy) &&
6847 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006848 SVI->getType()->getNumElements()) {
6849 CastInst *Tmp;
6850 // If either of the operands is a cast from CI.getType(), then
6851 // evaluating the shuffle in the casted destination's type will allow
6852 // us to eliminate at least one cast.
6853 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6854 Tmp->getOperand(0)->getType() == DestTy) ||
6855 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6856 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006857 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6858 SVI->getOperand(0), DestTy, &CI);
6859 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6860 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006861 // Return a new shuffle vector. Use the same element ID's, as we
6862 // know the vector types match #elts.
6863 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006864 }
6865 }
6866 }
6867 }
Chris Lattner260ab202002-04-18 17:39:14 +00006868 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006869}
6870
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006871/// GetSelectFoldableOperands - We want to turn code that looks like this:
6872/// %C = or %A, %B
6873/// %D = select %cond, %C, %A
6874/// into:
6875/// %C = select %cond, %B, 0
6876/// %D = or %A, %C
6877///
6878/// Assuming that the specified instruction is an operand to the select, return
6879/// a bitmask indicating which operands of this instruction are foldable if they
6880/// equal the other incoming value of the select.
6881///
6882static unsigned GetSelectFoldableOperands(Instruction *I) {
6883 switch (I->getOpcode()) {
6884 case Instruction::Add:
6885 case Instruction::Mul:
6886 case Instruction::And:
6887 case Instruction::Or:
6888 case Instruction::Xor:
6889 return 3; // Can fold through either operand.
6890 case Instruction::Sub: // Can only fold on the amount subtracted.
6891 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006892 case Instruction::LShr:
6893 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006894 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006895 default:
6896 return 0; // Cannot fold
6897 }
6898}
6899
6900/// GetSelectFoldableConstant - For the same transformation as the previous
6901/// function, return the identity constant that goes into the select.
6902static Constant *GetSelectFoldableConstant(Instruction *I) {
6903 switch (I->getOpcode()) {
6904 default: assert(0 && "This cannot happen!"); abort();
6905 case Instruction::Add:
6906 case Instruction::Sub:
6907 case Instruction::Or:
6908 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006909 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006910 case Instruction::LShr:
6911 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006912 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006913 case Instruction::And:
6914 return ConstantInt::getAllOnesValue(I->getType());
6915 case Instruction::Mul:
6916 return ConstantInt::get(I->getType(), 1);
6917 }
6918}
6919
Chris Lattner411336f2005-01-19 21:50:18 +00006920/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6921/// have the same opcode and only one use each. Try to simplify this.
6922Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6923 Instruction *FI) {
6924 if (TI->getNumOperands() == 1) {
6925 // If this is a non-volatile load or a cast from the same type,
6926 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006927 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006928 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6929 return 0;
6930 } else {
6931 return 0; // unknown unary op.
6932 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006933
Chris Lattner411336f2005-01-19 21:50:18 +00006934 // Fold this by inserting a select from the input values.
6935 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6936 FI->getOperand(0), SI.getName()+".v");
6937 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006938 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6939 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006940 }
6941
Reid Spencer2341c222007-02-02 02:16:23 +00006942 // Only handle binary operators here.
6943 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006944 return 0;
6945
6946 // Figure out if the operations have any operands in common.
6947 Value *MatchOp, *OtherOpT, *OtherOpF;
6948 bool MatchIsOpZero;
6949 if (TI->getOperand(0) == FI->getOperand(0)) {
6950 MatchOp = TI->getOperand(0);
6951 OtherOpT = TI->getOperand(1);
6952 OtherOpF = FI->getOperand(1);
6953 MatchIsOpZero = true;
6954 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6955 MatchOp = TI->getOperand(1);
6956 OtherOpT = TI->getOperand(0);
6957 OtherOpF = FI->getOperand(0);
6958 MatchIsOpZero = false;
6959 } else if (!TI->isCommutative()) {
6960 return 0;
6961 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6962 MatchOp = TI->getOperand(0);
6963 OtherOpT = TI->getOperand(1);
6964 OtherOpF = FI->getOperand(0);
6965 MatchIsOpZero = true;
6966 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6967 MatchOp = TI->getOperand(1);
6968 OtherOpT = TI->getOperand(0);
6969 OtherOpF = FI->getOperand(1);
6970 MatchIsOpZero = true;
6971 } else {
6972 return 0;
6973 }
6974
6975 // If we reach here, they do have operations in common.
6976 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6977 OtherOpF, SI.getName()+".v");
6978 InsertNewInstBefore(NewSI, SI);
6979
6980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6981 if (MatchIsOpZero)
6982 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6983 else
6984 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006985 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006986 assert(0 && "Shouldn't get here");
6987 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006988}
6989
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006990Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006991 Value *CondVal = SI.getCondition();
6992 Value *TrueVal = SI.getTrueValue();
6993 Value *FalseVal = SI.getFalseValue();
6994
6995 // select true, X, Y -> X
6996 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006997 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006998 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006999
7000 // select C, X, X -> X
7001 if (TrueVal == FalseVal)
7002 return ReplaceInstUsesWith(SI, TrueVal);
7003
Chris Lattner81a7a232004-10-16 18:11:37 +00007004 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7005 return ReplaceInstUsesWith(SI, FalseVal);
7006 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7007 return ReplaceInstUsesWith(SI, TrueVal);
7008 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7009 if (isa<Constant>(TrueVal))
7010 return ReplaceInstUsesWith(SI, TrueVal);
7011 else
7012 return ReplaceInstUsesWith(SI, FalseVal);
7013 }
7014
Reid Spencer542964f2007-01-11 18:21:29 +00007015 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007016 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007017 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007018 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007019 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007020 } else {
7021 // Change: A = select B, false, C --> A = and !B, C
7022 Value *NotCond =
7023 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7024 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007025 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007026 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007027 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007028 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007029 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007030 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007031 } else {
7032 // Change: A = select B, C, true --> A = or !B, C
7033 Value *NotCond =
7034 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7035 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007036 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007037 }
7038 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00007039 }
Chris Lattner1c631e82004-04-08 04:43:23 +00007040
Chris Lattner183b3362004-04-09 19:05:30 +00007041 // Selecting between two integer constants?
7042 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7043 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00007044 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00007045 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007046 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00007047 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00007048 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00007049 Value *NotCond =
7050 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00007051 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007052 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00007053 }
Chris Lattner20f23722007-04-11 06:12:58 +00007054
7055 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner35167c32004-06-09 07:59:58 +00007056
Reid Spencer266e42b2006-12-23 06:05:41 +00007057 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007058
Reid Spencer266e42b2006-12-23 06:05:41 +00007059 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00007060 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00007061 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00007062 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007063 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007064 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00007065 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00007066 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00007067 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7068 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7069 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00007070 InsertNewInstBefore(SRA, SI);
7071
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007072 // Finally, convert to the type of the select RHS. We figure out
7073 // if this requires a SExt, Trunc or BitCast based on the sizes.
7074 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng56cda952007-04-02 08:20:41 +00007075 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7076 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007077 if (SRASize < SISize)
7078 opc = Instruction::SExt;
7079 else if (SRASize > SISize)
7080 opc = Instruction::Trunc;
7081 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007082 }
7083 }
7084
7085
7086 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00007087 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007088 // non-constant value, eliminate this whole mess. This corresponds to
7089 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00007090 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007091 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007092 cast<Constant>(IC->getOperand(1))->isNullValue())
7093 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7094 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007095 isa<ConstantInt>(ICA->getOperand(1)) &&
7096 (ICA->getOperand(1) == TrueValC ||
7097 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007098 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7099 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007100 // know whether we have a icmp_ne or icmp_eq and whether the
7101 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00007102 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00007103 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007104 Value *V = ICA;
7105 if (ShouldNotVal)
7106 V = InsertNewInstBefore(BinaryOperator::create(
7107 Instruction::Xor, V, ICA->getOperand(1)), SI);
7108 return ReplaceInstUsesWith(SI, V);
7109 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007110 }
Chris Lattner533bc492004-03-30 19:37:13 +00007111 }
Chris Lattner623fba12004-04-10 22:21:27 +00007112
7113 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007114 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7115 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007116 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007117 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007118 return ReplaceInstUsesWith(SI, FalseVal);
7119 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007120 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007121 return ReplaceInstUsesWith(SI, TrueVal);
7122 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7123
Reid Spencer266e42b2006-12-23 06:05:41 +00007124 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007125 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007126 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007127 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007128 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007129 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7130 return ReplaceInstUsesWith(SI, TrueVal);
7131 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7132 }
7133 }
7134
7135 // See if we are selecting two values based on a comparison of the two values.
7136 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7137 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7138 // Transform (X == Y) ? X : Y -> Y
7139 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7140 return ReplaceInstUsesWith(SI, FalseVal);
7141 // Transform (X != Y) ? X : Y -> X
7142 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7143 return ReplaceInstUsesWith(SI, TrueVal);
7144 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7145
7146 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7147 // Transform (X == Y) ? Y : X -> X
7148 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7149 return ReplaceInstUsesWith(SI, FalseVal);
7150 // Transform (X != Y) ? Y : X -> Y
7151 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007152 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007153 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7154 }
7155 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007156
Chris Lattnera04c9042005-01-13 22:52:24 +00007157 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7158 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7159 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007160 Instruction *AddOp = 0, *SubOp = 0;
7161
Chris Lattner411336f2005-01-19 21:50:18 +00007162 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7163 if (TI->getOpcode() == FI->getOpcode())
7164 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7165 return IV;
7166
7167 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7168 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007169 if (TI->getOpcode() == Instruction::Sub &&
7170 FI->getOpcode() == Instruction::Add) {
7171 AddOp = FI; SubOp = TI;
7172 } else if (FI->getOpcode() == Instruction::Sub &&
7173 TI->getOpcode() == Instruction::Add) {
7174 AddOp = TI; SubOp = FI;
7175 }
7176
7177 if (AddOp) {
7178 Value *OtherAddOp = 0;
7179 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7180 OtherAddOp = AddOp->getOperand(1);
7181 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7182 OtherAddOp = AddOp->getOperand(0);
7183 }
7184
7185 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007186 // So at this point we know we have (Y -> OtherAddOp):
7187 // select C, (add X, Y), (sub X, Z)
7188 Value *NegVal; // Compute -Z
7189 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7190 NegVal = ConstantExpr::getNeg(C);
7191 } else {
7192 NegVal = InsertNewInstBefore(
7193 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007194 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007195
7196 Value *NewTrueOp = OtherAddOp;
7197 Value *NewFalseOp = NegVal;
7198 if (AddOp != TI)
7199 std::swap(NewTrueOp, NewFalseOp);
7200 Instruction *NewSel =
7201 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7202
7203 NewSel = InsertNewInstBefore(NewSel, SI);
7204 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007205 }
7206 }
7207 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007208
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007209 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007210 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007211 // See the comment above GetSelectFoldableOperands for a description of the
7212 // transformation we are doing here.
7213 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7214 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7215 !isa<Constant>(FalseVal))
7216 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7217 unsigned OpToFold = 0;
7218 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7219 OpToFold = 1;
7220 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7221 OpToFold = 2;
7222 }
7223
7224 if (OpToFold) {
7225 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007226 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007227 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007228 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007229 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7231 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007232 else {
7233 assert(0 && "Unknown instruction!!");
7234 }
7235 }
7236 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007237
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007238 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7239 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7240 !isa<Constant>(TrueVal))
7241 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7242 unsigned OpToFold = 0;
7243 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7244 OpToFold = 1;
7245 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7246 OpToFold = 2;
7247 }
7248
7249 if (OpToFold) {
7250 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007251 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007252 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007253 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007254 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007255 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7256 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007257 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007258 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007259 }
7260 }
7261 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007262
7263 if (BinaryOperator::isNot(CondVal)) {
7264 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7265 SI.setOperand(1, FalseVal);
7266 SI.setOperand(2, TrueVal);
7267 return &SI;
7268 }
7269
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007270 return 0;
7271}
7272
Chris Lattner82f2ef22006-03-06 20:18:44 +00007273/// GetKnownAlignment - If the specified pointer has an alignment that we can
7274/// determine, return it, otherwise return 0.
7275static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7276 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7277 unsigned Align = GV->getAlignment();
7278 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007279 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007280 return Align;
7281 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7282 unsigned Align = AI->getAlignment();
7283 if (Align == 0 && TD) {
7284 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007285 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007286 else if (isa<MallocInst>(AI)) {
7287 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007288 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007289 Align =
7290 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007291 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007292 Align =
7293 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007294 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007295 }
7296 }
7297 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007298 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007299 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007300 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007301 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007302 if (isa<PointerType>(CI->getOperand(0)->getType()))
7303 return GetKnownAlignment(CI->getOperand(0), TD);
7304 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007305 } else if (isa<GetElementPtrInst>(V) ||
7306 (isa<ConstantExpr>(V) &&
7307 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7308 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007309 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7310 if (BaseAlignment == 0) return 0;
7311
7312 // If all indexes are zero, it is just the alignment of the base pointer.
7313 bool AllZeroOperands = true;
7314 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7315 if (!isa<Constant>(GEPI->getOperand(i)) ||
7316 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7317 AllZeroOperands = false;
7318 break;
7319 }
7320 if (AllZeroOperands)
7321 return BaseAlignment;
7322
7323 // Otherwise, if the base alignment is >= the alignment we expect for the
7324 // base pointer type, then we know that the resultant pointer is aligned at
7325 // least as much as its type requires.
7326 if (!TD) return 0;
7327
7328 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007329 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007330 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007331 <= BaseAlignment) {
7332 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007333 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007334 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007335 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007336 return 0;
7337 }
7338 return 0;
7339}
7340
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007341
Chris Lattnerc66b2232006-01-13 20:11:04 +00007342/// visitCallInst - CallInst simplification. This mostly only handles folding
7343/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7344/// the heavy lifting.
7345///
Chris Lattner970c33a2003-06-19 17:00:31 +00007346Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007347 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7348 if (!II) return visitCallSite(&CI);
7349
Chris Lattner51ea1272004-02-28 05:22:00 +00007350 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7351 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007352 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007353 bool Changed = false;
7354
7355 // memmove/cpy/set of zero bytes is a noop.
7356 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7357 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7358
Chris Lattner00648e12004-10-12 04:52:52 +00007359 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007360 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007361 // Replace the instruction with just byte operations. We would
7362 // transform other cases to loads/stores, but we don't know if
7363 // alignment is sufficient.
7364 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007365 }
7366
Chris Lattner00648e12004-10-12 04:52:52 +00007367 // If we have a memmove and the source operation is a constant global,
7368 // then the source and dest pointers can't alias, so we can change this
7369 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007370 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007371 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7372 if (GVSrc->isConstant()) {
7373 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007374 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007375 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007376 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007377 Name = "llvm.memcpy.i32";
7378 else
7379 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007380 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007381 CI.getCalledFunction()->getFunctionType());
7382 CI.setOperand(0, MemCpy);
7383 Changed = true;
7384 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007385 }
Chris Lattner00648e12004-10-12 04:52:52 +00007386
Chris Lattner82f2ef22006-03-06 20:18:44 +00007387 // If we can determine a pointer alignment that is bigger than currently
7388 // set, update the alignment.
7389 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7390 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7391 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7392 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007393 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007394 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007395 Changed = true;
7396 }
7397 } else if (isa<MemSetInst>(MI)) {
7398 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007399 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007400 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007401 Changed = true;
7402 }
7403 }
7404
Chris Lattnerc66b2232006-01-13 20:11:04 +00007405 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007406 } else {
7407 switch (II->getIntrinsicID()) {
7408 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007409 case Intrinsic::ppc_altivec_lvx:
7410 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007411 case Intrinsic::x86_sse_loadu_ps:
7412 case Intrinsic::x86_sse2_loadu_pd:
7413 case Intrinsic::x86_sse2_loadu_dq:
7414 // Turn PPC lvx -> load if the pointer is known aligned.
7415 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007416 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007417 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007418 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007419 return new LoadInst(Ptr);
7420 }
7421 break;
7422 case Intrinsic::ppc_altivec_stvx:
7423 case Intrinsic::ppc_altivec_stvxl:
7424 // Turn stvx -> store if the pointer is known aligned.
7425 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007426 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007427 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7428 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007429 return new StoreInst(II->getOperand(1), Ptr);
7430 }
7431 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007432 case Intrinsic::x86_sse_storeu_ps:
7433 case Intrinsic::x86_sse2_storeu_pd:
7434 case Intrinsic::x86_sse2_storeu_dq:
7435 case Intrinsic::x86_sse2_storel_dq:
7436 // Turn X86 storeu -> store if the pointer is known aligned.
7437 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7438 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007439 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7440 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007441 return new StoreInst(II->getOperand(2), Ptr);
7442 }
7443 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007444
7445 case Intrinsic::x86_sse_cvttss2si: {
7446 // These intrinsics only demands the 0th element of its input vector. If
7447 // we can simplify the input based on that, do so now.
7448 uint64_t UndefElts;
7449 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7450 UndefElts)) {
7451 II->setOperand(1, V);
7452 return II;
7453 }
7454 break;
7455 }
7456
Chris Lattnere79d2492006-04-06 19:19:17 +00007457 case Intrinsic::ppc_altivec_vperm:
7458 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007459 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007460 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7461
7462 // Check that all of the elements are integer constants or undefs.
7463 bool AllEltsOk = true;
7464 for (unsigned i = 0; i != 16; ++i) {
7465 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7466 !isa<UndefValue>(Mask->getOperand(i))) {
7467 AllEltsOk = false;
7468 break;
7469 }
7470 }
7471
7472 if (AllEltsOk) {
7473 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007474 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7475 II->getOperand(1), Mask->getType(), CI);
7476 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7477 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007478 Value *Result = UndefValue::get(Op0->getType());
7479
7480 // Only extract each element once.
7481 Value *ExtractedElts[32];
7482 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7483
7484 for (unsigned i = 0; i != 16; ++i) {
7485 if (isa<UndefValue>(Mask->getOperand(i)))
7486 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007487 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007488 Idx &= 31; // Match the hardware behavior.
7489
7490 if (ExtractedElts[Idx] == 0) {
7491 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007492 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007493 InsertNewInstBefore(Elt, CI);
7494 ExtractedElts[Idx] = Elt;
7495 }
7496
7497 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007498 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007499 InsertNewInstBefore(cast<Instruction>(Result), CI);
7500 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007501 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007502 }
7503 }
7504 break;
7505
Chris Lattner503221f2006-01-13 21:28:09 +00007506 case Intrinsic::stackrestore: {
7507 // If the save is right next to the restore, remove the restore. This can
7508 // happen when variable allocas are DCE'd.
7509 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7510 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7511 BasicBlock::iterator BI = SS;
7512 if (&*++BI == II)
7513 return EraseInstFromFunction(CI);
7514 }
7515 }
7516
7517 // If the stack restore is in a return/unwind block and if there are no
7518 // allocas or calls between the restore and the return, nuke the restore.
7519 TerminatorInst *TI = II->getParent()->getTerminator();
7520 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7521 BasicBlock::iterator BI = II;
7522 bool CannotRemove = false;
7523 for (++BI; &*BI != TI; ++BI) {
7524 if (isa<AllocaInst>(BI) ||
7525 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7526 CannotRemove = true;
7527 break;
7528 }
7529 }
7530 if (!CannotRemove)
7531 return EraseInstFromFunction(CI);
7532 }
7533 break;
7534 }
7535 }
Chris Lattner00648e12004-10-12 04:52:52 +00007536 }
7537
Chris Lattnerc66b2232006-01-13 20:11:04 +00007538 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007539}
7540
7541// InvokeInst simplification
7542//
7543Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007544 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007545}
7546
Chris Lattneraec3d942003-10-07 22:32:43 +00007547// visitCallSite - Improvements for call and invoke instructions.
7548//
7549Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007550 bool Changed = false;
7551
7552 // If the callee is a constexpr cast of a function, attempt to move the cast
7553 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007554 if (transformConstExprCastCall(CS)) return 0;
7555
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007556 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007557
Chris Lattner61d9d812005-05-13 07:09:09 +00007558 if (Function *CalleeF = dyn_cast<Function>(Callee))
7559 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7560 Instruction *OldCall = CS.getInstruction();
7561 // If the call and callee calling conventions don't match, this call must
7562 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007563 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007564 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007565 if (!OldCall->use_empty())
7566 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7567 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7568 return EraseInstFromFunction(*OldCall);
7569 return 0;
7570 }
7571
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007572 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7573 // This instruction is not reachable, just remove it. We insert a store to
7574 // undef so that we know that this code is not reachable, despite the fact
7575 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007576 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007577 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007578 CS.getInstruction());
7579
7580 if (!CS.getInstruction()->use_empty())
7581 CS.getInstruction()->
7582 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7583
7584 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7585 // Don't break the CFG, insert a dummy cond branch.
7586 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007587 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007588 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007589 return EraseInstFromFunction(*CS.getInstruction());
7590 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007591
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007592 const PointerType *PTy = cast<PointerType>(Callee->getType());
7593 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7594 if (FTy->isVarArg()) {
7595 // See if we can optimize any arguments passed through the varargs area of
7596 // the call.
7597 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7598 E = CS.arg_end(); I != E; ++I)
7599 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7600 // If this cast does not effect the value passed through the varargs
7601 // area, we can eliminate the use of the cast.
7602 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007603 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007604 *I = Op;
7605 Changed = true;
7606 }
7607 }
7608 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007609
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007610 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007611}
7612
Chris Lattner970c33a2003-06-19 17:00:31 +00007613// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7614// attempt to move the cast to the arguments of the call/invoke.
7615//
7616bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7617 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7618 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007619 if (CE->getOpcode() != Instruction::BitCast ||
7620 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007621 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007622 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007623 Instruction *Caller = CS.getInstruction();
7624
7625 // Okay, this is a cast from a function to a different type. Unless doing so
7626 // would cause a type conversion of one of our arguments, change this call to
7627 // be a direct call with arguments casted to the appropriate types.
7628 //
7629 const FunctionType *FT = Callee->getFunctionType();
7630 const Type *OldRetTy = Caller->getType();
7631
Chris Lattner1f7942f2004-01-14 06:06:08 +00007632 // Check to see if we are changing the return type...
7633 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007634 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007635 // Conversion is ok if changing from pointer to int of same size.
7636 !(isa<PointerType>(FT->getReturnType()) &&
7637 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007638 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007639
7640 // If the callsite is an invoke instruction, and the return value is used by
7641 // a PHI node in a successor, we cannot change the return type of the call
7642 // because there is no place to put the cast instruction (without breaking
7643 // the critical edge). Bail out in this case.
7644 if (!Caller->use_empty())
7645 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7646 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7647 UI != E; ++UI)
7648 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7649 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007650 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007651 return false;
7652 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007653
7654 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7655 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007656
Chris Lattner970c33a2003-06-19 17:00:31 +00007657 CallSite::arg_iterator AI = CS.arg_begin();
7658 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7659 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007660 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007661 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Dale Johannesen7c2001d2007-04-04 19:16:42 +00007662 //Some conversions are safe even if we do not have a body.
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007663 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007664 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007665 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007666 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007667 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7668 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007669 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007670 if (Callee->isDeclaration() && !isConvertible) return false;
Dale Johannesen7c2001d2007-04-04 19:16:42 +00007671
7672 // Most other conversions can be done if we have a body, even if these
7673 // lose information, e.g. int->short.
7674 // Some conversions cannot be done at all, e.g. float to pointer.
7675 // Logic here parallels CastInst::getCastOpcode (the design there
7676 // requires legality checks like this be done before calling it).
7677 if (ParamTy->isInteger()) {
7678 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7679 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7680 return false;
7681 }
7682 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7683 !isa<PointerType>(ActTy))
7684 return false;
7685 } else if (ParamTy->isFloatingPoint()) {
7686 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7687 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7688 return false;
7689 }
7690 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7691 return false;
7692 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7693 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7694 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7695 return false;
7696 }
7697 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7698 return false;
7699 } else if (isa<PointerType>(ParamTy)) {
7700 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7701 return false;
7702 } else {
7703 return false;
7704 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007705 }
7706
7707 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007708 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007709 return false; // Do not delete arguments unless we have a function body...
7710
7711 // Okay, we decided that this is a safe thing to do: go ahead and start
7712 // inserting cast instructions as necessary...
7713 std::vector<Value*> Args;
7714 Args.reserve(NumActualArgs);
7715
7716 AI = CS.arg_begin();
7717 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7718 const Type *ParamTy = FT->getParamType(i);
7719 if ((*AI)->getType() == ParamTy) {
7720 Args.push_back(*AI);
7721 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007722 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007723 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007724 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007725 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007726 }
7727 }
7728
7729 // If the function takes more arguments than the call was taking, add them
7730 // now...
7731 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7732 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7733
7734 // If we are removing arguments to the function, emit an obnoxious warning...
7735 if (FT->getNumParams() < NumActualArgs)
7736 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007737 cerr << "WARNING: While resolving call to function '"
7738 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007739 } else {
7740 // Add all of the arguments in their promoted form to the arg list...
7741 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7742 const Type *PTy = getPromotedType((*AI)->getType());
7743 if (PTy != (*AI)->getType()) {
7744 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007745 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7746 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007747 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007748 InsertNewInstBefore(Cast, *Caller);
7749 Args.push_back(Cast);
7750 } else {
7751 Args.push_back(*AI);
7752 }
7753 }
7754 }
7755
7756 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007757 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007758
7759 Instruction *NC;
7760 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007761 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007762 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007763 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007764 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007765 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007766 if (cast<CallInst>(Caller)->isTailCall())
7767 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007768 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007769 }
7770
Chris Lattner6e0123b2007-02-11 01:23:03 +00007771 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007772 Value *NV = NC;
7773 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7774 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007775 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007776 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7777 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007778 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007779
7780 // If this is an invoke instruction, we should insert it after the first
7781 // non-phi, instruction in the normal successor block.
7782 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7783 BasicBlock::iterator I = II->getNormalDest()->begin();
7784 while (isa<PHINode>(I)) ++I;
7785 InsertNewInstBefore(NC, *I);
7786 } else {
7787 // Otherwise, it's a call, just insert cast right after the call instr
7788 InsertNewInstBefore(NC, *Caller);
7789 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007790 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007791 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007792 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007793 }
7794 }
7795
7796 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7797 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007798 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007799 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007800 return true;
7801}
7802
Chris Lattnercadac0c2006-11-01 04:51:18 +00007803/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7804/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7805/// and a single binop.
7806Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7807 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007808 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7809 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007810 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007811 Value *LHSVal = FirstInst->getOperand(0);
7812 Value *RHSVal = FirstInst->getOperand(1);
7813
7814 const Type *LHSType = LHSVal->getType();
7815 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007816
7817 // Scan to see if all operands are the same opcode, all have one use, and all
7818 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007819 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007820 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007821 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007822 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007823 // types or GEP's with different index types.
7824 I->getOperand(0)->getType() != LHSType ||
7825 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007826 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007827
7828 // If they are CmpInst instructions, check their predicates
7829 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7830 if (cast<CmpInst>(I)->getPredicate() !=
7831 cast<CmpInst>(FirstInst)->getPredicate())
7832 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007833
7834 // Keep track of which operand needs a phi node.
7835 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7836 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007837 }
7838
Chris Lattner4f218d52006-11-08 19:42:28 +00007839 // Otherwise, this is safe to transform, determine if it is profitable.
7840
7841 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7842 // Indexes are often folded into load/store instructions, so we don't want to
7843 // hide them behind a phi.
7844 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7845 return 0;
7846
Chris Lattnercadac0c2006-11-01 04:51:18 +00007847 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007848 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007849 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007850 if (LHSVal == 0) {
7851 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7852 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7853 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007854 InsertNewInstBefore(NewLHS, PN);
7855 LHSVal = NewLHS;
7856 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007857
7858 if (RHSVal == 0) {
7859 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7860 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7861 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007862 InsertNewInstBefore(NewRHS, PN);
7863 RHSVal = NewRHS;
7864 }
7865
Chris Lattnercd62f112006-11-08 19:29:23 +00007866 // Add all operands to the new PHIs.
7867 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7868 if (NewLHS) {
7869 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7870 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7871 }
7872 if (NewRHS) {
7873 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7874 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7875 }
7876 }
7877
Chris Lattnercadac0c2006-11-01 04:51:18 +00007878 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007879 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007880 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7881 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7882 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007883 else {
7884 assert(isa<GetElementPtrInst>(FirstInst));
7885 return new GetElementPtrInst(LHSVal, RHSVal);
7886 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007887}
7888
Chris Lattner14f82c72006-11-01 07:13:54 +00007889/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7890/// of the block that defines it. This means that it must be obvious the value
7891/// of the load is not changed from the point of the load to the end of the
7892/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007893///
7894/// Finally, it is safe, but not profitable, to sink a load targetting a
7895/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7896/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007897static bool isSafeToSinkLoad(LoadInst *L) {
7898 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7899
7900 for (++BBI; BBI != E; ++BBI)
7901 if (BBI->mayWriteToMemory())
7902 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007903
7904 // Check for non-address taken alloca. If not address-taken already, it isn't
7905 // profitable to do this xform.
7906 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7907 bool isAddressTaken = false;
7908 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7909 UI != E; ++UI) {
7910 if (isa<LoadInst>(UI)) continue;
7911 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7912 // If storing TO the alloca, then the address isn't taken.
7913 if (SI->getOperand(1) == AI) continue;
7914 }
7915 isAddressTaken = true;
7916 break;
7917 }
7918
7919 if (!isAddressTaken)
7920 return false;
7921 }
7922
Chris Lattner14f82c72006-11-01 07:13:54 +00007923 return true;
7924}
7925
Chris Lattner970c33a2003-06-19 17:00:31 +00007926
Chris Lattner7515cab2004-11-14 19:13:23 +00007927// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7928// operator and they all are only used by the PHI, PHI together their
7929// inputs, and do the operation once, to the result of the PHI.
7930Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7931 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7932
7933 // Scan the instruction, looking for input operations that can be folded away.
7934 // If all input operands to the phi are the same instruction (e.g. a cast from
7935 // the same type or "+42") we can pull the operation through the PHI, reducing
7936 // code size and simplifying code.
7937 Constant *ConstantOp = 0;
7938 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007939 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007940 if (isa<CastInst>(FirstInst)) {
7941 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007942 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007943 // Can fold binop, compare or shift here if the RHS is a constant,
7944 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007945 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007946 if (ConstantOp == 0)
7947 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007948 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7949 isVolatile = LI->isVolatile();
7950 // We can't sink the load if the loaded value could be modified between the
7951 // load and the PHI.
7952 if (LI->getParent() != PN.getIncomingBlock(0) ||
7953 !isSafeToSinkLoad(LI))
7954 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007955 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007956 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007957 return FoldPHIArgBinOpIntoPHI(PN);
7958 // Can't handle general GEPs yet.
7959 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007960 } else {
7961 return 0; // Cannot fold this operation.
7962 }
7963
7964 // Check to see if all arguments are the same operation.
7965 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7966 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7967 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007968 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007969 return 0;
7970 if (CastSrcTy) {
7971 if (I->getOperand(0)->getType() != CastSrcTy)
7972 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007973 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007974 // We can't sink the load if the loaded value could be modified between
7975 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007976 if (LI->isVolatile() != isVolatile ||
7977 LI->getParent() != PN.getIncomingBlock(i) ||
7978 !isSafeToSinkLoad(LI))
7979 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007980 } else if (I->getOperand(1) != ConstantOp) {
7981 return 0;
7982 }
7983 }
7984
7985 // Okay, they are all the same operation. Create a new PHI node of the
7986 // correct type, and PHI together all of the LHS's of the instructions.
7987 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7988 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007989 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007990
7991 Value *InVal = FirstInst->getOperand(0);
7992 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007993
7994 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007995 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7996 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7997 if (NewInVal != InVal)
7998 InVal = 0;
7999 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8000 }
8001
8002 Value *PhiVal;
8003 if (InVal) {
8004 // The new PHI unions all of the same values together. This is really
8005 // common, so we handle it intelligently here for compile-time speed.
8006 PhiVal = InVal;
8007 delete NewPN;
8008 } else {
8009 InsertNewInstBefore(NewPN, PN);
8010 PhiVal = NewPN;
8011 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008012
Chris Lattner7515cab2004-11-14 19:13:23 +00008013 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008014 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8015 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00008016 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00008017 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00008018 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00008019 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00008020 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8021 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8022 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00008023 else
Reid Spencer2341c222007-02-02 02:16:23 +00008024 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00008025 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008026}
Chris Lattner48a44f72002-05-02 17:06:02 +00008027
Chris Lattner71536432005-01-17 05:10:15 +00008028/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8029/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00008030static bool DeadPHICycle(PHINode *PN,
8031 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00008032 if (PN->use_empty()) return true;
8033 if (!PN->hasOneUse()) return false;
8034
8035 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00008036 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00008037 return true;
8038
8039 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8040 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008041
Chris Lattner71536432005-01-17 05:10:15 +00008042 return false;
8043}
8044
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008045// PHINode simplification
8046//
Chris Lattner113f4f42002-06-25 16:13:24 +00008047Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00008048 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00008049 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00008050
Owen Andersonae8aa642006-07-10 22:03:18 +00008051 if (Value *V = PN.hasConstantValue())
8052 return ReplaceInstUsesWith(PN, V);
8053
Owen Andersonae8aa642006-07-10 22:03:18 +00008054 // If all PHI operands are the same operation, pull them through the PHI,
8055 // reducing code size.
8056 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8057 PN.getIncomingValue(0)->hasOneUse())
8058 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8059 return Result;
8060
8061 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8062 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8063 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008064 if (PN.hasOneUse()) {
8065 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8066 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00008067 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00008068 PotentiallyDeadPHIs.insert(&PN);
8069 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8070 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8071 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008072
8073 // If this phi has a single use, and if that use just computes a value for
8074 // the next iteration of a loop, delete the phi. This occurs with unused
8075 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8076 // common case here is good because the only other things that catch this
8077 // are induction variable analysis (sometimes) and ADCE, which is only run
8078 // late.
8079 if (PHIUser->hasOneUse() &&
8080 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8081 PHIUser->use_back() == &PN) {
8082 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8083 }
8084 }
Owen Andersonae8aa642006-07-10 22:03:18 +00008085
Chris Lattner91daeb52003-12-19 05:58:40 +00008086 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008087}
8088
Reid Spencer13bc5d72006-12-12 09:18:51 +00008089static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8090 Instruction *InsertPoint,
8091 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00008092 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8093 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008094 // We must cast correctly to the pointer type. Ensure that we
8095 // sign extend the integer value if it is smaller as this is
8096 // used for address computation.
8097 Instruction::CastOps opcode =
8098 (VTySize < PtrSize ? Instruction::SExt :
8099 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8100 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00008101}
8102
Chris Lattner48a44f72002-05-02 17:06:02 +00008103
Chris Lattner113f4f42002-06-25 16:13:24 +00008104Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008105 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00008106 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00008107 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008108 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00008109 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008110
Chris Lattner81a7a232004-10-16 18:11:37 +00008111 if (isa<UndefValue>(GEP.getOperand(0)))
8112 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8113
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008114 bool HasZeroPointerIndex = false;
8115 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8116 HasZeroPointerIndex = C->isNullValue();
8117
8118 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008119 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008120
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008121 // Keep track of whether all indices are zero constants integers.
8122 bool AllZeroIndices = true;
8123
Chris Lattner69193f92004-04-05 01:30:19 +00008124 // Eliminate unneeded casts for indices.
8125 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008126
Chris Lattner2b2412d2004-04-07 18:38:20 +00008127 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008128 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8129 // Track whether this GEP has all zero indices, if so, it doesn't move the
8130 // input pointer, it just changes its type.
8131 if (AllZeroIndices) {
8132 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
8133 AllZeroIndices = CI->isNullValue();
8134 else
8135 AllZeroIndices = false;
8136 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008137 if (isa<SequentialType>(*GTI)) {
8138 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008139 if (CI->getOpcode() == Instruction::ZExt ||
8140 CI->getOpcode() == Instruction::SExt) {
8141 const Type *SrcTy = CI->getOperand(0)->getType();
8142 // We can eliminate a cast from i32 to i64 iff the target
8143 // is a 32-bit pointer target.
8144 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8145 MadeChange = true;
8146 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008147 }
8148 }
8149 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008150 // If we are using a wider index than needed for this platform, shrink it
8151 // to what we need. If the incoming value needs a cast instruction,
8152 // insert it. This explicit cast can make subsequent optimizations more
8153 // obvious.
8154 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008155 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008156 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008157 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008158 MadeChange = true;
8159 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008160 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8161 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008162 GEP.setOperand(i, Op);
8163 MadeChange = true;
8164 }
Chris Lattner69193f92004-04-05 01:30:19 +00008165 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008166 }
Chris Lattner69193f92004-04-05 01:30:19 +00008167 if (MadeChange) return &GEP;
8168
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008169 // If this GEP instruction doesn't move the pointer, and if the input operand
8170 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8171 // real input to the dest type.
8172 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
8173 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8174 GEP.getType());
8175
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008176 // Combine Indices - If the source pointer to this getelementptr instruction
8177 // is a getelementptr instruction, combine the indices of the two
8178 // getelementptr instructions into a single instruction.
8179 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008180 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008181 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008182 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008183
8184 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008185 // Note that if our source is a gep chain itself that we wait for that
8186 // chain to be resolved before we perform this transformation. This
8187 // avoids us creating a TON of code in some cases.
8188 //
8189 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8190 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8191 return 0; // Wait until our source is folded to completion.
8192
Chris Lattneraf6094f2007-02-15 22:48:32 +00008193 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008194
8195 // Find out whether the last index in the source GEP is a sequential idx.
8196 bool EndsWithSequential = false;
8197 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8198 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008199 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008200
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008201 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008202 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008203 // Replace: gep (gep %P, long B), long A, ...
8204 // With: T = long A+B; gep %P, T, ...
8205 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008206 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008207 if (SO1 == Constant::getNullValue(SO1->getType())) {
8208 Sum = GO1;
8209 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8210 Sum = SO1;
8211 } else {
8212 // If they aren't the same type, convert both to an integer of the
8213 // target's pointer size.
8214 if (SO1->getType() != GO1->getType()) {
8215 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008216 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008217 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008218 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008219 } else {
8220 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008221 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008222 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008223 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008224
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008225 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008226 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008227 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008228 } else {
8229 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008230 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8231 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008232 }
8233 }
8234 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008235 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8236 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8237 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008238 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8239 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008240 }
Chris Lattner69193f92004-04-05 01:30:19 +00008241 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008242
8243 // Recycle the GEP we already have if possible.
8244 if (SrcGEPOperands.size() == 2) {
8245 GEP.setOperand(0, SrcGEPOperands[0]);
8246 GEP.setOperand(1, Sum);
8247 return &GEP;
8248 } else {
8249 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8250 SrcGEPOperands.end()-1);
8251 Indices.push_back(Sum);
8252 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008254 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008255 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008256 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008257 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008258 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8259 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008260 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8261 }
8262
8263 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008264 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8265 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008266
Chris Lattner5f667a62004-05-07 22:09:22 +00008267 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008268 // GEP of global variable. If all of the indices for this GEP are
8269 // constants, we can promote this to a constexpr instead of an instruction.
8270
8271 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008272 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008273 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8274 for (; I != E && isa<Constant>(*I); ++I)
8275 Indices.push_back(cast<Constant>(*I));
8276
8277 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008278 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8279 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008280
8281 // Replace all uses of the GEP with the new constexpr...
8282 return ReplaceInstUsesWith(GEP, CE);
8283 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008284 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008285 if (!isa<PointerType>(X->getType())) {
8286 // Not interesting. Source pointer must be a cast from pointer.
8287 } else if (HasZeroPointerIndex) {
8288 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8289 // into : GEP [10 x ubyte]* X, long 0, ...
8290 //
8291 // This occurs when the program declares an array extern like "int X[];"
8292 //
8293 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8294 const PointerType *XTy = cast<PointerType>(X->getType());
8295 if (const ArrayType *XATy =
8296 dyn_cast<ArrayType>(XTy->getElementType()))
8297 if (const ArrayType *CATy =
8298 dyn_cast<ArrayType>(CPTy->getElementType()))
8299 if (CATy->getElementType() == XATy->getElementType()) {
8300 // At this point, we know that the cast source type is a pointer
8301 // to an array of the same type as the destination pointer
8302 // array. Because the array type is never stepped over (there
8303 // is a leading zero) we can fold the cast into this GEP.
8304 GEP.setOperand(0, X);
8305 return &GEP;
8306 }
8307 } else if (GEP.getNumOperands() == 2) {
8308 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008309 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8310 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008311 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8312 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8313 if (isa<ArrayType>(SrcElTy) &&
8314 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8315 TD->getTypeSize(ResElTy)) {
8316 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008317 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008318 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008319 // V and GEP are both pointer types --> BitCast
8320 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008321 }
Chris Lattner2a893292005-09-13 18:36:04 +00008322
8323 // Transform things like:
8324 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8325 // (where tmp = 8*tmp2) into:
8326 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8327
8328 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008329 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008330 uint64_t ArrayEltSize =
8331 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8332
8333 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8334 // allow either a mul, shift, or constant here.
8335 Value *NewIdx = 0;
8336 ConstantInt *Scale = 0;
8337 if (ArrayEltSize == 1) {
8338 NewIdx = GEP.getOperand(1);
8339 Scale = ConstantInt::get(NewIdx->getType(), 1);
8340 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008341 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008342 Scale = CI;
8343 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8344 if (Inst->getOpcode() == Instruction::Shl &&
8345 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00008346 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8347 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8348 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +00008349 NewIdx = Inst->getOperand(0);
8350 } else if (Inst->getOpcode() == Instruction::Mul &&
8351 isa<ConstantInt>(Inst->getOperand(1))) {
8352 Scale = cast<ConstantInt>(Inst->getOperand(1));
8353 NewIdx = Inst->getOperand(0);
8354 }
8355 }
8356
8357 // If the index will be to exactly the right offset with the scale taken
8358 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008359 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008360 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008361 Scale = ConstantInt::get(Scale->getType(),
8362 Scale->getZExtValue() / ArrayEltSize);
8363 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008364 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8365 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008366 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8367 NewIdx = InsertNewInstBefore(Sc, GEP);
8368 }
8369
8370 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008371 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008372 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008373 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008374 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8375 // The NewGEP must be pointer typed, so must the old one -> BitCast
8376 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008377 }
8378 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008379 }
Chris Lattnerca081252001-12-14 16:52:21 +00008380 }
8381
Chris Lattnerca081252001-12-14 16:52:21 +00008382 return 0;
8383}
8384
Chris Lattner1085bdf2002-11-04 16:18:53 +00008385Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8386 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8387 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008388 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8389 const Type *NewTy =
8390 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008391 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008392
8393 // Create and insert the replacement instruction...
8394 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008395 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008396 else {
8397 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008398 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008399 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008400
8401 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008402
Chris Lattner1085bdf2002-11-04 16:18:53 +00008403 // Scan to the end of the allocation instructions, to skip over a block of
8404 // allocas if possible...
8405 //
8406 BasicBlock::iterator It = New;
8407 while (isa<AllocationInst>(*It)) ++It;
8408
8409 // Now that I is pointing to the first non-allocation-inst in the block,
8410 // insert our getelementptr instruction...
8411 //
Reid Spencerc635f472006-12-31 05:48:39 +00008412 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008413 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8414 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008415
8416 // Now make everything use the getelementptr instead of the original
8417 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008418 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008419 } else if (isa<UndefValue>(AI.getArraySize())) {
8420 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008421 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008422
8423 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8424 // Note that we only do this for alloca's, because malloc should allocate and
8425 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008426 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008427 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008428 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8429
Chris Lattner1085bdf2002-11-04 16:18:53 +00008430 return 0;
8431}
8432
Chris Lattner8427bff2003-12-07 01:24:23 +00008433Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8434 Value *Op = FI.getOperand(0);
8435
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008436 // free undef -> unreachable.
8437 if (isa<UndefValue>(Op)) {
8438 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008439 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008440 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008441 return EraseInstFromFunction(FI);
8442 }
Chris Lattnerefb33d22007-04-14 00:20:02 +00008443
Chris Lattnerf3a36602004-02-28 04:57:37 +00008444 // If we have 'free null' delete the instruction. This can happen in stl code
8445 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008446 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008447 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +00008448
8449 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8450 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8451 FI.setOperand(0, CI->getOperand(0));
8452 return &FI;
8453 }
8454
8455 // Change free (gep X, 0,0,0,0) into free(X)
8456 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8457 if (GEPI->hasAllZeroIndices()) {
8458 AddToWorkList(GEPI);
8459 FI.setOperand(0, GEPI->getOperand(0));
8460 return &FI;
8461 }
8462 }
8463
8464 // Change free(malloc) into nothing, if the malloc has a single use.
8465 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8466 if (MI->hasOneUse()) {
8467 EraseInstFromFunction(FI);
8468 return EraseInstFromFunction(*MI);
8469 }
Chris Lattnerf3a36602004-02-28 04:57:37 +00008470
Chris Lattner8427bff2003-12-07 01:24:23 +00008471 return 0;
8472}
8473
8474
Chris Lattner72684fe2005-01-31 05:51:45 +00008475/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008476static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8477 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008478 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008479
8480 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008481 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008482 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008483
Reid Spencer31a4ef42007-01-22 05:51:25 +00008484 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008485 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008486 // If the source is an array, the code below will not succeed. Check to
8487 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8488 // constants.
8489 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8490 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8491 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008492 Value *Idxs[2];
8493 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8494 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008495 SrcTy = cast<PointerType>(CastOp->getType());
8496 SrcPTy = SrcTy->getElementType();
8497 }
8498
Reid Spencer31a4ef42007-01-22 05:51:25 +00008499 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008500 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008501 // Do not allow turning this into a load of an integer, which is then
8502 // casted to a pointer, this pessimizes pointer analysis a lot.
8503 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008504 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8505 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008506
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008507 // Okay, we are casting from one integer or pointer type to another of
8508 // the same size. Instead of casting the pointer before the load, cast
8509 // the result of the loaded value.
8510 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8511 CI->getName(),
8512 LI.isVolatile()),LI);
8513 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008514 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008515 }
Chris Lattner35e24772004-07-13 01:49:43 +00008516 }
8517 }
8518 return 0;
8519}
8520
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008521/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008522/// from this value cannot trap. If it is not obviously safe to load from the
8523/// specified pointer, we do a quick local scan of the basic block containing
8524/// ScanFrom, to determine if the address is already accessed.
8525static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8526 // If it is an alloca or global variable, it is always safe to load from.
8527 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8528
8529 // Otherwise, be a little bit agressive by scanning the local block where we
8530 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008531 // from/to. If so, the previous load or store would have already trapped,
8532 // so there is no harm doing an extra load (also, CSE will later eliminate
8533 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008534 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8535
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008536 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008537 --BBI;
8538
8539 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8540 if (LI->getOperand(0) == V) return true;
8541 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8542 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008543
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008544 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008545 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008546}
8547
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008548Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8549 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008550
Chris Lattnera9d84e32005-05-01 04:24:53 +00008551 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008552 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008553 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8554 return Res;
8555
8556 // None of the following transforms are legal for volatile loads.
8557 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008558
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008559 if (&LI.getParent()->front() != &LI) {
8560 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008561 // If the instruction immediately before this is a store to the same
8562 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008563 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8564 if (SI->getOperand(1) == LI.getOperand(0))
8565 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008566 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8567 if (LIB->getOperand(0) == LI.getOperand(0))
8568 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008569 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008570
8571 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8572 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8573 isa<UndefValue>(GEPI->getOperand(0))) {
8574 // Insert a new store to null instruction before the load to indicate
8575 // that this code is not reachable. We do this instead of inserting
8576 // an unreachable instruction directly because we cannot modify the
8577 // CFG.
8578 new StoreInst(UndefValue::get(LI.getType()),
8579 Constant::getNullValue(Op->getType()), &LI);
8580 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8581 }
8582
Chris Lattner81a7a232004-10-16 18:11:37 +00008583 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008584 // load null/undef -> undef
8585 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008586 // Insert a new store to null instruction before the load to indicate that
8587 // this code is not reachable. We do this instead of inserting an
8588 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008589 new StoreInst(UndefValue::get(LI.getType()),
8590 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008591 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008592 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008593
Chris Lattner81a7a232004-10-16 18:11:37 +00008594 // Instcombine load (constant global) into the value loaded.
8595 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008596 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008597 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008598
Chris Lattner81a7a232004-10-16 18:11:37 +00008599 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8600 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8601 if (CE->getOpcode() == Instruction::GetElementPtr) {
8602 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008603 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008604 if (Constant *V =
8605 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008606 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008607 if (CE->getOperand(0)->isNullValue()) {
8608 // Insert a new store to null instruction before the load to indicate
8609 // that this code is not reachable. We do this instead of inserting
8610 // an unreachable instruction directly because we cannot modify the
8611 // CFG.
8612 new StoreInst(UndefValue::get(LI.getType()),
8613 Constant::getNullValue(Op->getType()), &LI);
8614 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8615 }
8616
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008617 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008618 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8619 return Res;
8620 }
8621 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008622
Chris Lattnera9d84e32005-05-01 04:24:53 +00008623 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008624 // Change select and PHI nodes to select values instead of addresses: this
8625 // helps alias analysis out a lot, allows many others simplifications, and
8626 // exposes redundancy in the code.
8627 //
8628 // Note that we cannot do the transformation unless we know that the
8629 // introduced loads cannot trap! Something like this is valid as long as
8630 // the condition is always false: load (select bool %C, int* null, int* %G),
8631 // but it would not be valid if we transformed it to load from null
8632 // unconditionally.
8633 //
8634 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8635 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008636 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8637 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008638 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008639 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008640 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008641 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008642 return new SelectInst(SI->getCondition(), V1, V2);
8643 }
8644
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008645 // load (select (cond, null, P)) -> load P
8646 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8647 if (C->isNullValue()) {
8648 LI.setOperand(0, SI->getOperand(2));
8649 return &LI;
8650 }
8651
8652 // load (select (cond, P, null)) -> load P
8653 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8654 if (C->isNullValue()) {
8655 LI.setOperand(0, SI->getOperand(1));
8656 return &LI;
8657 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008658 }
8659 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008660 return 0;
8661}
8662
Reid Spencere928a152007-01-19 21:20:31 +00008663/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008664/// when possible.
8665static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8666 User *CI = cast<User>(SI.getOperand(1));
8667 Value *CastOp = CI->getOperand(0);
8668
8669 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8670 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8671 const Type *SrcPTy = SrcTy->getElementType();
8672
Reid Spencer31a4ef42007-01-22 05:51:25 +00008673 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008674 // If the source is an array, the code below will not succeed. Check to
8675 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8676 // constants.
8677 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8678 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8679 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008680 Value* Idxs[2];
8681 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8682 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008683 SrcTy = cast<PointerType>(CastOp->getType());
8684 SrcPTy = SrcTy->getElementType();
8685 }
8686
Reid Spencer9a4bed02007-01-20 23:35:48 +00008687 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8688 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8689 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008690
8691 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008692 // the same size. Instead of casting the pointer before
8693 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008694 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008695 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008696 Instruction::CastOps opcode = Instruction::BitCast;
8697 const Type* CastSrcTy = SIOp0->getType();
8698 const Type* CastDstTy = SrcPTy;
8699 if (isa<PointerType>(CastDstTy)) {
8700 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008701 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008702 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008703 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008704 opcode = Instruction::PtrToInt;
8705 }
8706 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008707 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008708 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008709 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008710 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8711 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008712 return new StoreInst(NewCast, CastOp);
8713 }
8714 }
8715 }
8716 return 0;
8717}
8718
Chris Lattner31f486c2005-01-31 05:36:43 +00008719Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8720 Value *Val = SI.getOperand(0);
8721 Value *Ptr = SI.getOperand(1);
8722
8723 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008724 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008725 ++NumCombined;
8726 return 0;
8727 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008728
8729 // If the RHS is an alloca with a single use, zapify the store, making the
8730 // alloca dead.
8731 if (Ptr->hasOneUse()) {
8732 if (isa<AllocaInst>(Ptr)) {
8733 EraseInstFromFunction(SI);
8734 ++NumCombined;
8735 return 0;
8736 }
8737
8738 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8739 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8740 GEP->getOperand(0)->hasOneUse()) {
8741 EraseInstFromFunction(SI);
8742 ++NumCombined;
8743 return 0;
8744 }
8745 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008746
Chris Lattner5997cf92006-02-08 03:25:32 +00008747 // Do really simple DSE, to catch cases where there are several consequtive
8748 // stores to the same location, separated by a few arithmetic operations. This
8749 // situation often occurs with bitfield accesses.
8750 BasicBlock::iterator BBI = &SI;
8751 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8752 --ScanInsts) {
8753 --BBI;
8754
8755 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8756 // Prev store isn't volatile, and stores to the same location?
8757 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8758 ++NumDeadStore;
8759 ++BBI;
8760 EraseInstFromFunction(*PrevSI);
8761 continue;
8762 }
8763 break;
8764 }
8765
Chris Lattnerdab43b22006-05-26 19:19:20 +00008766 // If this is a load, we have to stop. However, if the loaded value is from
8767 // the pointer we're loading and is producing the pointer we're storing,
8768 // then *this* store is dead (X = load P; store X -> P).
8769 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8770 if (LI == Val && LI->getOperand(0) == Ptr) {
8771 EraseInstFromFunction(SI);
8772 ++NumCombined;
8773 return 0;
8774 }
8775 // Otherwise, this is a load from some other location. Stores before it
8776 // may not be dead.
8777 break;
8778 }
8779
Chris Lattner5997cf92006-02-08 03:25:32 +00008780 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008781 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008782 break;
8783 }
8784
8785
8786 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008787
8788 // store X, null -> turns into 'unreachable' in SimplifyCFG
8789 if (isa<ConstantPointerNull>(Ptr)) {
8790 if (!isa<UndefValue>(Val)) {
8791 SI.setOperand(0, UndefValue::get(Val->getType()));
8792 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008793 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008794 ++NumCombined;
8795 }
8796 return 0; // Do not modify these!
8797 }
8798
8799 // store undef, Ptr -> noop
8800 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008801 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008802 ++NumCombined;
8803 return 0;
8804 }
8805
Chris Lattner72684fe2005-01-31 05:51:45 +00008806 // If the pointer destination is a cast, see if we can fold the cast into the
8807 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008808 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008809 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8810 return Res;
8811 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008812 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008813 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8814 return Res;
8815
Chris Lattner219175c2005-09-12 23:23:25 +00008816
8817 // If this store is the last instruction in the basic block, and if the block
8818 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008819 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008820 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8821 if (BI->isUnconditional()) {
8822 // Check to see if the successor block has exactly two incoming edges. If
8823 // so, see if the other predecessor contains a store to the same location.
8824 // if so, insert a PHI node (if needed) and move the stores down.
8825 BasicBlock *Dest = BI->getSuccessor(0);
8826
8827 pred_iterator PI = pred_begin(Dest);
8828 BasicBlock *Other = 0;
8829 if (*PI != BI->getParent())
8830 Other = *PI;
8831 ++PI;
8832 if (PI != pred_end(Dest)) {
8833 if (*PI != BI->getParent())
8834 if (Other)
8835 Other = 0;
8836 else
8837 Other = *PI;
8838 if (++PI != pred_end(Dest))
8839 Other = 0;
8840 }
8841 if (Other) { // If only one other pred...
8842 BBI = Other->getTerminator();
8843 // Make sure this other block ends in an unconditional branch and that
8844 // there is an instruction before the branch.
8845 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8846 BBI != Other->begin()) {
8847 --BBI;
8848 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8849
8850 // If this instruction is a store to the same location.
8851 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8852 // Okay, we know we can perform this transformation. Insert a PHI
8853 // node now if we need it.
8854 Value *MergedVal = OtherStore->getOperand(0);
8855 if (MergedVal != SI.getOperand(0)) {
8856 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8857 PN->reserveOperandSpace(2);
8858 PN->addIncoming(SI.getOperand(0), SI.getParent());
8859 PN->addIncoming(OtherStore->getOperand(0), Other);
8860 MergedVal = InsertNewInstBefore(PN, Dest->front());
8861 }
8862
8863 // Advance to a place where it is safe to insert the new store and
8864 // insert it.
8865 BBI = Dest->begin();
8866 while (isa<PHINode>(BBI)) ++BBI;
8867 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8868 OtherStore->isVolatile()), *BBI);
8869
8870 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008871 EraseInstFromFunction(SI);
8872 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008873 ++NumCombined;
8874 return 0;
8875 }
8876 }
8877 }
8878 }
8879
Chris Lattner31f486c2005-01-31 05:36:43 +00008880 return 0;
8881}
8882
8883
Chris Lattner9eef8a72003-06-04 04:46:00 +00008884Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8885 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008886 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008887 BasicBlock *TrueDest;
8888 BasicBlock *FalseDest;
8889 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8890 !isa<Constant>(X)) {
8891 // Swap Destinations and condition...
8892 BI.setCondition(X);
8893 BI.setSuccessor(0, FalseDest);
8894 BI.setSuccessor(1, TrueDest);
8895 return &BI;
8896 }
8897
Reid Spencer266e42b2006-12-23 06:05:41 +00008898 // Cannonicalize fcmp_one -> fcmp_oeq
8899 FCmpInst::Predicate FPred; Value *Y;
8900 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8901 TrueDest, FalseDest)))
8902 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8903 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8904 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008905 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008906 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8907 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008908 // Swap Destinations and condition...
8909 BI.setCondition(NewSCC);
8910 BI.setSuccessor(0, FalseDest);
8911 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008912 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008913 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008914 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008915 return &BI;
8916 }
8917
8918 // Cannonicalize icmp_ne -> icmp_eq
8919 ICmpInst::Predicate IPred;
8920 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8921 TrueDest, FalseDest)))
8922 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8923 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8924 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8925 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008926 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008927 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8928 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008929 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008930 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008931 BI.setSuccessor(0, FalseDest);
8932 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008933 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008934 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008935 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008936 return &BI;
8937 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008938
Chris Lattner9eef8a72003-06-04 04:46:00 +00008939 return 0;
8940}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008941
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008942Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8943 Value *Cond = SI.getCondition();
8944 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8945 if (I->getOpcode() == Instruction::Add)
8946 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8947 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8948 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008949 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008950 AddRHS));
8951 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008952 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008953 return &SI;
8954 }
8955 }
8956 return 0;
8957}
8958
Chris Lattner6bc98652006-03-05 00:22:33 +00008959/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8960/// is to leave as a vector operation.
8961static bool CheapToScalarize(Value *V, bool isConstant) {
8962 if (isa<ConstantAggregateZero>(V))
8963 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008964 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008965 if (isConstant) return true;
8966 // If all elts are the same, we can extract.
8967 Constant *Op0 = C->getOperand(0);
8968 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8969 if (C->getOperand(i) != Op0)
8970 return false;
8971 return true;
8972 }
8973 Instruction *I = dyn_cast<Instruction>(V);
8974 if (!I) return false;
8975
8976 // Insert element gets simplified to the inserted element or is deleted if
8977 // this is constant idx extract element and its a constant idx insertelt.
8978 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8979 isa<ConstantInt>(I->getOperand(2)))
8980 return true;
8981 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8982 return true;
8983 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8984 if (BO->hasOneUse() &&
8985 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8986 CheapToScalarize(BO->getOperand(1), isConstant)))
8987 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008988 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8989 if (CI->hasOneUse() &&
8990 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8991 CheapToScalarize(CI->getOperand(1), isConstant)))
8992 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008993
8994 return false;
8995}
8996
Chris Lattner945e4372007-02-14 05:52:17 +00008997/// Read and decode a shufflevector mask.
8998///
8999/// It turns undef elements into values that are larger than the number of
9000/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00009001static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9002 unsigned NElts = SVI->getType()->getNumElements();
9003 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9004 return std::vector<unsigned>(NElts, 0);
9005 if (isa<UndefValue>(SVI->getOperand(2)))
9006 return std::vector<unsigned>(NElts, 2*NElts);
9007
9008 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009009 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00009010 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9011 if (isa<UndefValue>(CP->getOperand(i)))
9012 Result.push_back(NElts*2); // undef -> 8
9013 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00009014 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00009015 return Result;
9016}
9017
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009018/// FindScalarElement - Given a vector and an element number, see if the scalar
9019/// value is already around as a register, for example if it were inserted then
9020/// extracted from the vector.
9021static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009022 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9023 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00009024 unsigned Width = PTy->getNumElements();
9025 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009026 return UndefValue::get(PTy->getElementType());
9027
9028 if (isa<UndefValue>(V))
9029 return UndefValue::get(PTy->getElementType());
9030 else if (isa<ConstantAggregateZero>(V))
9031 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00009032 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009033 return CP->getOperand(EltNo);
9034 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9035 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009036 if (!isa<ConstantInt>(III->getOperand(2)))
9037 return 0;
9038 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009039
9040 // If this is an insert to the element we are looking for, return the
9041 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009042 if (EltNo == IIElt)
9043 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009044
9045 // Otherwise, the insertelement doesn't modify the value, recurse on its
9046 // vector input.
9047 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00009048 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00009049 unsigned InEl = getShuffleMask(SVI)[EltNo];
9050 if (InEl < Width)
9051 return FindScalarElement(SVI->getOperand(0), InEl);
9052 else if (InEl < Width*2)
9053 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9054 else
9055 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009056 }
9057
9058 // Otherwise, we don't know.
9059 return 0;
9060}
9061
Robert Bocchinoa8352962006-01-13 22:48:06 +00009062Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009063
Chris Lattner92346c32006-03-31 18:25:14 +00009064 // If packed val is undef, replace extract with scalar undef.
9065 if (isa<UndefValue>(EI.getOperand(0)))
9066 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9067
9068 // If packed val is constant 0, replace extract with scalar 0.
9069 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9070 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9071
Reid Spencerd84d35b2007-02-15 02:26:10 +00009072 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009073 // If packed val is constant with uniform operands, replace EI
9074 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00009075 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009076 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00009077 if (C->getOperand(i) != op0) {
9078 op0 = 0;
9079 break;
9080 }
9081 if (op0)
9082 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009083 }
Chris Lattner6bc98652006-03-05 00:22:33 +00009084
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009085 // If extracting a specified index from the vector, see if we can recursively
9086 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009087 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +00009088 unsigned IndexVal = IdxC->getZExtValue();
9089 unsigned VectorWidth =
9090 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9091
9092 // If this is extracting an invalid index, turn this into undef, to avoid
9093 // crashing the code below.
9094 if (IndexVal >= VectorWidth)
9095 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9096
Chris Lattner2deeaea2006-10-05 06:55:50 +00009097 // This instruction only demands the single element from the input vector.
9098 // If the input vector has a single use, simplify it based on this use
9099 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +00009100 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00009101 uint64_t UndefElts;
9102 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00009103 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00009104 UndefElts)) {
9105 EI.setOperand(0, V);
9106 return &EI;
9107 }
9108 }
9109
Reid Spencere0fc4df2006-10-20 07:07:24 +00009110 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009111 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +00009112
9113 // If the this extractelement is directly using a bitcast from a vector of
9114 // the same number of elements, see if we can find the source element from
9115 // it. In this case, we will end up needing to bitcast the scalars.
9116 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9117 if (const VectorType *VT =
9118 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9119 if (VT->getNumElements() == VectorWidth)
9120 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9121 return new BitCastInst(Elt, EI.getType());
9122 }
Chris Lattner2d37f922006-04-10 23:06:36 +00009123 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009124
Chris Lattner83f65782006-05-25 22:53:38 +00009125 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009126 if (I->hasOneUse()) {
9127 // Push extractelement into predecessor operation if legal and
9128 // profitable to do so
9129 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009130 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9131 if (CheapToScalarize(BO, isConstantElt)) {
9132 ExtractElementInst *newEI0 =
9133 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9134 EI.getName()+".lhs");
9135 ExtractElementInst *newEI1 =
9136 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9137 EI.getName()+".rhs");
9138 InsertNewInstBefore(newEI0, EI);
9139 InsertNewInstBefore(newEI1, EI);
9140 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9141 }
Reid Spencerde46e482006-11-02 20:25:50 +00009142 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009143 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00009144 PointerType::get(EI.getType()), EI);
9145 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00009146 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00009147 InsertNewInstBefore(GEP, EI);
9148 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00009149 }
9150 }
9151 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9152 // Extracting the inserted element?
9153 if (IE->getOperand(2) == EI.getOperand(1))
9154 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9155 // If the inserted and extracted elements are constants, they must not
9156 // be the same value, extract from the pre-inserted value instead.
9157 if (isa<Constant>(IE->getOperand(2)) &&
9158 isa<Constant>(EI.getOperand(1))) {
9159 AddUsesToWorkList(EI);
9160 EI.setOperand(0, IE->getOperand(0));
9161 return &EI;
9162 }
9163 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9164 // If this is extracting an element from a shufflevector, figure out where
9165 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009166 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9167 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00009168 Value *Src;
9169 if (SrcIdx < SVI->getType()->getNumElements())
9170 Src = SVI->getOperand(0);
9171 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9172 SrcIdx -= SVI->getType()->getNumElements();
9173 Src = SVI->getOperand(1);
9174 } else {
9175 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009176 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009177 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009178 }
9179 }
Chris Lattner83f65782006-05-25 22:53:38 +00009180 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009181 return 0;
9182}
9183
Chris Lattner90951862006-04-16 00:51:47 +00009184/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9185/// elements from either LHS or RHS, return the shuffle mask and true.
9186/// Otherwise, return false.
9187static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9188 std::vector<Constant*> &Mask) {
9189 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9190 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009191 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009192
9193 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009194 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009195 return true;
9196 } else if (V == LHS) {
9197 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009198 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009199 return true;
9200 } else if (V == RHS) {
9201 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009202 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009203 return true;
9204 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9205 // If this is an insert of an extract from some other vector, include it.
9206 Value *VecOp = IEI->getOperand(0);
9207 Value *ScalarOp = IEI->getOperand(1);
9208 Value *IdxOp = IEI->getOperand(2);
9209
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009210 if (!isa<ConstantInt>(IdxOp))
9211 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009212 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009213
9214 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9215 // Okay, we can handle this if the vector we are insertinting into is
9216 // transitively ok.
9217 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9218 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009219 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009220 return true;
9221 }
9222 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9223 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009224 EI->getOperand(0)->getType() == V->getType()) {
9225 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009226 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009227
9228 // This must be extracting from either LHS or RHS.
9229 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9230 // Okay, we can handle this if the vector we are insertinting into is
9231 // transitively ok.
9232 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9233 // If so, update the mask to reflect the inserted value.
9234 if (EI->getOperand(0) == LHS) {
9235 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009236 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009237 } else {
9238 assert(EI->getOperand(0) == RHS);
9239 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009240 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009241
9242 }
9243 return true;
9244 }
9245 }
9246 }
9247 }
9248 }
9249 // TODO: Handle shufflevector here!
9250
9251 return false;
9252}
9253
9254/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9255/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9256/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009257static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009258 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009259 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009260 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009261 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009262 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009263
9264 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009265 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009266 return V;
9267 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009268 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009269 return V;
9270 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9271 // If this is an insert of an extract from some other vector, include it.
9272 Value *VecOp = IEI->getOperand(0);
9273 Value *ScalarOp = IEI->getOperand(1);
9274 Value *IdxOp = IEI->getOperand(2);
9275
9276 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9277 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9278 EI->getOperand(0)->getType() == V->getType()) {
9279 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009280 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9281 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009282
9283 // Either the extracted from or inserted into vector must be RHSVec,
9284 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009285 if (EI->getOperand(0) == RHS || RHS == 0) {
9286 RHS = EI->getOperand(0);
9287 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009288 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009289 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009290 return V;
9291 }
9292
Chris Lattner90951862006-04-16 00:51:47 +00009293 if (VecOp == RHS) {
9294 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009295 // Everything but the extracted element is replaced with the RHS.
9296 for (unsigned i = 0; i != NumElts; ++i) {
9297 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009298 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009299 }
9300 return V;
9301 }
Chris Lattner90951862006-04-16 00:51:47 +00009302
9303 // If this insertelement is a chain that comes from exactly these two
9304 // vectors, return the vector and the effective shuffle.
9305 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9306 return EI->getOperand(0);
9307
Chris Lattner39fac442006-04-15 01:39:45 +00009308 }
9309 }
9310 }
Chris Lattner90951862006-04-16 00:51:47 +00009311 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009312
9313 // Otherwise, can't do anything fancy. Return an identity vector.
9314 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009315 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009316 return V;
9317}
9318
9319Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9320 Value *VecOp = IE.getOperand(0);
9321 Value *ScalarOp = IE.getOperand(1);
9322 Value *IdxOp = IE.getOperand(2);
9323
Chris Lattner4ca9cbb2007-04-09 01:11:16 +00009324 // Inserting an undef or into an undefined place, remove this.
9325 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9326 ReplaceInstUsesWith(IE, VecOp);
9327
Chris Lattner39fac442006-04-15 01:39:45 +00009328 // If the inserted element was extracted from some other vector, and if the
9329 // indexes are constant, try to turn this into a shufflevector operation.
9330 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9331 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9332 EI->getOperand(0)->getType() == IE.getType()) {
9333 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009334 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9335 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009336
9337 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9338 return ReplaceInstUsesWith(IE, VecOp);
9339
9340 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9341 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9342
9343 // If we are extracting a value from a vector, then inserting it right
9344 // back into the same place, just use the input vector.
9345 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9346 return ReplaceInstUsesWith(IE, VecOp);
9347
9348 // We could theoretically do this for ANY input. However, doing so could
9349 // turn chains of insertelement instructions into a chain of shufflevector
9350 // instructions, and right now we do not merge shufflevectors. As such,
9351 // only do this in a situation where it is clear that there is benefit.
9352 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9353 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9354 // the values of VecOp, except then one read from EIOp0.
9355 // Build a new shuffle mask.
9356 std::vector<Constant*> Mask;
9357 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009358 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009359 else {
9360 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009361 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009362 NumVectorElts));
9363 }
Reid Spencerc635f472006-12-31 05:48:39 +00009364 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009365 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009366 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009367 }
9368
9369 // If this insertelement isn't used by some other insertelement, turn it
9370 // (and any insertelements it points to), into one big shuffle.
9371 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9372 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009373 Value *RHS = 0;
9374 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9375 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9376 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009377 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009378 }
9379 }
9380 }
9381
9382 return 0;
9383}
9384
9385
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009386Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9387 Value *LHS = SVI.getOperand(0);
9388 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009389 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009390
9391 bool MadeChange = false;
9392
Chris Lattner2deeaea2006-10-05 06:55:50 +00009393 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009394 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009395 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9396
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009397 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009398 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009399 if (isa<UndefValue>(SVI.getOperand(1))) {
9400 // Scan to see if there are any references to the RHS. If so, replace them
9401 // with undef element refs and set MadeChange to true.
9402 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9403 if (Mask[i] >= e && Mask[i] != 2*e) {
9404 Mask[i] = 2*e;
9405 MadeChange = true;
9406 }
9407 }
9408
9409 if (MadeChange) {
9410 // Remap any references to RHS to use LHS.
9411 std::vector<Constant*> Elts;
9412 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9413 if (Mask[i] == 2*e)
9414 Elts.push_back(UndefValue::get(Type::Int32Ty));
9415 else
9416 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9417 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009418 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009419 }
9420 }
Chris Lattner39fac442006-04-15 01:39:45 +00009421
Chris Lattner12249be2006-05-25 23:48:38 +00009422 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9423 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9424 if (LHS == RHS || isa<UndefValue>(LHS)) {
9425 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009426 // shuffle(undef,undef,mask) -> undef.
9427 return ReplaceInstUsesWith(SVI, LHS);
9428 }
9429
Chris Lattner12249be2006-05-25 23:48:38 +00009430 // Remap any references to RHS to use LHS.
9431 std::vector<Constant*> Elts;
9432 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009433 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009434 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009435 else {
9436 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9437 (Mask[i] < e && isa<UndefValue>(LHS)))
9438 Mask[i] = 2*e; // Turn into undef.
9439 else
9440 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009441 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009442 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009443 }
Chris Lattner12249be2006-05-25 23:48:38 +00009444 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009445 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009446 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009447 LHS = SVI.getOperand(0);
9448 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009449 MadeChange = true;
9450 }
9451
Chris Lattner0e477162006-05-26 00:29:06 +00009452 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009453 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009454
Chris Lattner12249be2006-05-25 23:48:38 +00009455 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9456 if (Mask[i] >= e*2) continue; // Ignore undef values.
9457 // Is this an identity shuffle of the LHS value?
9458 isLHSID &= (Mask[i] == i);
9459
9460 // Is this an identity shuffle of the RHS value?
9461 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009462 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009463
Chris Lattner12249be2006-05-25 23:48:38 +00009464 // Eliminate identity shuffles.
9465 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9466 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009467
Chris Lattner0e477162006-05-26 00:29:06 +00009468 // If the LHS is a shufflevector itself, see if we can combine it with this
9469 // one without producing an unusual shuffle. Here we are really conservative:
9470 // we are absolutely afraid of producing a shuffle mask not in the input
9471 // program, because the code gen may not be smart enough to turn a merged
9472 // shuffle into two specific shuffles: it may produce worse code. As such,
9473 // we only merge two shuffles if the result is one of the two input shuffle
9474 // masks. In this case, merging the shuffles just removes one instruction,
9475 // which we know is safe. This is good for things like turning:
9476 // (splat(splat)) -> splat.
9477 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9478 if (isa<UndefValue>(RHS)) {
9479 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9480
9481 std::vector<unsigned> NewMask;
9482 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9483 if (Mask[i] >= 2*e)
9484 NewMask.push_back(2*e);
9485 else
9486 NewMask.push_back(LHSMask[Mask[i]]);
9487
9488 // If the result mask is equal to the src shuffle or this shuffle mask, do
9489 // the replacement.
9490 if (NewMask == LHSMask || NewMask == Mask) {
9491 std::vector<Constant*> Elts;
9492 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9493 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009494 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009495 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009496 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009497 }
9498 }
9499 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9500 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009501 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009502 }
9503 }
9504 }
Chris Lattner4284f642007-01-30 22:32:46 +00009505
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009506 return MadeChange ? &SVI : 0;
9507}
9508
9509
Robert Bocchinoa8352962006-01-13 22:48:06 +00009510
Chris Lattner39c98bb2004-12-08 23:43:58 +00009511
9512/// TryToSinkInstruction - Try to move the specified instruction from its
9513/// current block into the beginning of DestBlock, which can only happen if it's
9514/// safe to move the instruction past all of the instructions between it and the
9515/// end of its block.
9516static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9517 assert(I->hasOneUse() && "Invariants didn't hold!");
9518
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009519 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9520 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009521
Chris Lattner39c98bb2004-12-08 23:43:58 +00009522 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009523 if (isa<AllocaInst>(I) && I->getParent() ==
9524 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009525 return false;
9526
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009527 // We can only sink load instructions if there is nothing between the load and
9528 // the end of block that could change the value.
9529 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009530 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9531 Scan != E; ++Scan)
9532 if (Scan->mayWriteToMemory())
9533 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009534 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009535
9536 BasicBlock::iterator InsertPos = DestBlock->begin();
9537 while (isa<PHINode>(InsertPos)) ++InsertPos;
9538
Chris Lattner9f269e42005-08-08 19:11:57 +00009539 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009540 ++NumSunkInst;
9541 return true;
9542}
9543
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009544
9545/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9546/// all reachable code to the worklist.
9547///
9548/// This has a couple of tricks to make the code faster and more powerful. In
9549/// particular, we constant fold and DCE instructions as we go, to avoid adding
9550/// them to the worklist (this significantly speeds up instcombine on code where
9551/// many instructions are dead or constant). Additionally, if we find a branch
9552/// whose condition is a known constant, we only visit the reachable successors.
9553///
9554static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009555 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009556 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009557 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009558 std::vector<BasicBlock*> Worklist;
9559 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009560
Chris Lattner12b89cc2007-03-23 19:17:18 +00009561 while (!Worklist.empty()) {
9562 BB = Worklist.back();
9563 Worklist.pop_back();
9564
9565 // We have now visited this block! If we've already been here, ignore it.
9566 if (!Visited.insert(BB)) continue;
9567
9568 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9569 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009570
Chris Lattner12b89cc2007-03-23 19:17:18 +00009571 // DCE instruction if trivially dead.
9572 if (isInstructionTriviallyDead(Inst)) {
9573 ++NumDeadInst;
9574 DOUT << "IC: DCE: " << *Inst;
9575 Inst->eraseFromParent();
9576 continue;
9577 }
9578
9579 // ConstantProp instruction if trivially constant.
9580 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9581 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9582 Inst->replaceAllUsesWith(C);
9583 ++NumConstProp;
9584 Inst->eraseFromParent();
9585 continue;
9586 }
9587
9588 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009589 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009590
9591 // Recursively visit successors. If this is a branch or switch on a
9592 // constant, only visit the reachable successor.
9593 TerminatorInst *TI = BB->getTerminator();
9594 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9595 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9596 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9597 Worklist.push_back(BI->getSuccessor(!CondVal));
9598 continue;
9599 }
9600 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9601 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9602 // See if this is an explicit destination.
9603 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9604 if (SI->getCaseValue(i) == Cond) {
9605 Worklist.push_back(SI->getSuccessor(i));
9606 continue;
9607 }
9608
9609 // Otherwise it is the default destination.
9610 Worklist.push_back(SI->getSuccessor(0));
9611 continue;
9612 }
9613 }
9614
9615 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9616 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009617 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009618}
9619
Chris Lattner960a5432007-03-03 02:04:50 +00009620bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009621 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009622 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009623
9624 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9625 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009626
Chris Lattner4ed40f72005-07-07 20:40:38 +00009627 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009628 // Do a depth-first traversal of the function, populate the worklist with
9629 // the reachable instructions. Ignore blocks that are not reachable. Keep
9630 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009631 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009632 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009633
Chris Lattner4ed40f72005-07-07 20:40:38 +00009634 // Do a quick scan over the function. If we find any blocks that are
9635 // unreachable, remove any instructions inside of them. This prevents
9636 // the instcombine code from having to deal with some bad special cases.
9637 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9638 if (!Visited.count(BB)) {
9639 Instruction *Term = BB->getTerminator();
9640 while (Term != BB->begin()) { // Remove instrs bottom-up
9641 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009642
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009643 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009644 ++NumDeadInst;
9645
9646 if (!I->use_empty())
9647 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9648 I->eraseFromParent();
9649 }
9650 }
9651 }
Chris Lattnerca081252001-12-14 16:52:21 +00009652
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009653 while (!Worklist.empty()) {
9654 Instruction *I = RemoveOneFromWorkList();
9655 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009656
Chris Lattner1443bc52006-05-11 17:11:52 +00009657 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009658 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009659 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009660 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009661 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009662 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009663
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009664 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009665
9666 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009667 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009668 continue;
9669 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009670
Chris Lattner1443bc52006-05-11 17:11:52 +00009671 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009672 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009673 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009674
Chris Lattner1443bc52006-05-11 17:11:52 +00009675 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009676 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009677 ReplaceInstUsesWith(*I, C);
9678
Chris Lattner99f48c62002-09-02 04:59:56 +00009679 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009680 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009681 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009682 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009683 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009684
Chris Lattner39c98bb2004-12-08 23:43:58 +00009685 // See if we can trivially sink this instruction to a successor basic block.
9686 if (I->hasOneUse()) {
9687 BasicBlock *BB = I->getParent();
9688 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9689 if (UserParent != BB) {
9690 bool UserIsSuccessor = false;
9691 // See if the user is one of our successors.
9692 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9693 if (*SI == UserParent) {
9694 UserIsSuccessor = true;
9695 break;
9696 }
9697
9698 // If the user is one of our immediate successors, and if that successor
9699 // only has us as a predecessors (we'd have to split the critical edge
9700 // otherwise), we can keep going.
9701 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9702 next(pred_begin(UserParent)) == pred_end(UserParent))
9703 // Okay, the CFG is simple enough, try to sink this instruction.
9704 Changed |= TryToSinkInstruction(I, UserParent);
9705 }
9706 }
9707
Chris Lattnerca081252001-12-14 16:52:21 +00009708 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009709#ifndef NDEBUG
9710 std::string OrigI;
9711#endif
9712 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009713 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009714 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009715 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009716 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009717 DOUT << "IC: Old = " << *I
9718 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009719
Chris Lattner396dbfe2004-06-09 05:08:07 +00009720 // Everything uses the new instruction now.
9721 I->replaceAllUsesWith(Result);
9722
9723 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009724 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009725 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009726
Chris Lattner6e0123b2007-02-11 01:23:03 +00009727 // Move the name to the new instruction first.
9728 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009729
9730 // Insert the new instruction into the basic block...
9731 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009732 BasicBlock::iterator InsertPos = I;
9733
9734 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9735 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9736 ++InsertPos;
9737
9738 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009739
Chris Lattner63d75af2004-05-01 23:27:23 +00009740 // Make sure that we reprocess all operands now that we reduced their
9741 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009742 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009743
Chris Lattner396dbfe2004-06-09 05:08:07 +00009744 // Instructions can end up on the worklist more than once. Make sure
9745 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009746 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009747
9748 // Erase the old instruction.
9749 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009750 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009751#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009752 DOUT << "IC: Mod = " << OrigI
9753 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009754#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009755
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009756 // If the instruction was modified, it's possible that it is now dead.
9757 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009758 if (isInstructionTriviallyDead(I)) {
9759 // Make sure we process all operands now that we are reducing their
9760 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009761 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009762
Chris Lattner63d75af2004-05-01 23:27:23 +00009763 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009764 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009765 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009766 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009767 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009768 AddToWorkList(I);
9769 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009770 }
Chris Lattner053c0932002-05-14 15:24:07 +00009771 }
Chris Lattner260ab202002-04-18 17:39:14 +00009772 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009773 }
9774 }
9775
Chris Lattner960a5432007-03-03 02:04:50 +00009776 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009777 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009778}
9779
Chris Lattner960a5432007-03-03 02:04:50 +00009780
9781bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009782 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9783
Chris Lattner960a5432007-03-03 02:04:50 +00009784 bool EverMadeChange = false;
9785
9786 // Iterate while there is work to do.
9787 unsigned Iteration = 0;
9788 while (DoOneIteration(F, Iteration++))
9789 EverMadeChange = true;
9790 return EverMadeChange;
9791}
9792
Brian Gaeke38b79e82004-07-27 17:43:21 +00009793FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009794 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009795}
Brian Gaeke960707c2003-11-11 22:41:34 +00009796