blob: 038779da9e5c98e8475e77bc07f5e975db25f3ad [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 Lattnerd1f46d32005-04-24 06:59:08 +0000186
Reid Spencer266e42b2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224
Chris Lattner970c33a2003-06-19 17:00:31 +0000225 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner69193f92004-04-05 01:30:19 +0000229 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner623826c2004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000239 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 }
241
Chris Lattner7e794272004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000248
Chris Lattnere79d2492006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000251
Reid Spencer13bc5d72006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000274 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000275
Chris Lattner2590e512006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner51ea1272004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattner3ac7c262003-08-13 20:16:26 +0000305 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencer266e42b2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000317
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Reid Spencer959a21d2007-03-23 21:24:59 +0000322 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
323 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000324 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
325 APInt& KnownZero, APInt& KnownOne,
326 unsigned Depth = 0);
327
Chris Lattner2deeaea2006-10-05 06:55:50 +0000328 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
329 uint64_t &UndefElts, unsigned Depth = 0);
330
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000331 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
332 // PHI node as operand #0, see if we can fold the instruction into the PHI
333 // (which is only possible if all operands to the PHI are constants).
334 Instruction *FoldOpIntoPhi(Instruction &I);
335
Chris Lattner7515cab2004-11-14 19:13:23 +0000336 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
337 // operator and they all are only used by the PHI, PHI together their
338 // inputs, and do the operation once, to the result of the PHI.
339 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000340 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
341
342
Zhou Sheng75b871f2007-01-11 12:24:14 +0000343 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
344 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000345
Zhou Sheng75b871f2007-01-11 12:24:14 +0000346 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000347 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000348 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000349 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000350 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000351 Instruction *MatchBSwap(BinaryOperator &I);
352
Reid Spencer74a528b2006-12-13 18:21:21 +0000353 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000354 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000355
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000356 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000357}
358
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000360// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000361static unsigned getComplexity(Value *V) {
362 if (isa<Instruction>(V)) {
363 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000364 return 3;
365 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000366 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000367 if (isa<Argument>(V)) return 3;
368 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000369}
Chris Lattner260ab202002-04-18 17:39:14 +0000370
Chris Lattner7fb29e12003-03-11 00:12:48 +0000371// isOnlyUse - Return true if this instruction will be deleted if we stop using
372// it.
373static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000374 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375}
376
Chris Lattnere79e8542004-02-23 06:38:22 +0000377// getPromotedType - Return the specified type promoted as it would be to pass
378// though a va_arg area...
379static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000380 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
381 if (ITy->getBitWidth() < 32)
382 return Type::Int32Ty;
383 } else if (Ty == Type::FloatTy)
384 return Type::DoubleTy;
385 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000386}
387
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000388/// getBitCastOperand - If the specified operand is a CastInst or a constant
389/// expression bitcast, return the operand value, otherwise return null.
390static Value *getBitCastOperand(Value *V) {
391 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000392 return I->getOperand(0);
393 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000394 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000395 return CE->getOperand(0);
396 return 0;
397}
398
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399/// This function is a wrapper around CastInst::isEliminableCastPair. It
400/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000401static Instruction::CastOps
402isEliminableCastPair(
403 const CastInst *CI, ///< The first cast instruction
404 unsigned opcode, ///< The opcode of the second cast instruction
405 const Type *DstTy, ///< The target type for the second cast instruction
406 TargetData *TD ///< The target data for pointer size
407) {
408
409 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
410 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000411
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000412 // Get the opcodes of the two Cast instructions
413 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
414 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000415
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000416 return Instruction::CastOps(
417 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
418 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000419}
420
421/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
422/// in any code being generated. It does not require codegen if V is simple
423/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000424static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
425 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000426 if (V->getType() == Ty || isa<Constant>(V)) return false;
427
Chris Lattner99155be2006-05-25 23:24:33 +0000428 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000430 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 return false;
432 return true;
433}
434
435/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
436/// InsertBefore instruction. This is specialized a bit to avoid inserting
437/// casts that are known to not do anything...
438///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000439Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
440 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000441 Instruction *InsertBefore) {
442 if (V->getType() == DestTy) return V;
443 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445
Reid Spencer13bc5d72006-12-12 09:18:51 +0000446 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447}
448
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000449// SimplifyCommutative - This performs a few simplifications for commutative
450// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000451//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452// 1. Order operands such that they are listed from right (least complex) to
453// left (most complex). This puts constants before unary operators before
454// binary operators.
455//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000456// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
457// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000459bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 bool Changed = false;
461 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
462 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000463
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000464 if (!I.isAssociative()) return Changed;
465 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
467 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
468 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000469 Constant *Folded = ConstantExpr::get(I.getOpcode(),
470 cast<Constant>(I.getOperand(1)),
471 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000472 I.setOperand(0, Op->getOperand(0));
473 I.setOperand(1, Folded);
474 return true;
475 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
476 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
477 isOnlyUse(Op) && isOnlyUse(Op1)) {
478 Constant *C1 = cast<Constant>(Op->getOperand(1));
479 Constant *C2 = cast<Constant>(Op1->getOperand(1));
480
481 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000482 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
484 Op1->getOperand(0),
485 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000486 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487 I.setOperand(0, New);
488 I.setOperand(1, Folded);
489 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000490 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000491 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000492 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000493}
Chris Lattnerca081252001-12-14 16:52:21 +0000494
Reid Spencer266e42b2006-12-23 06:05:41 +0000495/// SimplifyCompare - For a CmpInst this function just orders the operands
496/// so that theyare listed from right (least complex) to left (most complex).
497/// This puts constants before unary operators before binary operators.
498bool InstCombiner::SimplifyCompare(CmpInst &I) {
499 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
500 return false;
501 I.swapOperands();
502 // Compare instructions are not associative so there's nothing else we can do.
503 return true;
504}
505
Chris Lattnerbb74e222003-03-10 23:06:50 +0000506// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
507// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000508//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509static inline Value *dyn_castNegVal(Value *V) {
510 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000511 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000512
Chris Lattner9ad0d552004-12-14 20:08:06 +0000513 // Constants can be considered to be negated values if they can be folded.
514 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
515 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517}
518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519static inline Value *dyn_castNotVal(Value *V) {
520 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000521 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522
523 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000524 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000525 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000526 return 0;
527}
528
Chris Lattner7fb29e12003-03-11 00:12:48 +0000529// dyn_castFoldableMul - If this value is a multiply that can be folded into
530// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000531// non-constant operand of the multiply, and set CST to point to the multiplier.
532// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000533//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000535 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000538 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000541 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000542 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000543 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
544 uint32_t CSTVal = CST->getValue().getActiveBits() > 64 ?
545 BitWidth : CST->getZExtValue();
546 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547 return I->getOperand(0);
548 }
549 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000550 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000551}
Chris Lattner31ae8632002-08-14 17:51:49 +0000552
Chris Lattner0798af32005-01-13 20:14:25 +0000553/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554/// expression, return it.
555static User *dyn_castGetElementPtr(Value *V) {
556 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558 if (CE->getOpcode() == Instruction::GetElementPtr)
559 return cast<User>(V);
560 return false;
561}
562
Reid Spencer80263aa2007-03-25 05:33:51 +0000563/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000564static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000565 APInt Val(C->getValue());
566 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000567}
Reid Spencer80263aa2007-03-25 05:33:51 +0000568/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000569static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000570 APInt Val(C->getValue());
571 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000572}
573/// Add - Add two ConstantInts together
574static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
575 return ConstantInt::get(C1->getValue() + C2->getValue());
576}
577/// And - Bitwise AND two ConstantInts together
578static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
579 return ConstantInt::get(C1->getValue() & C2->getValue());
580}
581/// Subtract - Subtract one ConstantInt from another
582static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
583 return ConstantInt::get(C1->getValue() - C2->getValue());
584}
585/// Multiply - Multiply two ConstantInts together
586static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
587 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000588}
589
Chris Lattner4534dd592006-02-09 07:38:58 +0000590/// ComputeMaskedBits - Determine which of the bits specified in Mask are
591/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000592/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
593/// processing.
594/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
595/// we cannot optimize based on the assumption that it is zero without changing
596/// it to be an explicit zero. If we don't change it to zero, other code could
597/// optimized based on the contradictory assumption that it is non-zero.
598/// Because instcombine aggressively folds operations with undef args anyway,
599/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000600static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000601 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000602 assert(V && "No Value?");
603 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000604 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000605 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000606 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000607 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000608 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000609 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
610 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000611 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000612 KnownZero = ~KnownOne & Mask;
613 return;
614 }
615
Reid Spenceraa696402007-03-08 01:46:38 +0000616 if (Depth == 6 || Mask == 0)
617 return; // Limit search depth.
618
619 Instruction *I = dyn_cast<Instruction>(V);
620 if (!I) return;
621
Zhou Shengaf4341d2007-03-13 02:23:10 +0000622 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000623 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000624
625 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000626 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000627 // If either the LHS or the RHS are Zero, the result is zero.
628 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000629 APInt Mask2(Mask & ~KnownZero);
630 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000631 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
632 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
633
634 // Output known-1 bits are only known if set in both the LHS & RHS.
635 KnownOne &= KnownOne2;
636 // Output known-0 are known to be clear if zero in either the LHS | RHS.
637 KnownZero |= KnownZero2;
638 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000639 }
640 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000641 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000642 APInt Mask2(Mask & ~KnownOne);
643 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000644 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
645 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
646
647 // Output known-0 bits are only known if clear in both the LHS & RHS.
648 KnownZero &= KnownZero2;
649 // Output known-1 are known to be set if set in either the LHS | RHS.
650 KnownOne |= KnownOne2;
651 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000652 }
Reid Spenceraa696402007-03-08 01:46:38 +0000653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
664 return;
665 }
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
675 return;
676 case Instruction::FPTrunc:
677 case Instruction::FPExt:
678 case Instruction::FPToUI:
679 case Instruction::FPToSI:
680 case Instruction::SIToFP:
681 case Instruction::PtrToInt:
682 case Instruction::UIToFP:
683 case Instruction::IntToPtr:
684 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000685 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000686 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000687 uint32_t SrcBitWidth =
688 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000689 APInt MaskIn(Mask);
690 MaskIn.zext(SrcBitWidth);
691 KnownZero.zext(SrcBitWidth);
692 KnownOne.zext(SrcBitWidth);
693 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000694 KnownZero.trunc(BitWidth);
695 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000696 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000697 }
Reid Spenceraa696402007-03-08 01:46:38 +0000698 case Instruction::BitCast: {
699 const Type *SrcTy = I->getOperand(0)->getType();
700 if (SrcTy->isInteger()) {
701 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
702 return;
703 }
704 break;
705 }
706 case Instruction::ZExt: {
707 // Compute the bits in the result that are not present in the input.
708 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000709 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000710
Zhou Sheng57e3f732007-03-28 02:19:03 +0000711 APInt MaskIn(Mask);
712 MaskIn.trunc(SrcBitWidth);
713 KnownZero.trunc(SrcBitWidth);
714 KnownOne.trunc(SrcBitWidth);
715 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000716 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
717 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000718 KnownZero.zext(BitWidth);
719 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000720 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000721 return;
722 }
723 case Instruction::SExt: {
724 // Compute the bits in the result that are not present in the input.
725 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000726 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000727
Zhou Sheng57e3f732007-03-28 02:19:03 +0000728 APInt MaskIn(Mask);
729 MaskIn.trunc(SrcBitWidth);
730 KnownZero.trunc(SrcBitWidth);
731 KnownOne.trunc(SrcBitWidth);
732 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000733 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000734 KnownZero.zext(BitWidth);
735 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000736
737 // If the sign bit of the input is known set or clear, then we know the
738 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000739 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000740 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000741 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000742 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000743 return;
744 }
745 case Instruction::Shl:
746 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
747 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
748 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencerd8aad612007-03-25 02:03:12 +0000749 APInt Mask2(Mask.lshr(ShiftAmt));
750 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000752 KnownZero <<= ShiftAmt;
753 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000754 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000755 return;
756 }
757 break;
758 case Instruction::LShr:
759 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
760 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
761 // Compute the new bits that are at the top now.
762 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spenceraa696402007-03-08 01:46:38 +0000763
764 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000765 APInt Mask2(Mask.shl(ShiftAmt));
766 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000767 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
768 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
769 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000770 // high bits known zero.
771 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000772 return;
773 }
774 break;
775 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000776 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000777 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
778 // Compute the new bits that are at the top now.
779 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spenceraa696402007-03-08 01:46:38 +0000780
781 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000782 APInt Mask2(Mask.shl(ShiftAmt));
783 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000784 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
785 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
786 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
787
Zhou Sheng57e3f732007-03-28 02:19:03 +0000788 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
789 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000790 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000791 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000792 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000793 return;
794 }
795 break;
796 }
797}
798
Reid Spencerbb5741f2007-03-08 01:52:58 +0000799/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
800/// this predicate to simplify operations downstream. Mask is known to be zero
801/// for bits that V cannot have.
802static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000803 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000804 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 return (KnownZero & Mask) == Mask;
807}
808
Chris Lattner0157e7f2006-02-11 09:31:47 +0000809/// ShrinkDemandedConstant - Check to see if the specified operand of the
810/// specified instruction is a constant integer. If so, check to see if there
811/// are any bits set in the constant that are not demanded. If so, shrink the
812/// constant and return true.
813static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000814 APInt Demanded) {
815 assert(I && "No instruction?");
816 assert(OpNo < I->getNumOperands() && "Operand index too large");
817
818 // If the operand is not a constant integer, nothing to do.
819 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
820 if (!OpC) return false;
821
822 // If there are no bits set that aren't demanded, nothing to do.
823 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
824 if ((~Demanded & OpC->getValue()) == 0)
825 return false;
826
827 // This instruction is producing bits that are not demanded. Shrink the RHS.
828 Demanded &= OpC->getValue();
829 I->setOperand(OpNo, ConstantInt::get(Demanded));
830 return true;
831}
832
Chris Lattneree0f2802006-02-12 02:07:56 +0000833// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
834// set of known zero and one bits, compute the maximum and minimum values that
835// could have the specified known zero and known one bits, returning them in
836// min/max.
837static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000838 const APInt& KnownZero,
839 const APInt& KnownOne,
840 APInt& Min, APInt& Max) {
841 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
842 assert(KnownZero.getBitWidth() == BitWidth &&
843 KnownOne.getBitWidth() == BitWidth &&
844 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
845 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000846 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000847
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000848 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +0000849
850 // 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
Chris Lattneree0f2802006-02-12 02:07:56 +0000856 Min |= SignBit;
857 Max &= ~SignBit;
858 }
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
1137 DemandedMask &= SrcTy->getMask().zext(BitWidth);
Zhou Sheng444af492007-03-29 04:45:55 +00001138 DemandedMask.trunc(SrcBitWidth);
1139 RHSKnownZero.trunc(SrcBitWidth);
1140 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001143 return true;
1144 DemandedMask.zext(BitWidth);
1145 RHSKnownZero.zext(BitWidth);
1146 RHSKnownOne.zext(BitWidth);
1147 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1148 "Bits known to be one AND zero?");
1149 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001150 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001151 break;
1152 }
1153 case Instruction::SExt: {
1154 // Compute the bits in the result that are not present in the input.
1155 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001156 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001157
1158 // Get the sign bit for the source type
Zhou Shenga4475572007-03-29 02:26:30 +00001159 APInt InSignBit(APInt::getSignBit(SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001160 InSignBit.zext(BitWidth);
1161 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001162 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001163
Zhou Shenga4475572007-03-29 02:26:30 +00001164 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001165 // If any of the sign extended bits are demanded, we know that the sign
1166 // bit is demanded.
1167 if ((NewBits & DemandedMask) != 0)
1168 InputDemandedBits |= InSignBit;
1169
Zhou Sheng444af492007-03-29 04:45:55 +00001170 InputDemandedBits.trunc(SrcBitWidth);
1171 RHSKnownZero.trunc(SrcBitWidth);
1172 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001173 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1174 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001175 return true;
1176 InputDemandedBits.zext(BitWidth);
1177 RHSKnownZero.zext(BitWidth);
1178 RHSKnownOne.zext(BitWidth);
1179 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1180 "Bits known to be one AND zero?");
1181
1182 // If the sign bit of the input is known set or clear, then we know the
1183 // top bits of the result.
1184
1185 // If the input sign bit is known zero, or if the NewBits are not demanded
1186 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001187 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001188 {
1189 // Convert to ZExt cast
1190 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1191 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001192 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001193 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001194 }
1195 break;
1196 }
1197 case Instruction::Add: {
1198 // Figure out what the input bits are. If the top bits of the and result
1199 // are not demanded, then the add doesn't demand them from its input
1200 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001201 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001202
1203 // If there is a constant on the RHS, there are a variety of xformations
1204 // we can do.
1205 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1206 // If null, this should be simplified elsewhere. Some of the xforms here
1207 // won't work if the RHS is zero.
1208 if (RHS->isZero())
1209 break;
1210
1211 // If the top bit of the output is demanded, demand everything from the
1212 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001213 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001214
1215 // Find information about known zero/one bits in the input.
1216 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1217 LHSKnownZero, LHSKnownOne, Depth+1))
1218 return true;
1219
1220 // If the RHS of the add has bits set that can't affect the input, reduce
1221 // the constant.
1222 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1223 return UpdateValueUsesWith(I, I);
1224
1225 // Avoid excess work.
1226 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1227 break;
1228
1229 // Turn it into OR if input bits are zero.
1230 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1231 Instruction *Or =
1232 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1233 I->getName());
1234 InsertNewInstBefore(Or, *I);
1235 return UpdateValueUsesWith(I, Or);
1236 }
1237
1238 // We can say something about the output known-zero and known-one bits,
1239 // depending on potential carries from the input constant and the
1240 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1241 // bits set and the RHS constant is 0x01001, then we know we have a known
1242 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1243
1244 // To compute this, we first compute the potential carry bits. These are
1245 // the bits which may be modified. I'm not aware of a better way to do
1246 // this scan.
1247 APInt RHSVal(RHS->getValue());
1248
1249 bool CarryIn = false;
1250 APInt CarryBits(BitWidth, 0);
1251 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1252 *RHSRawVal = RHSVal.getRawData();
1253 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1254 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1255 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1256 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1257 if (AddVal < RHSRawVal[i])
1258 CarryIn = true;
1259 else
1260 CarryIn = false;
1261 CarryBits.setWordToValue(i, WordCarryBits);
1262 }
1263
1264 // Now that we know which bits have carries, compute the known-1/0 sets.
1265
1266 // Bits are known one if they are known zero in one operand and one in the
1267 // other, and there is no input carry.
1268 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1269 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1270
1271 // Bits are known zero if they are known zero in both operands and there
1272 // is no input carry.
1273 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1274 } else {
1275 // If the high-bits of this ADD are not demanded, then it does not demand
1276 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001277 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001278 // Right fill the mask of bits for this ADD to demand the most
1279 // significant bit and all those below it.
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 }
1289 break;
1290 }
1291 case Instruction::Sub:
1292 // If the high-bits of this SUB are not demanded, then it does not demand
1293 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001294 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001295 // Right fill the mask of bits for this SUB to demand the most
1296 // significant bit and all those below it.
Reid Spencer52830322007-03-25 21:11:44 +00001297 unsigned NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001298 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001299 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1300 LHSKnownZero, LHSKnownOne, Depth+1))
1301 return true;
1302 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1303 LHSKnownZero, LHSKnownOne, Depth+1))
1304 return true;
1305 }
1306 break;
1307 case Instruction::Shl:
1308 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1309 uint64_t ShiftAmt = SA->getZExtValue();
Zhou Shenga4475572007-03-29 02:26:30 +00001310 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1311 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001312 RHSKnownZero, RHSKnownOne, Depth+1))
1313 return true;
1314 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1315 "Bits known to be one AND zero?");
1316 RHSKnownZero <<= ShiftAmt;
1317 RHSKnownOne <<= ShiftAmt;
1318 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001319 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001320 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001321 }
1322 break;
1323 case Instruction::LShr:
1324 // For a logical shift right
1325 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1326 unsigned ShiftAmt = SA->getZExtValue();
1327
Reid Spencer1791f232007-03-12 17:25:59 +00001328 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001329 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1330 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001331 RHSKnownZero, RHSKnownOne, Depth+1))
1332 return true;
1333 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1334 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001335 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1336 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001337 if (ShiftAmt) {
1338 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001339 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001340 RHSKnownZero |= HighBits; // high bits known zero.
1341 }
Reid Spencer1791f232007-03-12 17:25:59 +00001342 }
1343 break;
1344 case Instruction::AShr:
1345 // If this is an arithmetic shift right and only the low-bit is set, we can
1346 // always convert this into a logical shr, even if the shift amount is
1347 // variable. The low bit of the shift cannot be an input sign bit unless
1348 // the shift amount is >= the size of the datatype, which is undefined.
1349 if (DemandedMask == 1) {
1350 // Perform the logical shift right.
1351 Value *NewVal = BinaryOperator::createLShr(
1352 I->getOperand(0), I->getOperand(1), I->getName());
1353 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1354 return UpdateValueUsesWith(I, NewVal);
1355 }
1356
1357 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358 unsigned ShiftAmt = SA->getZExtValue();
1359
Reid Spencer1791f232007-03-12 17:25:59 +00001360 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001361 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001362 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001363 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001364 RHSKnownZero, RHSKnownOne, Depth+1))
1365 return true;
1366 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1367 "Bits known to be one AND zero?");
1368 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001369 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001370 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1371 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1372
1373 // Handle the sign bits.
1374 APInt SignBit(APInt::getSignBit(BitWidth));
1375 // Adjust to where it is now in the mask.
1376 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1377
1378 // If the input sign bit is known to be zero, or if none of the top bits
1379 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001380 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001381 (HighBits & ~DemandedMask) == HighBits) {
1382 // Perform the logical shift right.
1383 Value *NewVal = BinaryOperator::createLShr(
1384 I->getOperand(0), SA, I->getName());
1385 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1386 return UpdateValueUsesWith(I, NewVal);
1387 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1388 RHSKnownOne |= HighBits;
1389 }
1390 }
1391 break;
1392 }
1393
1394 // If the client is only demanding bits that we know, return the known
1395 // constant.
1396 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1397 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1398 return false;
1399}
1400
Chris Lattner2deeaea2006-10-05 06:55:50 +00001401
1402/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1403/// 64 or fewer elements. DemandedElts contains the set of elements that are
1404/// actually used by the caller. This method analyzes which elements of the
1405/// operand are undef and returns that information in UndefElts.
1406///
1407/// If the information about demanded elements can be used to simplify the
1408/// operation, the operation is simplified, then the resultant value is
1409/// returned. This returns null if no change was made.
1410Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1411 uint64_t &UndefElts,
1412 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001413 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001414 assert(VWidth <= 64 && "Vector too wide to analyze!");
1415 uint64_t EltMask = ~0ULL >> (64-VWidth);
1416 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1417 "Invalid DemandedElts!");
1418
1419 if (isa<UndefValue>(V)) {
1420 // If the entire vector is undefined, just return this info.
1421 UndefElts = EltMask;
1422 return 0;
1423 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1424 UndefElts = EltMask;
1425 return UndefValue::get(V->getType());
1426 }
1427
1428 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001429 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1430 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001431 Constant *Undef = UndefValue::get(EltTy);
1432
1433 std::vector<Constant*> Elts;
1434 for (unsigned i = 0; i != VWidth; ++i)
1435 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1436 Elts.push_back(Undef);
1437 UndefElts |= (1ULL << i);
1438 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1439 Elts.push_back(Undef);
1440 UndefElts |= (1ULL << i);
1441 } else { // Otherwise, defined.
1442 Elts.push_back(CP->getOperand(i));
1443 }
1444
1445 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001446 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001447 return NewCP != CP ? NewCP : 0;
1448 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001449 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001450 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001452 Constant *Zero = Constant::getNullValue(EltTy);
1453 Constant *Undef = UndefValue::get(EltTy);
1454 std::vector<Constant*> Elts;
1455 for (unsigned i = 0; i != VWidth; ++i)
1456 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1457 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001458 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001459 }
1460
1461 if (!V->hasOneUse()) { // Other users may use these bits.
1462 if (Depth != 0) { // Not at the root.
1463 // TODO: Just compute the UndefElts information recursively.
1464 return false;
1465 }
1466 return false;
1467 } else if (Depth == 10) { // Limit search depth.
1468 return false;
1469 }
1470
1471 Instruction *I = dyn_cast<Instruction>(V);
1472 if (!I) return false; // Only analyze instructions.
1473
1474 bool MadeChange = false;
1475 uint64_t UndefElts2;
1476 Value *TmpV;
1477 switch (I->getOpcode()) {
1478 default: break;
1479
1480 case Instruction::InsertElement: {
1481 // If this is a variable index, we don't know which element it overwrites.
1482 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001483 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001484 if (Idx == 0) {
1485 // Note that we can't propagate undef elt info, because we don't know
1486 // which elt is getting updated.
1487 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1488 UndefElts2, Depth+1);
1489 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1490 break;
1491 }
1492
1493 // If this is inserting an element that isn't demanded, remove this
1494 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001495 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001496 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1497 return AddSoonDeadInstToWorklist(*I, 0);
1498
1499 // Otherwise, the element inserted overwrites whatever was there, so the
1500 // input demanded set is simpler than the output set.
1501 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1502 DemandedElts & ~(1ULL << IdxNo),
1503 UndefElts, Depth+1);
1504 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1505
1506 // The inserted element is defined.
1507 UndefElts |= 1ULL << IdxNo;
1508 break;
1509 }
1510
1511 case Instruction::And:
1512 case Instruction::Or:
1513 case Instruction::Xor:
1514 case Instruction::Add:
1515 case Instruction::Sub:
1516 case Instruction::Mul:
1517 // div/rem demand all inputs, because they don't want divide by zero.
1518 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1519 UndefElts, Depth+1);
1520 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1521 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1522 UndefElts2, Depth+1);
1523 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1524
1525 // Output elements are undefined if both are undefined. Consider things
1526 // like undef&0. The result is known zero, not undef.
1527 UndefElts &= UndefElts2;
1528 break;
1529
1530 case Instruction::Call: {
1531 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1532 if (!II) break;
1533 switch (II->getIntrinsicID()) {
1534 default: break;
1535
1536 // Binary vector operations that work column-wise. A dest element is a
1537 // function of the corresponding input elements from the two inputs.
1538 case Intrinsic::x86_sse_sub_ss:
1539 case Intrinsic::x86_sse_mul_ss:
1540 case Intrinsic::x86_sse_min_ss:
1541 case Intrinsic::x86_sse_max_ss:
1542 case Intrinsic::x86_sse2_sub_sd:
1543 case Intrinsic::x86_sse2_mul_sd:
1544 case Intrinsic::x86_sse2_min_sd:
1545 case Intrinsic::x86_sse2_max_sd:
1546 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1547 UndefElts, Depth+1);
1548 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1549 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1550 UndefElts2, Depth+1);
1551 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1552
1553 // If only the low elt is demanded and this is a scalarizable intrinsic,
1554 // scalarize it now.
1555 if (DemandedElts == 1) {
1556 switch (II->getIntrinsicID()) {
1557 default: break;
1558 case Intrinsic::x86_sse_sub_ss:
1559 case Intrinsic::x86_sse_mul_ss:
1560 case Intrinsic::x86_sse2_sub_sd:
1561 case Intrinsic::x86_sse2_mul_sd:
1562 // TODO: Lower MIN/MAX/ABS/etc
1563 Value *LHS = II->getOperand(1);
1564 Value *RHS = II->getOperand(2);
1565 // Extract the element as scalars.
1566 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1567 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1568
1569 switch (II->getIntrinsicID()) {
1570 default: assert(0 && "Case stmts out of sync!");
1571 case Intrinsic::x86_sse_sub_ss:
1572 case Intrinsic::x86_sse2_sub_sd:
1573 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1574 II->getName()), *II);
1575 break;
1576 case Intrinsic::x86_sse_mul_ss:
1577 case Intrinsic::x86_sse2_mul_sd:
1578 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1579 II->getName()), *II);
1580 break;
1581 }
1582
1583 Instruction *New =
1584 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1585 II->getName());
1586 InsertNewInstBefore(New, *II);
1587 AddSoonDeadInstToWorklist(*II, 0);
1588 return New;
1589 }
1590 }
1591
1592 // Output elements are undefined if both are undefined. Consider things
1593 // like undef&0. The result is known zero, not undef.
1594 UndefElts &= UndefElts2;
1595 break;
1596 }
1597 break;
1598 }
1599 }
1600 return MadeChange ? I : 0;
1601}
1602
Reid Spencer266e42b2006-12-23 06:05:41 +00001603/// @returns true if the specified compare instruction is
1604/// true when both operands are equal...
1605/// @brief Determine if the ICmpInst returns true if both operands are equal
1606static bool isTrueWhenEqual(ICmpInst &ICI) {
1607 ICmpInst::Predicate pred = ICI.getPredicate();
1608 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1609 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1610 pred == ICmpInst::ICMP_SLE;
1611}
1612
Chris Lattnerb8b97502003-08-13 19:01:45 +00001613/// AssociativeOpt - Perform an optimization on an associative operator. This
1614/// function is designed to check a chain of associative operators for a
1615/// potential to apply a certain optimization. Since the optimization may be
1616/// applicable if the expression was reassociated, this checks the chain, then
1617/// reassociates the expression as necessary to expose the optimization
1618/// opportunity. This makes use of a special Functor, which must define
1619/// 'shouldApply' and 'apply' methods.
1620///
1621template<typename Functor>
1622Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1623 unsigned Opcode = Root.getOpcode();
1624 Value *LHS = Root.getOperand(0);
1625
1626 // Quick check, see if the immediate LHS matches...
1627 if (F.shouldApply(LHS))
1628 return F.apply(Root);
1629
1630 // Otherwise, if the LHS is not of the same opcode as the root, return.
1631 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001632 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001633 // Should we apply this transform to the RHS?
1634 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1635
1636 // If not to the RHS, check to see if we should apply to the LHS...
1637 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1638 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1639 ShouldApply = true;
1640 }
1641
1642 // If the functor wants to apply the optimization to the RHS of LHSI,
1643 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1644 if (ShouldApply) {
1645 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001646
Chris Lattnerb8b97502003-08-13 19:01:45 +00001647 // Now all of the instructions are in the current basic block, go ahead
1648 // and perform the reassociation.
1649 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1650
1651 // First move the selected RHS to the LHS of the root...
1652 Root.setOperand(0, LHSI->getOperand(1));
1653
1654 // Make what used to be the LHS of the root be the user of the root...
1655 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001656 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001657 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1658 return 0;
1659 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001660 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001661 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001662 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1663 BasicBlock::iterator ARI = &Root; ++ARI;
1664 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1665 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001666
1667 // Now propagate the ExtraOperand down the chain of instructions until we
1668 // get to LHSI.
1669 while (TmpLHSI != LHSI) {
1670 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001671 // Move the instruction to immediately before the chain we are
1672 // constructing to avoid breaking dominance properties.
1673 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1674 BB->getInstList().insert(ARI, NextLHSI);
1675 ARI = NextLHSI;
1676
Chris Lattnerb8b97502003-08-13 19:01:45 +00001677 Value *NextOp = NextLHSI->getOperand(1);
1678 NextLHSI->setOperand(1, ExtraOperand);
1679 TmpLHSI = NextLHSI;
1680 ExtraOperand = NextOp;
1681 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001682
Chris Lattnerb8b97502003-08-13 19:01:45 +00001683 // Now that the instructions are reassociated, have the functor perform
1684 // the transformation...
1685 return F.apply(Root);
1686 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001687
Chris Lattnerb8b97502003-08-13 19:01:45 +00001688 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1689 }
1690 return 0;
1691}
1692
1693
1694// AddRHS - Implements: X + X --> X << 1
1695struct AddRHS {
1696 Value *RHS;
1697 AddRHS(Value *rhs) : RHS(rhs) {}
1698 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1699 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001700 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001701 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001702 }
1703};
1704
1705// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1706// iff C1&C2 == 0
1707struct AddMaskingAnd {
1708 Constant *C2;
1709 AddMaskingAnd(Constant *c) : C2(c) {}
1710 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001711 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001712 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001713 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001714 }
1715 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001716 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001717 }
1718};
1719
Chris Lattner86102b82005-01-01 16:22:27 +00001720static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001721 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001722 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001723 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001724 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001725
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001726 return IC->InsertNewInstBefore(CastInst::create(
1727 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001728 }
1729
Chris Lattner183b3362004-04-09 19:05:30 +00001730 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001731 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1732 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001733
Chris Lattner183b3362004-04-09 19:05:30 +00001734 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1735 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001736 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1737 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001738 }
1739
1740 Value *Op0 = SO, *Op1 = ConstOperand;
1741 if (!ConstIsRHS)
1742 std::swap(Op0, Op1);
1743 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001744 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1745 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001746 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1747 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1748 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001749 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001750 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001751 abort();
1752 }
Chris Lattner86102b82005-01-01 16:22:27 +00001753 return IC->InsertNewInstBefore(New, I);
1754}
1755
1756// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1757// constant as the other operand, try to fold the binary operator into the
1758// select arguments. This also works for Cast instructions, which obviously do
1759// not have a second operand.
1760static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1761 InstCombiner *IC) {
1762 // Don't modify shared select instructions
1763 if (!SI->hasOneUse()) return 0;
1764 Value *TV = SI->getOperand(1);
1765 Value *FV = SI->getOperand(2);
1766
1767 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001768 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001769 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001770
Chris Lattner86102b82005-01-01 16:22:27 +00001771 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1772 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1773
1774 return new SelectInst(SI->getCondition(), SelectTrueVal,
1775 SelectFalseVal);
1776 }
1777 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001778}
1779
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001780
1781/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1782/// node as operand #0, see if we can fold the instruction into the PHI (which
1783/// is only possible if all operands to the PHI are constants).
1784Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1785 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001786 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001787 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001788
Chris Lattner04689872006-09-09 22:02:56 +00001789 // Check to see if all of the operands of the PHI are constants. If there is
1790 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001791 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001792 BasicBlock *NonConstBB = 0;
1793 for (unsigned i = 0; i != NumPHIValues; ++i)
1794 if (!isa<Constant>(PN->getIncomingValue(i))) {
1795 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001796 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001797 NonConstBB = PN->getIncomingBlock(i);
1798
1799 // If the incoming non-constant value is in I's block, we have an infinite
1800 // loop.
1801 if (NonConstBB == I.getParent())
1802 return 0;
1803 }
1804
1805 // If there is exactly one non-constant value, we can insert a copy of the
1806 // operation in that block. However, if this is a critical edge, we would be
1807 // inserting the computation one some other paths (e.g. inside a loop). Only
1808 // do this if the pred block is unconditionally branching into the phi block.
1809 if (NonConstBB) {
1810 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1811 if (!BI || !BI->isUnconditional()) return 0;
1812 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001813
1814 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001815 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001816 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001817 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001818 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001819
1820 // Next, add all of the operands to the PHI.
1821 if (I.getNumOperands() == 2) {
1822 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001823 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001824 Value *InV;
1825 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001826 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1827 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1828 else
1829 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001830 } else {
1831 assert(PN->getIncomingBlock(i) == NonConstBB);
1832 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1833 InV = BinaryOperator::create(BO->getOpcode(),
1834 PN->getIncomingValue(i), C, "phitmp",
1835 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001836 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1837 InV = CmpInst::create(CI->getOpcode(),
1838 CI->getPredicate(),
1839 PN->getIncomingValue(i), C, "phitmp",
1840 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001841 else
1842 assert(0 && "Unknown binop!");
1843
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001844 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001845 }
1846 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001847 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001848 } else {
1849 CastInst *CI = cast<CastInst>(&I);
1850 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001851 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001852 Value *InV;
1853 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001854 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001855 } else {
1856 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001857 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1858 I.getType(), "phitmp",
1859 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001860 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001861 }
1862 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001863 }
1864 }
1865 return ReplaceInstUsesWith(I, NewPN);
1866}
1867
Chris Lattner113f4f42002-06-25 16:13:24 +00001868Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001869 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001870 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001871
Chris Lattnercf4a9962004-04-10 22:01:55 +00001872 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001873 // X + undef -> undef
1874 if (isa<UndefValue>(RHS))
1875 return ReplaceInstUsesWith(I, RHS);
1876
Chris Lattnercf4a9962004-04-10 22:01:55 +00001877 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001878 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001879 if (RHSC->isNullValue())
1880 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001881 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1882 if (CFP->isExactlyValue(-0.0))
1883 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001884 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001885
Chris Lattnercf4a9962004-04-10 22:01:55 +00001886 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001887 // X + (signbit) --> X ^ signbit
Reid Spencer959a21d2007-03-23 21:24:59 +00001888 APInt Val(CI->getValue());
1889 unsigned BitWidth = Val.getBitWidth();
1890 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001891 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001892
1893 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1894 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001895 if (!isa<VectorType>(I.getType())) {
1896 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1897 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1898 KnownZero, KnownOne))
1899 return &I;
1900 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001901 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001902
1903 if (isa<PHINode>(LHS))
1904 if (Instruction *NV = FoldOpIntoPhi(I))
1905 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001906
Chris Lattner330628a2006-01-06 17:59:59 +00001907 ConstantInt *XorRHS = 0;
1908 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001909 if (isa<ConstantInt>(RHSC) &&
1910 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001911 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00001912 APInt RHSVal(cast<ConstantInt>(RHSC)->getValue());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001913
Reid Spencer959a21d2007-03-23 21:24:59 +00001914 unsigned Size = TySizeBits / 2;
1915 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1916 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001917 do {
1918 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001919 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1920 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001921 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1922 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001923 // This is a sign extend if the top bits are known zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00001924 APInt Mask(APInt::getAllOnesValue(TySizeBits));
1925 Mask <<= Size;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001926 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001927 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001928 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001929 }
1930 }
1931 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001932 C0080Val = APIntOps::lshr(C0080Val, Size);
1933 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1934 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001935
Reid Spencera5c18bf2007-03-28 01:36:16 +00001936 // FIXME: This shouldn't be necessary. When the backends can handle types
1937 // with funny bit widths then this whole cascade of if statements should
1938 // be removed. It is just here to get the size of the "middle" type back
1939 // up to something that the back ends can handle.
1940 const Type *MiddleType = 0;
1941 switch (Size) {
1942 default: break;
1943 case 32: MiddleType = Type::Int32Ty; break;
1944 case 16: MiddleType = Type::Int16Ty; break;
1945 case 8: MiddleType = Type::Int8Ty; break;
1946 }
1947 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001948 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001949 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001950 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001951 }
1952 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001953 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001954
Chris Lattnerb8b97502003-08-13 19:01:45 +00001955 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001956 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001957 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001958
1959 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1960 if (RHSI->getOpcode() == Instruction::Sub)
1961 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1962 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1963 }
1964 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1965 if (LHSI->getOpcode() == Instruction::Sub)
1966 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1967 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1968 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001969 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001970
Chris Lattner147e9752002-05-08 22:46:53 +00001971 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001972 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001973 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001974
1975 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001976 if (!isa<Constant>(RHS))
1977 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001978 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001979
Misha Brukmanb1c93172005-04-21 23:48:37 +00001980
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001981 ConstantInt *C2;
1982 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1983 if (X == RHS) // X*C + X --> X * (C+1)
1984 return BinaryOperator::createMul(RHS, AddOne(C2));
1985
1986 // X*C1 + X*C2 --> X * (C1+C2)
1987 ConstantInt *C1;
1988 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00001989 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001990 }
1991
1992 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001993 if (dyn_castFoldableMul(RHS, C2) == LHS)
1994 return BinaryOperator::createMul(LHS, AddOne(C2));
1995
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001996 // X + ~X --> -1 since ~X = -X-1
1997 if (dyn_castNotVal(LHS) == RHS ||
1998 dyn_castNotVal(RHS) == LHS)
1999 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2000
Chris Lattner57c8d992003-02-18 19:57:07 +00002001
Chris Lattnerb8b97502003-08-13 19:01:45 +00002002 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002003 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002004 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2005 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002006
Chris Lattnerb9cde762003-10-02 15:11:26 +00002007 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002008 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002009 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2010 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002011
Chris Lattnerbff91d92004-10-08 05:07:56 +00002012 // (X & FF00) + xx00 -> (X+xx00) & FF00
2013 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002014 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002015 if (Anded == CRHS) {
2016 // See if all bits from the first bit set in the Add RHS up are included
2017 // in the mask. First, get the rightmost bit.
Reid Spencer959a21d2007-03-23 21:24:59 +00002018 APInt AddRHSV(CRHS->getValue());
Chris Lattnerbff91d92004-10-08 05:07:56 +00002019
2020 // Form a mask of all bits from the lowest bit added through the top.
Reid Spencer959a21d2007-03-23 21:24:59 +00002021 APInt AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2022 AddRHSHighBits &= C2->getType()->getMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002023
2024 // See if the and mask includes all of these bits.
Reid Spencer959a21d2007-03-23 21:24:59 +00002025 APInt AddRHSHighBitsAnd = AddRHSHighBits & C2->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002026
Chris Lattnerbff91d92004-10-08 05:07:56 +00002027 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2028 // Okay, the xform is safe. Insert the new add pronto.
2029 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2030 LHS->getName()), I);
2031 return BinaryOperator::createAnd(NewAdd, C2);
2032 }
2033 }
2034 }
2035
Chris Lattnerd4252a72004-07-30 07:50:03 +00002036 // Try to fold constant add into select arguments.
2037 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002038 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002039 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002040 }
2041
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002042 // add (cast *A to intptrtype) B ->
2043 // cast (GEP (cast *A to sbyte*) B) ->
2044 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002045 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002046 CastInst *CI = dyn_cast<CastInst>(LHS);
2047 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002048 if (!CI) {
2049 CI = dyn_cast<CastInst>(RHS);
2050 Other = LHS;
2051 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002052 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002053 (CI->getType()->getPrimitiveSizeInBits() ==
2054 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002055 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002056 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002057 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002058 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002059 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002060 }
2061 }
2062
Chris Lattner113f4f42002-06-25 16:13:24 +00002063 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002064}
2065
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002066// isSignBit - Return true if the value represented by the constant only has the
2067// highest order bit set.
2068static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002069 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002070 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002071}
2072
Chris Lattner113f4f42002-06-25 16:13:24 +00002073Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002074 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002075
Chris Lattnere6794492002-08-12 21:17:25 +00002076 if (Op0 == Op1) // sub X, X -> 0
2077 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002078
Chris Lattnere6794492002-08-12 21:17:25 +00002079 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002080 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002081 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002082
Chris Lattner81a7a232004-10-16 18:11:37 +00002083 if (isa<UndefValue>(Op0))
2084 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2085 if (isa<UndefValue>(Op1))
2086 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2087
Chris Lattner8f2f5982003-11-05 01:06:05 +00002088 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2089 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002090 if (C->isAllOnesValue())
2091 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002092
Chris Lattner8f2f5982003-11-05 01:06:05 +00002093 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002094 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002095 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002096 return BinaryOperator::createAdd(X, AddOne(C));
2097
Chris Lattner27df1db2007-01-15 07:02:54 +00002098 // -(X >>u 31) -> (X >>s 31)
2099 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002100 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002101 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002102 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002103 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002104 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002105 if (CU->getZExtValue() ==
2106 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002107 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002108 return BinaryOperator::create(Instruction::AShr,
2109 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002110 }
2111 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002112 }
2113 else if (SI->getOpcode() == Instruction::AShr) {
2114 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2115 // Check to see if we are shifting out everything but the sign bit.
2116 if (CU->getZExtValue() ==
2117 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002118 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002119 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002120 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002121 }
2122 }
2123 }
Chris Lattner022167f2004-03-13 00:11:49 +00002124 }
Chris Lattner183b3362004-04-09 19:05:30 +00002125
2126 // Try to fold constant sub into select arguments.
2127 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002128 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002129 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002130
2131 if (isa<PHINode>(Op0))
2132 if (Instruction *NV = FoldOpIntoPhi(I))
2133 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002134 }
2135
Chris Lattnera9be4492005-04-07 16:15:25 +00002136 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2137 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002138 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002139 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002140 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002141 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002142 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002143 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2144 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2145 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002146 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002147 Op1I->getOperand(0));
2148 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002149 }
2150
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002151 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002152 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2153 // is not used by anyone else...
2154 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002155 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002156 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002157 // Swap the two operands of the subexpr...
2158 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2159 Op1I->setOperand(0, IIOp1);
2160 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002161
Chris Lattner3082c5a2003-02-18 19:28:33 +00002162 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002163 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002164 }
2165
2166 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2167 //
2168 if (Op1I->getOpcode() == Instruction::And &&
2169 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2170 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2171
Chris Lattner396dbfe2004-06-09 05:08:07 +00002172 Value *NewNot =
2173 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002174 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002175 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002176
Reid Spencer3c514952006-10-16 23:08:08 +00002177 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002178 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002179 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002180 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002181 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002182 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002183 ConstantExpr::getNeg(DivRHS));
2184
Chris Lattner57c8d992003-02-18 19:57:07 +00002185 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002186 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002187 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002188 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002189 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002190 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002191 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002192 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002193
Chris Lattner7a002fe2006-12-02 00:13:08 +00002194 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002195 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2196 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002197 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2198 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2199 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2200 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002201 } else if (Op0I->getOpcode() == Instruction::Sub) {
2202 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2203 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002204 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002205
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002206 ConstantInt *C1;
2207 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002208 if (X == Op1) // X*C - X --> X * (C-1)
2209 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002210
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002211 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2212 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002213 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002214 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002215 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002216}
2217
Reid Spencer266e42b2006-12-23 06:05:41 +00002218/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002219/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002220static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2221 switch (pred) {
2222 case ICmpInst::ICMP_SLT:
2223 // True if LHS s< RHS and RHS == 0
2224 return RHS->isNullValue();
2225 case ICmpInst::ICMP_SLE:
2226 // True if LHS s<= RHS and RHS == -1
2227 return RHS->isAllOnesValue();
2228 case ICmpInst::ICMP_UGE:
2229 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002230 return RHS->getValue() ==
2231 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002232 case ICmpInst::ICMP_UGT:
2233 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002234 return RHS->getValue() ==
2235 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002236 default:
2237 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002238 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002239}
2240
Chris Lattner113f4f42002-06-25 16:13:24 +00002241Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002242 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002243 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002244
Chris Lattner81a7a232004-10-16 18:11:37 +00002245 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2246 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2247
Chris Lattnere6794492002-08-12 21:17:25 +00002248 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002249 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2250 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002251
2252 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002253 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002254 if (SI->getOpcode() == Instruction::Shl)
2255 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002256 return BinaryOperator::createMul(SI->getOperand(0),
2257 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002258
Chris Lattnercce81be2003-09-11 22:24:54 +00002259 if (CI->isNullValue())
2260 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2261 if (CI->equalsInt(1)) // X * 1 == X
2262 return ReplaceInstUsesWith(I, Op0);
2263 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002264 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002265
Zhou Sheng4961cf12007-03-29 01:57:21 +00002266 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002267 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002268 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002269 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002270 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002271 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002272 if (Op1F->isNullValue())
2273 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002274
Chris Lattner3082c5a2003-02-18 19:28:33 +00002275 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2276 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2277 if (Op1F->getValue() == 1.0)
2278 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2279 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002280
2281 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2282 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2283 isa<ConstantInt>(Op0I->getOperand(1))) {
2284 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2285 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2286 Op1, "tmp");
2287 InsertNewInstBefore(Add, I);
2288 Value *C1C2 = ConstantExpr::getMul(Op1,
2289 cast<Constant>(Op0I->getOperand(1)));
2290 return BinaryOperator::createAdd(Add, C1C2);
2291
2292 }
Chris Lattner183b3362004-04-09 19:05:30 +00002293
2294 // Try to fold constant mul into select arguments.
2295 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002296 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002297 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002298
2299 if (isa<PHINode>(Op0))
2300 if (Instruction *NV = FoldOpIntoPhi(I))
2301 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002302 }
2303
Chris Lattner934a64cf2003-03-10 23:23:04 +00002304 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2305 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002306 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002307
Chris Lattner2635b522004-02-23 05:39:21 +00002308 // If one of the operands of the multiply is a cast from a boolean value, then
2309 // we know the bool is either zero or one, so this is a 'masking' multiply.
2310 // See if we can simplify things based on how the boolean was originally
2311 // formed.
2312 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002313 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002314 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002315 BoolCast = CI;
2316 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002317 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002318 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002319 BoolCast = CI;
2320 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002321 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002322 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2323 const Type *SCOpTy = SCIOp0->getType();
2324
Reid Spencer266e42b2006-12-23 06:05:41 +00002325 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002326 // multiply into a shift/and combination.
2327 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002328 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002329 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002330 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002331 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002332 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002333 InsertNewInstBefore(
2334 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002335 BoolCast->getOperand(0)->getName()+
2336 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002337
2338 // If the multiply type is not the same as the source type, sign extend
2339 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002340 if (I.getType() != V->getType()) {
2341 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2342 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2343 Instruction::CastOps opcode =
2344 (SrcBits == DstBits ? Instruction::BitCast :
2345 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2346 V = InsertCastBefore(opcode, V, I.getType(), I);
2347 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002348
Chris Lattner2635b522004-02-23 05:39:21 +00002349 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002350 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002351 }
2352 }
2353 }
2354
Chris Lattner113f4f42002-06-25 16:13:24 +00002355 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002356}
2357
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002358/// This function implements the transforms on div instructions that work
2359/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2360/// used by the visitors to those instructions.
2361/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002362Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002364
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002365 // undef / X -> 0
2366 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002368
2369 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002370 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002371 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002372
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002373 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002374 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2375 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002376 // same basic block, then we replace the select with Y, and the condition
2377 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002378 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002379 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002380 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2381 if (ST->isNullValue()) {
2382 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2383 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002384 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002385 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2386 I.setOperand(1, SI->getOperand(2));
2387 else
2388 UpdateValueUsesWith(SI, SI->getOperand(2));
2389 return &I;
2390 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002391
Chris Lattnerd79dc792006-09-09 20:26:32 +00002392 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2393 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2394 if (ST->isNullValue()) {
2395 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2396 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002397 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002398 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2399 I.setOperand(1, SI->getOperand(1));
2400 else
2401 UpdateValueUsesWith(SI, SI->getOperand(1));
2402 return &I;
2403 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002404 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002405
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002406 return 0;
2407}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002408
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002409/// This function implements the transforms common to both integer division
2410/// instructions (udiv and sdiv). It is called by the visitors to those integer
2411/// division instructions.
2412/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002413Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2415
2416 if (Instruction *Common = commonDivTransforms(I))
2417 return Common;
2418
2419 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2420 // div X, 1 == X
2421 if (RHS->equalsInt(1))
2422 return ReplaceInstUsesWith(I, Op0);
2423
2424 // (X / C1) / C2 -> X / (C1*C2)
2425 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2426 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2427 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2428 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002429 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002430 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002431
Reid Spencer6d392062007-03-23 20:05:17 +00002432 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2434 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2435 return R;
2436 if (isa<PHINode>(Op0))
2437 if (Instruction *NV = FoldOpIntoPhi(I))
2438 return NV;
2439 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002440 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002441
Chris Lattner3082c5a2003-02-18 19:28:33 +00002442 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002443 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002444 if (LHS->equalsInt(0))
2445 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2446
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002447 return 0;
2448}
2449
2450Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2451 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2452
2453 // Handle the integer div common cases
2454 if (Instruction *Common = commonIDivTransforms(I))
2455 return Common;
2456
2457 // X udiv C^2 -> X >> C
2458 // Check to see if this is an unsigned division with an exact power of 2,
2459 // if so, convert to a right shift.
2460 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002461 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002462 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002463 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002464 }
2465
2466 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002467 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002468 if (RHSI->getOpcode() == Instruction::Shl &&
2469 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002470 APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2471 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002472 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002473 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002474 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002475 Constant *C2V = ConstantInt::get(NTy, C2);
2476 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002477 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002478 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002479 }
2480 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002481 }
2482
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002483 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2484 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002485 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002486 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002487 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002488 APInt TVA(STO->getValue()), FVA(SFO->getValue());
2489 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002490 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002491 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002492 // Construct the "on true" case of the select
2493 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2494 Instruction *TSI = BinaryOperator::createLShr(
2495 Op0, TC, SI->getName()+".t");
2496 TSI = InsertNewInstBefore(TSI, I);
2497
2498 // Construct the "on false" case of the select
2499 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2500 Instruction *FSI = BinaryOperator::createLShr(
2501 Op0, FC, SI->getName()+".f");
2502 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002503
Reid Spencer3939b1a2007-03-05 23:36:13 +00002504 // construct the select instruction and return it.
2505 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002506 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002507 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002508 return 0;
2509}
2510
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002511Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2513
2514 // Handle the integer div common cases
2515 if (Instruction *Common = commonIDivTransforms(I))
2516 return Common;
2517
2518 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2519 // sdiv X, -1 == -X
2520 if (RHS->isAllOnesValue())
2521 return BinaryOperator::createNeg(Op0);
2522
2523 // -X/C -> X/-C
2524 if (Value *LHSNeg = dyn_castNegVal(Op0))
2525 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2526 }
2527
2528 // If the sign bits of both operands are zero (i.e. we can prove they are
2529 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002530 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002531 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002532 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2533 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2534 }
2535 }
2536
2537 return 0;
2538}
2539
2540Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2541 return commonDivTransforms(I);
2542}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002543
Chris Lattner85dda9a2006-03-02 06:50:58 +00002544/// GetFactor - If we can prove that the specified value is at least a multiple
2545/// of some factor, return that factor.
2546static Constant *GetFactor(Value *V) {
2547 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2548 return CI;
2549
2550 // Unless we can be tricky, we know this is a multiple of 1.
2551 Constant *Result = ConstantInt::get(V->getType(), 1);
2552
2553 Instruction *I = dyn_cast<Instruction>(V);
2554 if (!I) return Result;
2555
2556 if (I->getOpcode() == Instruction::Mul) {
2557 // Handle multiplies by a constant, etc.
2558 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2559 GetFactor(I->getOperand(1)));
2560 } else if (I->getOpcode() == Instruction::Shl) {
2561 // (X<<C) -> X * (1 << C)
2562 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2563 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2564 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2565 }
2566 } else if (I->getOpcode() == Instruction::And) {
2567 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2568 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002569 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002570 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2571 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002572 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002573 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002574 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002575 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002576 if (!CI->isIntegerCast())
2577 return Result;
2578 Value *Op = CI->getOperand(0);
2579 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002580 }
2581 return Result;
2582}
2583
Reid Spencer7eb55b32006-11-02 01:53:59 +00002584/// This function implements the transforms on rem instructions that work
2585/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2586/// is used by the visitors to those instructions.
2587/// @brief Transforms common to all three rem instructions
2588Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002589 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002590
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002591 // 0 % X == 0, we don't need to preserve faults!
2592 if (Constant *LHS = dyn_cast<Constant>(Op0))
2593 if (LHS->isNullValue())
2594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2595
2596 if (isa<UndefValue>(Op0)) // undef % X -> 0
2597 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2598 if (isa<UndefValue>(Op1))
2599 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002600
2601 // Handle cases involving: rem X, (select Cond, Y, Z)
2602 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2603 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2604 // the same basic block, then we replace the select with Y, and the
2605 // condition of the select with false (if the cond value is in the same
2606 // BB). If the select has uses other than the div, this allows them to be
2607 // simplified also.
2608 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2609 if (ST->isNullValue()) {
2610 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2611 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002612 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002613 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2614 I.setOperand(1, SI->getOperand(2));
2615 else
2616 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002617 return &I;
2618 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002619 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2620 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2621 if (ST->isNullValue()) {
2622 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2623 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002624 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002625 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2626 I.setOperand(1, SI->getOperand(1));
2627 else
2628 UpdateValueUsesWith(SI, SI->getOperand(1));
2629 return &I;
2630 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002631 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002632
Reid Spencer7eb55b32006-11-02 01:53:59 +00002633 return 0;
2634}
2635
2636/// This function implements the transforms common to both integer remainder
2637/// instructions (urem and srem). It is called by the visitors to those integer
2638/// remainder instructions.
2639/// @brief Common integer remainder transforms
2640Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2642
2643 if (Instruction *common = commonRemTransforms(I))
2644 return common;
2645
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002646 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002647 // X % 0 == undef, we don't need to preserve faults!
2648 if (RHS->equalsInt(0))
2649 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2650
Chris Lattner3082c5a2003-02-18 19:28:33 +00002651 if (RHS->equalsInt(1)) // X % 1 == 0
2652 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2653
Chris Lattnerb70f1412006-02-28 05:49:21 +00002654 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2655 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2656 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2657 return R;
2658 } else if (isa<PHINode>(Op0I)) {
2659 if (Instruction *NV = FoldOpIntoPhi(I))
2660 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002661 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002662 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2663 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002664 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002665 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002666 }
2667
Reid Spencer7eb55b32006-11-02 01:53:59 +00002668 return 0;
2669}
2670
2671Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2672 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2673
2674 if (Instruction *common = commonIRemTransforms(I))
2675 return common;
2676
2677 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2678 // X urem C^2 -> X and C
2679 // Check to see if this is an unsigned remainder with an exact power of 2,
2680 // if so, convert to a bitwise and.
2681 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002682 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002683 return BinaryOperator::createAnd(Op0, SubOne(C));
2684 }
2685
Chris Lattner2e90b732006-02-05 07:54:04 +00002686 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002687 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2688 if (RHSI->getOpcode() == Instruction::Shl &&
2689 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002690 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002691 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2692 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2693 "tmp"), I);
2694 return BinaryOperator::createAnd(Op0, Add);
2695 }
2696 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002697 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002698
Reid Spencer7eb55b32006-11-02 01:53:59 +00002699 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2700 // where C1&C2 are powers of two.
2701 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2702 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2703 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2704 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002705 if ((STO->getValue().isPowerOf2()) &&
2706 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002707 Value *TrueAnd = InsertNewInstBefore(
2708 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2709 Value *FalseAnd = InsertNewInstBefore(
2710 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2711 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2712 }
2713 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002714 }
2715
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002716 return 0;
2717}
2718
Reid Spencer7eb55b32006-11-02 01:53:59 +00002719Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2720 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2721
2722 if (Instruction *common = commonIRemTransforms(I))
2723 return common;
2724
2725 if (Value *RHSNeg = dyn_castNegVal(Op1))
2726 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002727 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002728 // X % -Y -> X % Y
2729 AddUsesToWorkList(I);
2730 I.setOperand(1, RHSNeg);
2731 return &I;
2732 }
2733
2734 // If the top bits of both operands are zero (i.e. we can prove they are
2735 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002736 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002737 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2738 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2739 return BinaryOperator::createURem(Op0, Op1, I.getName());
2740 }
2741
2742 return 0;
2743}
2744
2745Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002746 return commonRemTransforms(I);
2747}
2748
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002749// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002750static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002751 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002752 if (isSigned) {
2753 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002754 APInt Val(APInt::getSignedMaxValue(TypeBits));
2755 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002756 }
Reid Spenceref599b02007-03-19 21:10:28 +00002757 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002758}
2759
2760// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002761static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2762 if (isSigned) {
2763 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002764 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2765 APInt Val(APInt::getSignedMinValue(TypeBits));
2766 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002767 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002768 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002769}
2770
Chris Lattner35167c32004-06-09 07:59:58 +00002771// isOneBitSet - Return true if there is exactly one bit set in the specified
2772// constant.
2773static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002774 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002775}
2776
Chris Lattner8fc5af42004-09-23 21:46:38 +00002777// isHighOnes - Return true if the constant is of the form 1+0+.
2778// This is the same as lowones(~X).
2779static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002780 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002781}
2782
Reid Spencer266e42b2006-12-23 06:05:41 +00002783/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002784/// are carefully arranged to allow folding of expressions such as:
2785///
2786/// (A < B) | (A > B) --> (A != B)
2787///
Reid Spencer266e42b2006-12-23 06:05:41 +00002788/// Note that this is only valid if the first and second predicates have the
2789/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002790///
Reid Spencer266e42b2006-12-23 06:05:41 +00002791/// Three bits are used to represent the condition, as follows:
2792/// 0 A > B
2793/// 1 A == B
2794/// 2 A < B
2795///
2796/// <=> Value Definition
2797/// 000 0 Always false
2798/// 001 1 A > B
2799/// 010 2 A == B
2800/// 011 3 A >= B
2801/// 100 4 A < B
2802/// 101 5 A != B
2803/// 110 6 A <= B
2804/// 111 7 Always true
2805///
2806static unsigned getICmpCode(const ICmpInst *ICI) {
2807 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002808 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002809 case ICmpInst::ICMP_UGT: return 1; // 001
2810 case ICmpInst::ICMP_SGT: return 1; // 001
2811 case ICmpInst::ICMP_EQ: return 2; // 010
2812 case ICmpInst::ICMP_UGE: return 3; // 011
2813 case ICmpInst::ICMP_SGE: return 3; // 011
2814 case ICmpInst::ICMP_ULT: return 4; // 100
2815 case ICmpInst::ICMP_SLT: return 4; // 100
2816 case ICmpInst::ICMP_NE: return 5; // 101
2817 case ICmpInst::ICMP_ULE: return 6; // 110
2818 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002819 // True -> 7
2820 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002821 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002822 return 0;
2823 }
2824}
2825
Reid Spencer266e42b2006-12-23 06:05:41 +00002826/// getICmpValue - This is the complement of getICmpCode, which turns an
2827/// opcode and two operands into either a constant true or false, or a brand
2828/// new /// ICmp instruction. The sign is passed in to determine which kind
2829/// of predicate to use in new icmp instructions.
2830static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2831 switch (code) {
2832 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002833 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002834 case 1:
2835 if (sign)
2836 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2837 else
2838 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2839 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2840 case 3:
2841 if (sign)
2842 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2843 else
2844 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2845 case 4:
2846 if (sign)
2847 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2848 else
2849 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2850 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2851 case 6:
2852 if (sign)
2853 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2854 else
2855 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002856 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002857 }
2858}
2859
Reid Spencer266e42b2006-12-23 06:05:41 +00002860static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2861 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2862 (ICmpInst::isSignedPredicate(p1) &&
2863 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2864 (ICmpInst::isSignedPredicate(p2) &&
2865 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2866}
2867
2868namespace {
2869// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2870struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002871 InstCombiner &IC;
2872 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002873 ICmpInst::Predicate pred;
2874 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2875 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2876 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002877 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002878 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2879 if (PredicatesFoldable(pred, ICI->getPredicate()))
2880 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2881 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002882 return false;
2883 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002884 Instruction *apply(Instruction &Log) const {
2885 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2886 if (ICI->getOperand(0) != LHS) {
2887 assert(ICI->getOperand(1) == LHS);
2888 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002889 }
2890
Chris Lattnerd1bce952007-03-13 14:27:42 +00002891 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002892 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002893 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002894 unsigned Code;
2895 switch (Log.getOpcode()) {
2896 case Instruction::And: Code = LHSCode & RHSCode; break;
2897 case Instruction::Or: Code = LHSCode | RHSCode; break;
2898 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002899 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002900 }
2901
Chris Lattnerd1bce952007-03-13 14:27:42 +00002902 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2903 ICmpInst::isSignedPredicate(ICI->getPredicate());
2904
2905 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002906 if (Instruction *I = dyn_cast<Instruction>(RV))
2907 return I;
2908 // Otherwise, it's a constant boolean value...
2909 return IC.ReplaceInstUsesWith(Log, RV);
2910 }
2911};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002912} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002913
Chris Lattnerba1cb382003-09-19 17:17:26 +00002914// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2915// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002916// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002917Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002918 ConstantInt *OpRHS,
2919 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002920 BinaryOperator &TheAnd) {
2921 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002922 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002923 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002924 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002925
Chris Lattnerba1cb382003-09-19 17:17:26 +00002926 switch (Op->getOpcode()) {
2927 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002928 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002929 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002930 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002931 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002932 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002933 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002934 }
2935 break;
2936 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002937 if (Together == AndRHS) // (X | C) & C --> C
2938 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002939
Chris Lattner86102b82005-01-01 16:22:27 +00002940 if (Op->hasOneUse() && Together != OpRHS) {
2941 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002942 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002943 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002944 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002945 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002946 }
2947 break;
2948 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002949 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002950 // Adding a one to a single bit bit-field should be turned into an XOR
2951 // of the bit. First thing to check is to see if this AND is with a
2952 // single bit constant.
Reid Spencer6274c722007-03-23 18:46:34 +00002953 APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
Chris Lattnerba1cb382003-09-19 17:17:26 +00002954
2955 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002956 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002957 // Ok, at this point, we know that we are masking the result of the
2958 // ADD down to exactly one bit. If the constant we are adding has
2959 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencer6274c722007-03-23 18:46:34 +00002960 APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002961
Chris Lattnerba1cb382003-09-19 17:17:26 +00002962 // Check to see if any bits below the one bit set in AndRHSV are set.
2963 if ((AddRHS & (AndRHSV-1)) == 0) {
2964 // If not, the only thing that can effect the output of the AND is
2965 // the bit specified by AndRHSV. If that bit is set, the effect of
2966 // the XOR is to toggle the bit. If it is clear, then the ADD has
2967 // no effect.
2968 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2969 TheAnd.setOperand(0, X);
2970 return &TheAnd;
2971 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002972 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002973 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002974 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002975 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002976 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002977 }
2978 }
2979 }
2980 }
2981 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002982
2983 case Instruction::Shl: {
2984 // We know that the AND will not produce any of the bits shifted in, so if
2985 // the anded constant includes them, clear them now!
2986 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002987 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002988 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2989 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002990
Chris Lattner7e794272004-09-24 15:21:34 +00002991 if (CI == ShlMask) { // Masking out bits that the shift already masks
2992 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2993 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002994 TheAnd.setOperand(1, CI);
2995 return &TheAnd;
2996 }
2997 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002998 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002999 case Instruction::LShr:
3000 {
Chris Lattner2da29172003-09-19 19:05:02 +00003001 // We know that the AND will not produce any of the bits shifted in, so if
3002 // the anded constant includes them, clear them now! This only applies to
3003 // unsigned shifts, because a signed shr may bring in set bits!
3004 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003005 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003006 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3007 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003008
Reid Spencerfdff9382006-11-08 06:47:33 +00003009 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3010 return ReplaceInstUsesWith(TheAnd, Op);
3011 } else if (CI != AndRHS) {
3012 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3013 return &TheAnd;
3014 }
3015 break;
3016 }
3017 case Instruction::AShr:
3018 // Signed shr.
3019 // See if this is shifting in some sign extension, then masking it out
3020 // with an and.
3021 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003022 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003023 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003024 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3025 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003026 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003027 // Make the argument unsigned.
3028 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003029 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003030 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003031 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003032 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003033 }
Chris Lattner2da29172003-09-19 19:05:02 +00003034 }
3035 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003036 }
3037 return 0;
3038}
3039
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003040
Chris Lattner6862fbd2004-09-29 17:40:11 +00003041/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3042/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003043/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3044/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003045/// insert new instructions.
3046Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003047 bool isSigned, bool Inside,
3048 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003049 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003050 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003051 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003052
Chris Lattner6862fbd2004-09-29 17:40:11 +00003053 if (Inside) {
3054 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003055 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003056
Reid Spencer266e42b2006-12-23 06:05:41 +00003057 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003058 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003059 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003060 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3061 return new ICmpInst(pred, V, Hi);
3062 }
3063
3064 // Emit V-Lo <u Hi-Lo
3065 Constant *NegLo = ConstantExpr::getNeg(Lo);
3066 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003067 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003068 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3069 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003070 }
3071
3072 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003073 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003074
Reid Spencerf4071162007-03-21 23:19:50 +00003075 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003076 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003077 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003078 ICmpInst::Predicate pred = (isSigned ?
3079 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3080 return new ICmpInst(pred, V, Hi);
3081 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003082
Reid Spencerf4071162007-03-21 23:19:50 +00003083 // Emit V-Lo >u Hi-1-Lo
3084 // Note that Hi has already had one subtracted from it, above.
3085 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003086 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003087 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003088 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3089 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003090}
3091
Chris Lattnerb4b25302005-09-18 07:22:02 +00003092// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3093// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3094// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3095// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003096static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencera962d182007-03-24 00:42:08 +00003097 APInt V = Val->getValue();
3098 uint32_t BitWidth = Val->getType()->getBitWidth();
3099 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003100
3101 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003102 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003103 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003104 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003105 return true;
3106}
3107
Chris Lattnerb4b25302005-09-18 07:22:02 +00003108/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3109/// where isSub determines whether the operator is a sub. If we can fold one of
3110/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003111///
3112/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3113/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3114/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3115///
3116/// return (A +/- B).
3117///
3118Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003119 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003120 Instruction &I) {
3121 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3122 if (!LHSI || LHSI->getNumOperands() != 2 ||
3123 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3124
3125 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3126
3127 switch (LHSI->getOpcode()) {
3128 default: return 0;
3129 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003130 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003131 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003132 if ((Mask->getValue().countLeadingZeros() +
3133 Mask->getValue().countPopulation()) ==
3134 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003135 break;
3136
3137 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3138 // part, we don't need any explicit masks to take them out of A. If that
3139 // is all N is, ignore it.
Reid Spencer755d0e72007-03-26 17:44:01 +00003140 unsigned MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003141 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003142 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3143 APInt Mask(APInt::getAllOnesValue(BitWidth));
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003144 Mask = Mask.lshr(BitWidth-MB+1);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003145 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003146 break;
3147 }
3148 }
Chris Lattneraf517572005-09-18 04:24:45 +00003149 return 0;
3150 case Instruction::Or:
3151 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003152 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003153 if ((Mask->getValue().countLeadingZeros() +
3154 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003155 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003156 break;
3157 return 0;
3158 }
3159
3160 Instruction *New;
3161 if (isSub)
3162 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3163 else
3164 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3165 return InsertNewInstBefore(New, I);
3166}
3167
Chris Lattner113f4f42002-06-25 16:13:24 +00003168Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003169 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003171
Chris Lattner81a7a232004-10-16 18:11:37 +00003172 if (isa<UndefValue>(Op1)) // X & undef -> 0
3173 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3174
Chris Lattner86102b82005-01-01 16:22:27 +00003175 // and X, X = X
3176 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003177 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003178
Chris Lattner5b2edb12006-02-12 08:02:11 +00003179 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003180 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003181 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003182 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3183 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3184 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003185 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003186 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003187 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003188 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003189 if (CP->isAllOnesValue())
3190 return ReplaceInstUsesWith(I, I.getOperand(0));
3191 }
3192 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003193
Zhou Sheng75b871f2007-01-11 12:24:14 +00003194 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003195 APInt AndRHSMask(AndRHS->getValue());
3196 APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3197 APInt NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003198
Chris Lattnerba1cb382003-09-19 17:17:26 +00003199 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003200 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003201 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003202 Value *Op0LHS = Op0I->getOperand(0);
3203 Value *Op0RHS = Op0I->getOperand(1);
3204 switch (Op0I->getOpcode()) {
3205 case Instruction::Xor:
3206 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003207 // If the mask is only needed on one incoming arm, push it up.
3208 if (Op0I->hasOneUse()) {
3209 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3210 // Not masking anything out for the LHS, move to RHS.
3211 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3212 Op0RHS->getName()+".masked");
3213 InsertNewInstBefore(NewRHS, I);
3214 return BinaryOperator::create(
3215 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003216 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003217 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003218 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3219 // Not masking anything out for the RHS, move to LHS.
3220 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3221 Op0LHS->getName()+".masked");
3222 InsertNewInstBefore(NewLHS, I);
3223 return BinaryOperator::create(
3224 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3225 }
3226 }
3227
Chris Lattner86102b82005-01-01 16:22:27 +00003228 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003229 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003230 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3231 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3232 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3233 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3234 return BinaryOperator::createAnd(V, AndRHS);
3235 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3236 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003237 break;
3238
3239 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003240 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3241 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3242 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3243 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3244 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003245 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003246 }
3247
Chris Lattner16464b32003-07-23 19:25:52 +00003248 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003249 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003250 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003251 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003252 // If this is an integer truncation or change from signed-to-unsigned, and
3253 // if the source is an and/or with immediate, transform it. This
3254 // frequently occurs for bitfield accesses.
3255 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003256 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003257 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003258 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003259 if (CastOp->getOpcode() == Instruction::And) {
3260 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003261 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3262 // This will fold the two constants together, which may allow
3263 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003264 Instruction *NewCast = CastInst::createTruncOrBitCast(
3265 CastOp->getOperand(0), I.getType(),
3266 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003267 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003268 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003269 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003270 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003271 return BinaryOperator::createAnd(NewCast, C3);
3272 } else if (CastOp->getOpcode() == Instruction::Or) {
3273 // Change: and (cast (or X, C1) to T), C2
3274 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003275 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003276 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3277 return ReplaceInstUsesWith(I, AndRHS);
3278 }
3279 }
Chris Lattner33217db2003-07-23 19:36:21 +00003280 }
Chris Lattner183b3362004-04-09 19:05:30 +00003281
3282 // Try to fold constant and into select arguments.
3283 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003284 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003285 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003286 if (isa<PHINode>(Op0))
3287 if (Instruction *NV = FoldOpIntoPhi(I))
3288 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003289 }
3290
Chris Lattnerbb74e222003-03-10 23:06:50 +00003291 Value *Op0NotVal = dyn_castNotVal(Op0);
3292 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003293
Chris Lattner023a4832004-06-18 06:07:51 +00003294 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3295 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3296
Misha Brukman9c003d82004-07-30 12:50:08 +00003297 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003298 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003299 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3300 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003301 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003302 return BinaryOperator::createNot(Or);
3303 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003304
3305 {
3306 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003307 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3308 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3309 return ReplaceInstUsesWith(I, Op1);
3310 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3311 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3312 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003313
3314 if (Op0->hasOneUse() &&
3315 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3316 if (A == Op1) { // (A^B)&A -> A&(A^B)
3317 I.swapOperands(); // Simplify below
3318 std::swap(Op0, Op1);
3319 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3320 cast<BinaryOperator>(Op0)->swapOperands();
3321 I.swapOperands(); // Simplify below
3322 std::swap(Op0, Op1);
3323 }
3324 }
3325 if (Op1->hasOneUse() &&
3326 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3327 if (B == Op0) { // B&(A^B) -> B&(B^A)
3328 cast<BinaryOperator>(Op1)->swapOperands();
3329 std::swap(A, B);
3330 }
3331 if (A == Op0) { // A&(A^B) -> A & ~B
3332 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3333 InsertNewInstBefore(NotB, I);
3334 return BinaryOperator::createAnd(A, NotB);
3335 }
3336 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003337 }
3338
Reid Spencer266e42b2006-12-23 06:05:41 +00003339 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3340 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3341 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003342 return R;
3343
Chris Lattner623826c2004-09-28 21:48:02 +00003344 Value *LHSVal, *RHSVal;
3345 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003346 ICmpInst::Predicate LHSCC, RHSCC;
3347 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3348 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3349 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3350 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3351 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3352 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3353 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3354 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003355 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003356 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3357 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3358 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3359 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003360 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003361 std::swap(LHS, RHS);
3362 std::swap(LHSCst, RHSCst);
3363 std::swap(LHSCC, RHSCC);
3364 }
3365
Reid Spencer266e42b2006-12-23 06:05:41 +00003366 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003367 // comparing a value against two constants and and'ing the result
3368 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003369 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3370 // (from the FoldICmpLogical check above), that the two constants
3371 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003372 assert(LHSCst != RHSCst && "Compares not folded above?");
3373
3374 switch (LHSCC) {
3375 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003376 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003377 switch (RHSCC) {
3378 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003379 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3380 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3381 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003382 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003383 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3384 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3385 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003386 return ReplaceInstUsesWith(I, LHS);
3387 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003388 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003389 switch (RHSCC) {
3390 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003391 case ICmpInst::ICMP_ULT:
3392 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3393 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3394 break; // (X != 13 & X u< 15) -> no change
3395 case ICmpInst::ICMP_SLT:
3396 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3397 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3398 break; // (X != 13 & X s< 15) -> no change
3399 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3400 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3401 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003402 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003403 case ICmpInst::ICMP_NE:
3404 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003405 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3406 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3407 LHSVal->getName()+".off");
3408 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003409 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3410 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003411 }
3412 break; // (X != 13 & X != 15) -> no change
3413 }
3414 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003415 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003416 switch (RHSCC) {
3417 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003418 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3419 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003420 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003421 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3422 break;
3423 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3424 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003425 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003426 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3427 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003428 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003429 break;
3430 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003431 switch (RHSCC) {
3432 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003433 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3434 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003436 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3437 break;
3438 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3439 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003440 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003441 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3442 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003443 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003444 break;
3445 case ICmpInst::ICMP_UGT:
3446 switch (RHSCC) {
3447 default: assert(0 && "Unknown integer condition code!");
3448 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3449 return ReplaceInstUsesWith(I, LHS);
3450 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3451 return ReplaceInstUsesWith(I, RHS);
3452 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3453 break;
3454 case ICmpInst::ICMP_NE:
3455 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3456 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3457 break; // (X u> 13 & X != 15) -> no change
3458 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3459 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3460 true, I);
3461 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3462 break;
3463 }
3464 break;
3465 case ICmpInst::ICMP_SGT:
3466 switch (RHSCC) {
3467 default: assert(0 && "Unknown integer condition code!");
3468 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3469 return ReplaceInstUsesWith(I, LHS);
3470 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3471 return ReplaceInstUsesWith(I, RHS);
3472 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3473 break;
3474 case ICmpInst::ICMP_NE:
3475 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3476 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3477 break; // (X s> 13 & X != 15) -> no change
3478 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3479 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3480 true, I);
3481 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3482 break;
3483 }
3484 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003485 }
3486 }
3487 }
3488
Chris Lattner3af10532006-05-05 06:39:07 +00003489 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003490 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3491 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3492 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3493 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003494 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003495 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003496 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3497 I.getType(), TD) &&
3498 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3499 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003500 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3501 Op1C->getOperand(0),
3502 I.getName());
3503 InsertNewInstBefore(NewOp, I);
3504 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3505 }
Chris Lattner3af10532006-05-05 06:39:07 +00003506 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003507
3508 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003509 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3510 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3511 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003512 SI0->getOperand(1) == SI1->getOperand(1) &&
3513 (SI0->hasOneUse() || SI1->hasOneUse())) {
3514 Instruction *NewOp =
3515 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3516 SI1->getOperand(0),
3517 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003518 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3519 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003520 }
Chris Lattner3af10532006-05-05 06:39:07 +00003521 }
3522
Chris Lattner113f4f42002-06-25 16:13:24 +00003523 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003524}
3525
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003526/// CollectBSwapParts - Look to see if the specified value defines a single byte
3527/// in the result. If it does, and if the specified byte hasn't been filled in
3528/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003529static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003530 Instruction *I = dyn_cast<Instruction>(V);
3531 if (I == 0) return true;
3532
3533 // If this is an or instruction, it is an inner node of the bswap.
3534 if (I->getOpcode() == Instruction::Or)
3535 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3536 CollectBSwapParts(I->getOperand(1), ByteValues);
3537
3538 // If this is a shift by a constant int, and it is "24", then its operand
3539 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003540 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003541 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003542 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003543 8*(ByteValues.size()-1))
3544 return true;
3545
3546 unsigned DestNo;
3547 if (I->getOpcode() == Instruction::Shl) {
3548 // X << 24 defines the top byte with the lowest of the input bytes.
3549 DestNo = ByteValues.size()-1;
3550 } else {
3551 // X >>u 24 defines the low byte with the highest of the input bytes.
3552 DestNo = 0;
3553 }
3554
3555 // If the destination byte value is already defined, the values are or'd
3556 // together, which isn't a bswap (unless it's an or of the same bits).
3557 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3558 return true;
3559 ByteValues[DestNo] = I->getOperand(0);
3560 return false;
3561 }
3562
3563 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3564 // don't have this.
3565 Value *Shift = 0, *ShiftLHS = 0;
3566 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3567 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3568 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3569 return true;
3570 Instruction *SI = cast<Instruction>(Shift);
3571
3572 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003573 if (ShiftAmt->getZExtValue() & 7 ||
3574 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003575 return true;
3576
3577 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3578 unsigned DestByte;
3579 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003580 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003581 break;
3582 // Unknown mask for bswap.
3583 if (DestByte == ByteValues.size()) return true;
3584
Reid Spencere0fc4df2006-10-20 07:07:24 +00003585 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003586 unsigned SrcByte;
3587 if (SI->getOpcode() == Instruction::Shl)
3588 SrcByte = DestByte - ShiftBytes;
3589 else
3590 SrcByte = DestByte + ShiftBytes;
3591
3592 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3593 if (SrcByte != ByteValues.size()-DestByte-1)
3594 return true;
3595
3596 // If the destination byte value is already defined, the values are or'd
3597 // together, which isn't a bswap (unless it's an or of the same bits).
3598 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3599 return true;
3600 ByteValues[DestByte] = SI->getOperand(0);
3601 return false;
3602}
3603
3604/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3605/// If so, insert the new bswap intrinsic and return it.
3606Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003607 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003608 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003609 return 0;
3610
3611 /// ByteValues - For each byte of the result, we keep track of which value
3612 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003613 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003614 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003615
3616 // Try to find all the pieces corresponding to the bswap.
3617 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3618 CollectBSwapParts(I.getOperand(1), ByteValues))
3619 return 0;
3620
3621 // Check to see if all of the bytes come from the same value.
3622 Value *V = ByteValues[0];
3623 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3624
3625 // Check to make sure that all of the bytes come from the same value.
3626 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3627 if (ByteValues[i] != V)
3628 return 0;
3629
3630 // If they do then *success* we can turn this into a bswap. Figure out what
3631 // bswap to make it into.
3632 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003633 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003634 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003635 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003636 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003637 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003638 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003639 FnName = "llvm.bswap.i64";
3640 else
3641 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003642 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003643 return new CallInst(F, V);
3644}
3645
3646
Chris Lattner113f4f42002-06-25 16:13:24 +00003647Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003648 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003650
Chris Lattner3a8248f2007-03-24 23:56:43 +00003651 if (isa<UndefValue>(Op1)) // X | undef -> -1
3652 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003653
Chris Lattner5b2edb12006-02-12 08:02:11 +00003654 // or X, X = X
3655 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003656 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003657
Chris Lattner5b2edb12006-02-12 08:02:11 +00003658 // See if we can simplify any instructions used by the instruction whose sole
3659 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003660 if (!isa<VectorType>(I.getType())) {
3661 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3662 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3663 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3664 KnownZero, KnownOne))
3665 return &I;
3666 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003667
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003668 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003669 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003670 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003671 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3672 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003673 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003674 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003675 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003676 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3677 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003678
Chris Lattnerd4252a72004-07-30 07:50:03 +00003679 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3680 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003681 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003682 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003683 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003684 return BinaryOperator::createXor(Or,
3685 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003686 }
Chris Lattner183b3362004-04-09 19:05:30 +00003687
3688 // Try to fold constant and into select arguments.
3689 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003690 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003691 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003692 if (isa<PHINode>(Op0))
3693 if (Instruction *NV = FoldOpIntoPhi(I))
3694 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003695 }
3696
Chris Lattner330628a2006-01-06 17:59:59 +00003697 Value *A = 0, *B = 0;
3698 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003699
3700 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3701 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3702 return ReplaceInstUsesWith(I, Op1);
3703 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3704 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3705 return ReplaceInstUsesWith(I, Op0);
3706
Chris Lattnerb7845d62006-07-10 20:25:24 +00003707 // (A | B) | C and A | (B | C) -> bswap if possible.
3708 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003709 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003710 match(Op1, m_Or(m_Value(), m_Value())) ||
3711 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3712 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003713 if (Instruction *BSwap = MatchBSwap(I))
3714 return BSwap;
3715 }
3716
Chris Lattnerb62f5082005-05-09 04:58:36 +00003717 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3718 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003719 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003720 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3721 InsertNewInstBefore(NOr, I);
3722 NOr->takeName(Op0);
3723 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003724 }
3725
3726 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3727 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003728 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003729 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3730 InsertNewInstBefore(NOr, I);
3731 NOr->takeName(Op0);
3732 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003733 }
3734
Chris Lattner15212982005-09-18 03:42:07 +00003735 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003736 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003737 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3738
3739 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3740 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3741
3742
Chris Lattner01f56c62005-09-18 06:02:59 +00003743 // If we have: ((V + N) & C1) | (V & C2)
3744 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3745 // replace with V+N.
3746 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003747 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003748 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003749 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3750 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003751 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003752 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003753 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003754 return ReplaceInstUsesWith(I, A);
3755 }
3756 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003757 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003758 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3759 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003760 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003761 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003762 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003763 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003764 }
3765 }
3766 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003767
3768 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003769 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3770 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3771 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003772 SI0->getOperand(1) == SI1->getOperand(1) &&
3773 (SI0->hasOneUse() || SI1->hasOneUse())) {
3774 Instruction *NewOp =
3775 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3776 SI1->getOperand(0),
3777 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003778 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3779 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003780 }
3781 }
Chris Lattner812aab72003-08-12 19:11:07 +00003782
Chris Lattnerd4252a72004-07-30 07:50:03 +00003783 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3784 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003785 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003786 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003787 } else {
3788 A = 0;
3789 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003790 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003791 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3792 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003793 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003794 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003795
Misha Brukman9c003d82004-07-30 12:50:08 +00003796 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003797 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3798 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3799 I.getName()+".demorgan"), I);
3800 return BinaryOperator::createNot(And);
3801 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003802 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003803
Reid Spencer266e42b2006-12-23 06:05:41 +00003804 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3805 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3806 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003807 return R;
3808
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003809 Value *LHSVal, *RHSVal;
3810 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003811 ICmpInst::Predicate LHSCC, RHSCC;
3812 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3813 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3814 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3815 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3816 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3817 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3818 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3819 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003820 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003821 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3822 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3823 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3824 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003825 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003826 std::swap(LHS, RHS);
3827 std::swap(LHSCst, RHSCst);
3828 std::swap(LHSCC, RHSCC);
3829 }
3830
Reid Spencer266e42b2006-12-23 06:05:41 +00003831 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003832 // comparing a value against two constants and or'ing the result
3833 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003834 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3835 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003836 // equal.
3837 assert(LHSCst != RHSCst && "Compares not folded above?");
3838
3839 switch (LHSCC) {
3840 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003841 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003842 switch (RHSCC) {
3843 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003844 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003845 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3846 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3847 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3848 LHSVal->getName()+".off");
3849 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003850 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003851 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003852 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003853 break; // (X == 13 | X == 15) -> no change
3854 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3855 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003856 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003857 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3858 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3859 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003860 return ReplaceInstUsesWith(I, RHS);
3861 }
3862 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003863 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003864 switch (RHSCC) {
3865 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003866 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3867 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3868 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003869 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003870 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3871 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3872 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003873 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003874 }
3875 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003876 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003877 switch (RHSCC) {
3878 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003879 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003880 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003881 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3882 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3883 false, I);
3884 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3885 break;
3886 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3887 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003888 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003889 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3890 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003891 }
3892 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003893 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003894 switch (RHSCC) {
3895 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003896 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3897 break;
3898 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3899 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3900 false, I);
3901 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3904 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3905 return ReplaceInstUsesWith(I, RHS);
3906 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3907 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003908 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003909 break;
3910 case ICmpInst::ICMP_UGT:
3911 switch (RHSCC) {
3912 default: assert(0 && "Unknown integer condition code!");
3913 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3914 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3915 return ReplaceInstUsesWith(I, LHS);
3916 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3919 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003920 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003921 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3922 break;
3923 }
3924 break;
3925 case ICmpInst::ICMP_SGT:
3926 switch (RHSCC) {
3927 default: assert(0 && "Unknown integer condition code!");
3928 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3929 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3930 return ReplaceInstUsesWith(I, LHS);
3931 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3932 break;
3933 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3934 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003935 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003936 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3937 break;
3938 }
3939 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003940 }
3941 }
3942 }
Chris Lattner3af10532006-05-05 06:39:07 +00003943
3944 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003945 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003946 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003947 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3948 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003949 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003950 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003951 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3952 I.getType(), TD) &&
3953 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3954 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003955 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3956 Op1C->getOperand(0),
3957 I.getName());
3958 InsertNewInstBefore(NewOp, I);
3959 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3960 }
Chris Lattner3af10532006-05-05 06:39:07 +00003961 }
Chris Lattner3af10532006-05-05 06:39:07 +00003962
Chris Lattner15212982005-09-18 03:42:07 +00003963
Chris Lattner113f4f42002-06-25 16:13:24 +00003964 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003965}
3966
Chris Lattnerc2076352004-02-16 01:20:27 +00003967// XorSelf - Implements: X ^ X --> 0
3968struct XorSelf {
3969 Value *RHS;
3970 XorSelf(Value *rhs) : RHS(rhs) {}
3971 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3972 Instruction *apply(BinaryOperator &Xor) const {
3973 return &Xor;
3974 }
3975};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003976
3977
Chris Lattner113f4f42002-06-25 16:13:24 +00003978Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003979 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003981
Chris Lattner81a7a232004-10-16 18:11:37 +00003982 if (isa<UndefValue>(Op1))
3983 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3984
Chris Lattnerc2076352004-02-16 01:20:27 +00003985 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3986 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3987 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003989 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003990
3991 // See if we can simplify any instructions used by the instruction whose sole
3992 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003993 if (!isa<VectorType>(I.getType())) {
3994 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3995 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3996 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3997 KnownZero, KnownOne))
3998 return &I;
3999 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004000
Zhou Sheng75b871f2007-01-11 12:24:14 +00004001 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004002 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4003 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004004 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004005 return new ICmpInst(ICI->getInversePredicate(),
4006 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004007
Reid Spencer266e42b2006-12-23 06:05:41 +00004008 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004009 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004010 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4011 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004012 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4013 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004014 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004015 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004016 }
Chris Lattner023a4832004-06-18 06:07:51 +00004017
4018 // ~(~X & Y) --> (X | ~Y)
4019 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4020 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4021 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4022 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004023 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004024 Op0I->getOperand(1)->getName()+".not");
4025 InsertNewInstBefore(NotY, I);
4026 return BinaryOperator::createOr(Op0NotVal, NotY);
4027 }
4028 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004029
Chris Lattner97638592003-07-23 21:37:07 +00004030 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004031 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004032 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004033 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004034 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4035 return BinaryOperator::createSub(
4036 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004037 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004038 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004039 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004040 } else if (Op0I->getOpcode() == Instruction::Or) {
4041 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004042 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004043 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4044 // Anything in both C1 and C2 is known to be zero, remove it from
4045 // NewRHS.
4046 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4047 NewRHS = ConstantExpr::getAnd(NewRHS,
4048 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004049 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004050 I.setOperand(0, Op0I->getOperand(0));
4051 I.setOperand(1, NewRHS);
4052 return &I;
4053 }
Chris Lattner97638592003-07-23 21:37:07 +00004054 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004055 }
Chris Lattner183b3362004-04-09 19:05:30 +00004056
4057 // Try to fold constant and into select arguments.
4058 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004059 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004060 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004061 if (isa<PHINode>(Op0))
4062 if (Instruction *NV = FoldOpIntoPhi(I))
4063 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004064 }
4065
Chris Lattnerbb74e222003-03-10 23:06:50 +00004066 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004067 if (X == Op1)
4068 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004069 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004070
Chris Lattnerbb74e222003-03-10 23:06:50 +00004071 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004072 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004073 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004074
Chris Lattner07418422007-03-18 22:51:34 +00004075
4076 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4077 if (Op1I) {
4078 Value *A, *B;
4079 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4080 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004081 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004082 I.swapOperands();
4083 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004084 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004085 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004086 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004087 }
Chris Lattner07418422007-03-18 22:51:34 +00004088 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4089 if (Op0 == A) // A^(A^B) == B
4090 return ReplaceInstUsesWith(I, B);
4091 else if (Op0 == B) // A^(B^A) == B
4092 return ReplaceInstUsesWith(I, A);
4093 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4094 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004095 Op1I->swapOperands();
Chris Lattner07418422007-03-18 22:51:34 +00004096 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004097 I.swapOperands(); // Simplified below.
4098 std::swap(Op0, Op1);
4099 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004100 }
Chris Lattner07418422007-03-18 22:51:34 +00004101 }
4102
4103 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4104 if (Op0I) {
4105 Value *A, *B;
4106 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4107 if (A == Op1) // (B|A)^B == (A|B)^B
4108 std::swap(A, B);
4109 if (B == Op1) { // (A|B)^B == A & ~B
4110 Instruction *NotB =
4111 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4112 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004113 }
Chris Lattner07418422007-03-18 22:51:34 +00004114 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4115 if (Op1 == A) // (A^B)^A == B
4116 return ReplaceInstUsesWith(I, B);
4117 else if (Op1 == B) // (B^A)^A == B
4118 return ReplaceInstUsesWith(I, A);
4119 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4120 if (A == Op1) // (A&B)^A -> (B&A)^A
4121 std::swap(A, B);
4122 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004123 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004124 Instruction *N =
4125 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004126 return BinaryOperator::createAnd(N, Op1);
4127 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004128 }
Chris Lattner07418422007-03-18 22:51:34 +00004129 }
4130
4131 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4132 if (Op0I && Op1I && Op0I->isShift() &&
4133 Op0I->getOpcode() == Op1I->getOpcode() &&
4134 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4135 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4136 Instruction *NewOp =
4137 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4138 Op1I->getOperand(0),
4139 Op0I->getName()), I);
4140 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4141 Op1I->getOperand(1));
4142 }
4143
4144 if (Op0I && Op1I) {
4145 Value *A, *B, *C, *D;
4146 // (A & B)^(A | B) -> A ^ B
4147 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4148 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4149 if ((A == C && B == D) || (A == D && B == C))
4150 return BinaryOperator::createXor(A, B);
4151 }
4152 // (A | B)^(A & B) -> A ^ B
4153 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4154 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4155 if ((A == C && B == D) || (A == D && B == C))
4156 return BinaryOperator::createXor(A, B);
4157 }
4158
4159 // (A & B)^(C & D)
4160 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4161 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4162 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4163 // (X & Y)^(X & Y) -> (Y^Z) & X
4164 Value *X = 0, *Y = 0, *Z = 0;
4165 if (A == C)
4166 X = A, Y = B, Z = D;
4167 else if (A == D)
4168 X = A, Y = B, Z = C;
4169 else if (B == C)
4170 X = B, Y = A, Z = D;
4171 else if (B == D)
4172 X = B, Y = A, Z = C;
4173
4174 if (X) {
4175 Instruction *NewOp =
4176 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4177 return BinaryOperator::createAnd(NewOp, X);
4178 }
4179 }
4180 }
4181
Reid Spencer266e42b2006-12-23 06:05:41 +00004182 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4183 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4184 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004185 return R;
4186
Chris Lattner3af10532006-05-05 06:39:07 +00004187 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004188 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004189 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004190 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4191 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004192 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004193 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004194 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4195 I.getType(), TD) &&
4196 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4197 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004198 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4199 Op1C->getOperand(0),
4200 I.getName());
4201 InsertNewInstBefore(NewOp, I);
4202 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4203 }
Chris Lattner3af10532006-05-05 06:39:07 +00004204 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004205
Chris Lattner113f4f42002-06-25 16:13:24 +00004206 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004207}
4208
Chris Lattner6862fbd2004-09-29 17:40:11 +00004209/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4210/// overflowed for this type.
4211static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004212 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004213 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4214
Reid Spencerf4071162007-03-21 23:19:50 +00004215 if (IsSigned)
4216 if (In2->getValue().isNegative())
4217 return Result->getValue().sgt(In1->getValue());
4218 else
4219 return Result->getValue().slt(In1->getValue());
4220 else
4221 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004222}
4223
Chris Lattner0798af32005-01-13 20:14:25 +00004224/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4225/// code necessary to compute the offset from the base pointer (without adding
4226/// in the base pointer). Return the result as a signed integer of intptr size.
4227static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4228 TargetData &TD = IC.getTargetData();
4229 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004230 const Type *IntPtrTy = TD.getIntPtrType();
4231 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004232
4233 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004234 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004235
Chris Lattner0798af32005-01-13 20:14:25 +00004236 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4237 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004238 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004239 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004240 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4241 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004242 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004243 Scale = ConstantExpr::getMul(OpC, Scale);
4244 if (Constant *RC = dyn_cast<Constant>(Result))
4245 Result = ConstantExpr::getAdd(RC, Scale);
4246 else {
4247 // Emit an add instruction.
4248 Result = IC.InsertNewInstBefore(
4249 BinaryOperator::createAdd(Result, Scale,
4250 GEP->getName()+".offs"), I);
4251 }
4252 }
4253 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004254 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004255 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004256 Op->getName()+".c"), I);
4257 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004258 // We'll let instcombine(mul) convert this to a shl if possible.
4259 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4260 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004261
4262 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004263 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004264 GEP->getName()+".offs"), I);
4265 }
4266 }
4267 return Result;
4268}
4269
Reid Spencer266e42b2006-12-23 06:05:41 +00004270/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004271/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004272Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4273 ICmpInst::Predicate Cond,
4274 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004275 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004276
4277 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4278 if (isa<PointerType>(CI->getOperand(0)->getType()))
4279 RHS = CI->getOperand(0);
4280
Chris Lattner0798af32005-01-13 20:14:25 +00004281 Value *PtrBase = GEPLHS->getOperand(0);
4282 if (PtrBase == RHS) {
4283 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004284 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4285 // each index is zero or not.
4286 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004287 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004288 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4289 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004290 bool EmitIt = true;
4291 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4292 if (isa<UndefValue>(C)) // undef index -> undef.
4293 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4294 if (C->isNullValue())
4295 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004296 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4297 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004298 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004299 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004300 ConstantInt::get(Type::Int1Ty,
4301 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004302 }
4303
4304 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004305 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004306 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004307 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4308 if (InVal == 0)
4309 InVal = Comp;
4310 else {
4311 InVal = InsertNewInstBefore(InVal, I);
4312 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004313 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004314 InVal = BinaryOperator::createOr(InVal, Comp);
4315 else // True if all are equal
4316 InVal = BinaryOperator::createAnd(InVal, Comp);
4317 }
4318 }
4319 }
4320
4321 if (InVal)
4322 return InVal;
4323 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004324 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004325 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4326 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004327 }
Chris Lattner0798af32005-01-13 20:14:25 +00004328
Reid Spencer266e42b2006-12-23 06:05:41 +00004329 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004330 // the result to fold to a constant!
4331 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4332 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4333 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004334 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4335 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004336 }
4337 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004338 // If the base pointers are different, but the indices are the same, just
4339 // compare the base pointer.
4340 if (PtrBase != GEPRHS->getOperand(0)) {
4341 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004342 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004343 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004344 if (IndicesTheSame)
4345 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4346 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4347 IndicesTheSame = false;
4348 break;
4349 }
4350
4351 // If all indices are the same, just compare the base pointers.
4352 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004353 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4354 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004355
4356 // Otherwise, the base pointers are different and the indices are
4357 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004358 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004359 }
Chris Lattner0798af32005-01-13 20:14:25 +00004360
Chris Lattner81e84172005-01-13 22:25:21 +00004361 // If one of the GEPs has all zero indices, recurse.
4362 bool AllZeros = true;
4363 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4364 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4365 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4366 AllZeros = false;
4367 break;
4368 }
4369 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004370 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4371 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004372
4373 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004374 AllZeros = true;
4375 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4376 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4377 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4378 AllZeros = false;
4379 break;
4380 }
4381 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004382 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004383
Chris Lattner4fa89822005-01-14 00:20:05 +00004384 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4385 // If the GEPs only differ by one index, compare it.
4386 unsigned NumDifferences = 0; // Keep track of # differences.
4387 unsigned DiffOperand = 0; // The operand that differs.
4388 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4389 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004390 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4391 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004392 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004393 NumDifferences = 2;
4394 break;
4395 } else {
4396 if (NumDifferences++) break;
4397 DiffOperand = i;
4398 }
4399 }
4400
4401 if (NumDifferences == 0) // SAME GEP?
4402 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004403 ConstantInt::get(Type::Int1Ty,
4404 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004405 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004406 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4407 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004408 // Make sure we do a signed comparison here.
4409 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004410 }
4411 }
4412
Reid Spencer266e42b2006-12-23 06:05:41 +00004413 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004414 // the result to fold to a constant!
4415 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4416 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4417 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4418 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4419 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004420 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004421 }
4422 }
4423 return 0;
4424}
4425
Reid Spencer266e42b2006-12-23 06:05:41 +00004426Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4427 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004428 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004429
Chris Lattner6ee923f2007-01-14 19:42:17 +00004430 // Fold trivial predicates.
4431 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4432 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4433 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4434 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4435
4436 // Simplify 'fcmp pred X, X'
4437 if (Op0 == Op1) {
4438 switch (I.getPredicate()) {
4439 default: assert(0 && "Unknown predicate!");
4440 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4441 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4442 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4443 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4444 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4445 case FCmpInst::FCMP_OLT: // True if ordered and less than
4446 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4447 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4448
4449 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4450 case FCmpInst::FCMP_ULT: // True if unordered or less than
4451 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4452 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4453 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4454 I.setPredicate(FCmpInst::FCMP_UNO);
4455 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4456 return &I;
4457
4458 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4459 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4460 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4461 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4462 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4463 I.setPredicate(FCmpInst::FCMP_ORD);
4464 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4465 return &I;
4466 }
4467 }
4468
Reid Spencer266e42b2006-12-23 06:05:41 +00004469 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004470 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004471
Reid Spencer266e42b2006-12-23 06:05:41 +00004472 // Handle fcmp with constant RHS
4473 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4474 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4475 switch (LHSI->getOpcode()) {
4476 case Instruction::PHI:
4477 if (Instruction *NV = FoldOpIntoPhi(I))
4478 return NV;
4479 break;
4480 case Instruction::Select:
4481 // If either operand of the select is a constant, we can fold the
4482 // comparison into the select arms, which will cause one to be
4483 // constant folded and the select turned into a bitwise or.
4484 Value *Op1 = 0, *Op2 = 0;
4485 if (LHSI->hasOneUse()) {
4486 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4487 // Fold the known value into the constant operand.
4488 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4489 // Insert a new FCmp of the other select operand.
4490 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4491 LHSI->getOperand(2), RHSC,
4492 I.getName()), I);
4493 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4494 // Fold the known value into the constant operand.
4495 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4496 // Insert a new FCmp of the other select operand.
4497 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4498 LHSI->getOperand(1), RHSC,
4499 I.getName()), I);
4500 }
4501 }
4502
4503 if (Op1)
4504 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4505 break;
4506 }
4507 }
4508
4509 return Changed ? &I : 0;
4510}
4511
4512Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4513 bool Changed = SimplifyCompare(I);
4514 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4515 const Type *Ty = Op0->getType();
4516
4517 // icmp X, X
4518 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004519 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4520 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004521
4522 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004523 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004524
4525 // icmp of GlobalValues can never equal each other as long as they aren't
4526 // external weak linkage type.
4527 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4528 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4529 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004530 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4531 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004532
4533 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004534 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004535 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4536 isa<ConstantPointerNull>(Op0)) &&
4537 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004538 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004539 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4540 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004541
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004543 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004544 switch (I.getPredicate()) {
4545 default: assert(0 && "Invalid icmp instruction!");
4546 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004547 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004548 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004549 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004550 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004551 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004552 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004553
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 case ICmpInst::ICMP_UGT:
4555 case ICmpInst::ICMP_SGT:
4556 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004557 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 case ICmpInst::ICMP_ULT:
4559 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004560 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4561 InsertNewInstBefore(Not, I);
4562 return BinaryOperator::createAnd(Not, Op1);
4563 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004564 case ICmpInst::ICMP_UGE:
4565 case ICmpInst::ICMP_SGE:
4566 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004567 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004568 case ICmpInst::ICMP_ULE:
4569 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004570 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4571 InsertNewInstBefore(Not, I);
4572 return BinaryOperator::createOr(Not, Op1);
4573 }
4574 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004575 }
4576
Chris Lattner2dd01742004-06-09 04:24:29 +00004577 // See if we are doing a comparison between a constant and an instruction that
4578 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004579 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004580 switch (I.getPredicate()) {
4581 default: break;
4582 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4583 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004584 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004585 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4586 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4587 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4588 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4589 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004590
Reid Spencer266e42b2006-12-23 06:05:41 +00004591 case ICmpInst::ICMP_SLT:
4592 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004593 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004594 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4595 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4596 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4597 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4598 break;
4599
4600 case ICmpInst::ICMP_UGT:
4601 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004602 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004603 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4604 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4605 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4606 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4607 break;
4608
4609 case ICmpInst::ICMP_SGT:
4610 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004611 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004612 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4613 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4614 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4615 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4616 break;
4617
4618 case ICmpInst::ICMP_ULE:
4619 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004620 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004621 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4622 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4623 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4624 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4625 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004626
Reid Spencer266e42b2006-12-23 06:05:41 +00004627 case ICmpInst::ICMP_SLE:
4628 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004629 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004630 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4631 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4632 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4633 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4634 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004635
Reid Spencer266e42b2006-12-23 06:05:41 +00004636 case ICmpInst::ICMP_UGE:
4637 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004638 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004639 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4640 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4641 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4642 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4643 break;
4644
4645 case ICmpInst::ICMP_SGE:
4646 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004647 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004648 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4649 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4650 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4651 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4652 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004653 }
4654
Reid Spencer266e42b2006-12-23 06:05:41 +00004655 // If we still have a icmp le or icmp ge instruction, turn it into the
4656 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004657 // already been handled above, this requires little checking.
4658 //
Reid Spencer624766f2007-03-25 19:55:33 +00004659 switch (I.getPredicate()) {
4660 default: break;
4661 case ICmpInst::ICMP_ULE:
4662 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4663 case ICmpInst::ICMP_SLE:
4664 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4665 case ICmpInst::ICMP_UGE:
4666 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4667 case ICmpInst::ICMP_SGE:
4668 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4669 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004670
4671 // See if we can fold the comparison based on bits known to be zero or one
4672 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004673 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4674 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4675 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004676 KnownZero, KnownOne, 0))
4677 return &I;
4678
4679 // Given the known and unknown bits, compute a range that the LHS could be
4680 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004681 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004682 // Compute the Min, Max and RHS values based on the known bits. For the
4683 // EQ and NE we use unsigned values.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004684 APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004685 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004686 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4687 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004688 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004689 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4690 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004691 }
4692 switch (I.getPredicate()) { // LE/GE have been folded already.
4693 default: assert(0 && "Unknown icmp opcode!");
4694 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004695 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004696 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004697 break;
4698 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004699 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004700 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004701 break;
4702 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004703 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004704 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004705 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004706 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004707 break;
4708 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004709 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004710 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004711 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004712 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004713 break;
4714 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004715 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004716 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004717 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004718 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004719 break;
4720 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004721 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004722 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004723 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004724 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004725 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004726 }
4727 }
4728
Reid Spencer266e42b2006-12-23 06:05:41 +00004729 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004730 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004731 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004732 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004733 switch (LHSI->getOpcode()) {
4734 case Instruction::And:
4735 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4736 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004737 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4738
Reid Spencer266e42b2006-12-23 06:05:41 +00004739 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004740 // and/compare to be the input width without changing the value
4741 // produced, eliminating a cast.
4742 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4743 // We can do this transformation if either the AND constant does not
4744 // have its sign bit set or if it is an equality comparison.
4745 // Extending a relational comparison when we're checking the sign
4746 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004747 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004748 (I.isEquality() || AndCST->getValue().isPositive() &&
4749 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004750 ConstantInt *NewCST;
4751 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004752 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4753 uint32_t BitWidth = cast<IntegerType>(
4754 Cast->getOperand(0)->getType())->getBitWidth();
4755 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4756 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00004757 Instruction *NewAnd =
4758 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4759 LHSI->getName());
4760 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004761 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004762 }
4763 }
4764
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004765 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4766 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4767 // happens a LOT in code produced by the C front-end, for bitfield
4768 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004769 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4770 if (Shift && !Shift->isShift())
4771 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004772
Reid Spencere0fc4df2006-10-20 07:07:24 +00004773 ConstantInt *ShAmt;
4774 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004775 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4776 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004777
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004778 // We can fold this as long as we can't shift unknown bits
4779 // into the mask. This can only happen with signed shift
4780 // rights, as they sign-extend.
4781 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004782 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004783 if (!CanFold) {
4784 // To test for the bad case of the signed shr, see if any
4785 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004786 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004787 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4788
Reid Spencer2341c222007-02-02 02:16:23 +00004789 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004790 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004791 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4792 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004793 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4794 CanFold = true;
4795 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004796
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004797 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004798 Constant *NewCst;
4799 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004800 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004801 else
4802 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004803
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004804 // Check to see if we are shifting out any of the bits being
4805 // compared.
4806 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4807 // If we shifted bits out, the fold is not going to work out.
4808 // As a special case, check to see if this means that the
4809 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004810 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004811 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004812 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004813 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004814 } else {
4815 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004816 Constant *NewAndCST;
4817 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004818 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004819 else
4820 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4821 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004822 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004823 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004824 AddUsesToWorkList(I);
4825 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004826 }
4827 }
Chris Lattner35167c32004-06-09 07:59:58 +00004828 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004829
4830 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4831 // preferable because it allows the C<<Y expression to be hoisted out
4832 // of a loop if Y is invariant and X is not.
4833 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004834 I.isEquality() && !Shift->isArithmeticShift() &&
4835 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004836 // Compute C << Y.
4837 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004838 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004839 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004840 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004841 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004842 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004843 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004844 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004845 }
4846 InsertNewInstBefore(cast<Instruction>(NS), I);
4847
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004848 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004849 Instruction *NewAnd = BinaryOperator::createAnd(
4850 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004851 InsertNewInstBefore(NewAnd, I);
4852
4853 I.setOperand(0, NewAnd);
4854 return &I;
4855 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004856 }
4857 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004858
Reid Spencer266e42b2006-12-23 06:05:41 +00004859 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004860 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004861 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004862 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4863
4864 // Check that the shift amount is in range. If not, don't perform
4865 // undefined shifts. When the shift is visited it will be
4866 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004867 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004868 break;
4869
Chris Lattner272d5ca2004-09-28 18:22:15 +00004870 // If we are comparing against bits always shifted out, the
4871 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004872 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004873 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004874 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004875 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004876 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004877 return ReplaceInstUsesWith(I, Cst);
4878 }
4879
4880 if (LHSI->hasOneUse()) {
4881 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004882 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Reid Spencer52830322007-03-25 21:11:44 +00004883 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4884 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004885
Chris Lattner272d5ca2004-09-28 18:22:15 +00004886 Instruction *AndI =
4887 BinaryOperator::createAnd(LHSI->getOperand(0),
4888 Mask, LHSI->getName()+".mask");
4889 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004890 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004891 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004892 }
4893 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004894 }
4895 break;
4896
Reid Spencer266e42b2006-12-23 06:05:41 +00004897 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004898 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004899 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004900 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004901 // Check that the shift amount is in range. If not, don't perform
4902 // undefined shifts. When the shift is visited it will be
4903 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004904 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004905 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004906 break;
4907
Chris Lattner1023b872004-09-27 16:18:50 +00004908 // If we are comparing against bits always shifted out, the
4909 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004910 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004911 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004912 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4913 ShAmt);
4914 else
4915 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4916 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004917
Chris Lattner1023b872004-09-27 16:18:50 +00004918 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004919 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004920 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004921 return ReplaceInstUsesWith(I, Cst);
4922 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004923
Chris Lattner1023b872004-09-27 16:18:50 +00004924 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004925 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004926
Chris Lattner1023b872004-09-27 16:18:50 +00004927 // Otherwise strength reduce the shift into an and.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004928 APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
4929 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004930
Chris Lattner1023b872004-09-27 16:18:50 +00004931 Instruction *AndI =
4932 BinaryOperator::createAnd(LHSI->getOperand(0),
4933 Mask, LHSI->getName()+".mask");
4934 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004935 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004936 ConstantExpr::getShl(CI, ShAmt));
4937 }
Chris Lattner1023b872004-09-27 16:18:50 +00004938 }
4939 }
4940 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004941
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004942 case Instruction::SDiv:
4943 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004944 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004945 // Fold this div into the comparison, producing a range check.
4946 // Determine, based on the divide type, what the range is being
4947 // checked. If there is an overflow on the low or high side, remember
4948 // it, otherwise compute the range [low, hi) bounding the new value.
4949 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004950 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004951 // FIXME: If the operand types don't match the type of the divide
4952 // then don't attempt this transform. The code below doesn't have the
4953 // logic to deal with a signed divide and an unsigned compare (and
4954 // vice versa). This is because (x /s C1) <s C2 produces different
4955 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4956 // (x /u C1) <u C2. Simply casting the operands and result won't
4957 // work. :( The if statement below tests that condition and bails
4958 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004959 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4960 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004961 break;
Reid Spencerf4071162007-03-21 23:19:50 +00004962 if (DivRHS->isZero())
4963 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004964
4965 // Initialize the variables that will indicate the nature of the
4966 // range check.
4967 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004968 ConstantInt *LoBound = 0, *HiBound = 0;
4969
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004970 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4971 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4972 // C2 (CI). By solving for X we can turn this into a range check
4973 // instead of computing a divide.
4974 ConstantInt *Prod =
4975 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004976
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004977 // Determine if the product overflows by seeing if the product is
4978 // not equal to the divide. Make sure we do the same kind of divide
4979 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00004980 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4981 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004982
Reid Spencer266e42b2006-12-23 06:05:41 +00004983 // Get the ICmp opcode
4984 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004985
Reid Spencerf4071162007-03-21 23:19:50 +00004986 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004987 LoBound = Prod;
4988 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004989 HiOverflow = ProdOV ||
4990 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00004991 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004992 if (CI->isNullValue()) { // (X / pos) op 0
4993 // Can't overflow.
4994 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4995 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00004996 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004997 LoBound = Prod;
4998 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004999 HiOverflow = ProdOV ||
5000 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005001 } else { // (X / pos) op neg
5002 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5003 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00005004 cast<ConstantInt>(DivRHSH), true);
5005 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005006 HiOverflow = ProdOV;
5007 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005008 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005009 if (CI->isNullValue()) { // (X / neg) op 0
5010 LoBound = AddOne(DivRHS);
5011 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005012 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005013 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00005014 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005015 HiOverflow = LoOverflow = ProdOV;
5016 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00005017 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5018 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005019 HiBound = AddOne(Prod);
5020 } else { // (X / neg) op neg
5021 LoBound = Prod;
5022 LoOverflow = HiOverflow = ProdOV;
5023 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5024 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005025
Chris Lattnera92af962004-10-11 19:40:04 +00005026 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005027 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005028 }
5029
5030 if (LoBound) {
5031 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005032 switch (predicate) {
5033 default: assert(0 && "Unhandled icmp opcode!");
5034 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005035 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005036 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005037 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005038 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5039 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005040 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005041 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5042 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005043 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005044 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5045 true, I);
5046 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005047 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005048 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005049 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005050 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5051 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005052 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005053 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5054 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005055 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005056 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5057 false, I);
5058 case ICmpInst::ICMP_ULT:
5059 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005060 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005061 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005062 return new ICmpInst(predicate, X, LoBound);
5063 case ICmpInst::ICMP_UGT:
5064 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005065 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005066 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005067 if (predicate == ICmpInst::ICMP_UGT)
5068 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5069 else
5070 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005071 }
5072 }
5073 }
5074 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005075 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005076
Reid Spencer266e42b2006-12-23 06:05:41 +00005077 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005078 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005079 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005080
Reid Spencere0fc4df2006-10-20 07:07:24 +00005081 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5082 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005083 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5084 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005085 case Instruction::SRem:
5086 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005087 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005088 BO->hasOneUse()) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005089 APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5090 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005091 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5092 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005093 return new ICmpInst(I.getPredicate(), NewRem,
5094 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005095 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005096 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005097 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005098 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005099 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5100 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005101 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005102 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5103 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005104 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005105 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5106 // efficiently invertible, or if the add has just this one use.
5107 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005108
Chris Lattnerc992add2003-08-13 05:33:12 +00005109 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005110 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005111 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005112 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005113 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005114 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005115 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005116 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005117 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005118 }
5119 }
5120 break;
5121 case Instruction::Xor:
5122 // For the xor case, we can xor two constants together, eliminating
5123 // the explicit xor.
5124 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005125 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5126 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005127
5128 // FALLTHROUGH
5129 case Instruction::Sub:
5130 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005131 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005132 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5133 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005134 break;
5135
5136 case Instruction::Or:
5137 // If bits are being or'd in that are not present in the constant we
5138 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005139 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005140 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005141 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005142 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5143 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005144 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005145 break;
5146
5147 case Instruction::And:
5148 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005149 // If bits are being compared against that are and'd out, then the
5150 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005151 if (!ConstantExpr::getAnd(CI,
5152 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005153 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5154 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005155
Chris Lattner35167c32004-06-09 07:59:58 +00005156 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005157 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005158 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5159 ICmpInst::ICMP_NE, Op0,
5160 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005161
Reid Spencer266e42b2006-12-23 06:05:41 +00005162 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005163 if (isSignBit(BOC)) {
5164 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005165 Constant *Zero = Constant::getNullValue(X->getType());
5166 ICmpInst::Predicate pred = isICMP_NE ?
5167 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5168 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005169 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005170
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005171 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005172 if (CI->isNullValue() && isHighOnes(BOC)) {
5173 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005174 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005175 ICmpInst::Predicate pred = isICMP_NE ?
5176 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5177 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005178 }
5179
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005180 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005181 default: break;
5182 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005183 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5184 // Handle set{eq|ne} <intrinsic>, intcst.
5185 switch (II->getIntrinsicID()) {
5186 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005187 case Intrinsic::bswap_i16:
5188 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005189 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005190 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005191 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005192 ByteSwap_16(CI->getZExtValue())));
5193 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005194 case Intrinsic::bswap_i32:
5195 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005196 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005197 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005198 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005199 ByteSwap_32(CI->getZExtValue())));
5200 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005201 case Intrinsic::bswap_i64:
5202 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005203 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005204 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005205 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005206 ByteSwap_64(CI->getZExtValue())));
5207 return &I;
5208 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005209 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005210 } else { // Not a ICMP_EQ/ICMP_NE
5211 // If the LHS is a cast from an integral value of the same size, then
5212 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005213 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5214 Value *CastOp = Cast->getOperand(0);
5215 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005216 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005217 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005218 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005219 // If this is an unsigned comparison, try to make the comparison use
5220 // smaller constant values.
5221 switch (I.getPredicate()) {
5222 default: break;
5223 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5224 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005225 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005226 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005227 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005228 break;
5229 }
5230 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5231 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005232 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005233 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5234 Constant::getNullValue(SrcTy));
5235 break;
5236 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005237 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005238
Chris Lattner2b55ea32004-02-23 07:16:20 +00005239 }
5240 }
Chris Lattnere967b342003-06-04 05:10:11 +00005241 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005242 }
5243
Reid Spencer266e42b2006-12-23 06:05:41 +00005244 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005245 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5246 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5247 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005248 case Instruction::GetElementPtr:
5249 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005250 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005251 bool isAllZeros = true;
5252 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5253 if (!isa<Constant>(LHSI->getOperand(i)) ||
5254 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5255 isAllZeros = false;
5256 break;
5257 }
5258 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005259 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005260 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5261 }
5262 break;
5263
Chris Lattner77c32c32005-04-23 15:31:55 +00005264 case Instruction::PHI:
5265 if (Instruction *NV = FoldOpIntoPhi(I))
5266 return NV;
5267 break;
5268 case Instruction::Select:
5269 // If either operand of the select is a constant, we can fold the
5270 // comparison into the select arms, which will cause one to be
5271 // constant folded and the select turned into a bitwise or.
5272 Value *Op1 = 0, *Op2 = 0;
5273 if (LHSI->hasOneUse()) {
5274 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5275 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005276 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5277 // Insert a new ICmp of the other select operand.
5278 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5279 LHSI->getOperand(2), RHSC,
5280 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005281 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5282 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005283 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5284 // Insert a new ICmp of the other select operand.
5285 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5286 LHSI->getOperand(1), RHSC,
5287 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005288 }
5289 }
Jeff Cohen82639852005-04-23 21:38:35 +00005290
Chris Lattner77c32c32005-04-23 15:31:55 +00005291 if (Op1)
5292 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5293 break;
5294 }
5295 }
5296
Reid Spencer266e42b2006-12-23 06:05:41 +00005297 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005298 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005299 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005300 return NI;
5301 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005302 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5303 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005304 return NI;
5305
Reid Spencer266e42b2006-12-23 06:05:41 +00005306 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005307 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5308 // now.
5309 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5310 if (isa<PointerType>(Op0->getType()) &&
5311 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005312 // We keep moving the cast from the left operand over to the right
5313 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005314 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005315
Chris Lattner64d87b02007-01-06 01:45:59 +00005316 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5317 // so eliminate it as well.
5318 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5319 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005320
Chris Lattner16930792003-11-03 04:25:02 +00005321 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005322 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005323 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005324 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005325 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005326 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005327 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005328 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005329 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005330 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005331 }
5332
5333 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005334 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005335 // This comes up when you have code like
5336 // int X = A < B;
5337 // if (X) ...
5338 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005339 // with a constant or another cast from the same type.
5340 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005341 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005342 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005343 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005344
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005345 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005346 Value *A, *B, *C, *D;
5347 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5348 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5349 Value *OtherVal = A == Op1 ? B : A;
5350 return new ICmpInst(I.getPredicate(), OtherVal,
5351 Constant::getNullValue(A->getType()));
5352 }
5353
5354 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5355 // A^c1 == C^c2 --> A == C^(c1^c2)
5356 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5357 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5358 if (Op1->hasOneUse()) {
5359 Constant *NC = ConstantExpr::getXor(C1, C2);
5360 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5361 return new ICmpInst(I.getPredicate(), A,
5362 InsertNewInstBefore(Xor, I));
5363 }
5364
5365 // A^B == A^D -> B == D
5366 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5367 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5368 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5369 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5370 }
5371 }
5372
5373 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5374 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005375 // A == (A^B) -> B == 0
5376 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005377 return new ICmpInst(I.getPredicate(), OtherVal,
5378 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005379 }
5380 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005381 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005382 return new ICmpInst(I.getPredicate(), B,
5383 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005384 }
5385 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005386 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005387 return new ICmpInst(I.getPredicate(), B,
5388 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005389 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005390
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005391 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5392 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5393 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5394 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5395 Value *X = 0, *Y = 0, *Z = 0;
5396
5397 if (A == C) {
5398 X = B; Y = D; Z = A;
5399 } else if (A == D) {
5400 X = B; Y = C; Z = A;
5401 } else if (B == C) {
5402 X = A; Y = D; Z = B;
5403 } else if (B == D) {
5404 X = A; Y = C; Z = B;
5405 }
5406
5407 if (X) { // Build (X^Y) & Z
5408 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5409 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5410 I.setOperand(0, Op1);
5411 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5412 return &I;
5413 }
5414 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005415 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005416 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005417}
5418
Reid Spencer266e42b2006-12-23 06:05:41 +00005419// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005420// We only handle extending casts so far.
5421//
Reid Spencer266e42b2006-12-23 06:05:41 +00005422Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5423 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005424 Value *LHSCIOp = LHSCI->getOperand(0);
5425 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005426 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005427 Value *RHSCIOp;
5428
Reid Spencer266e42b2006-12-23 06:05:41 +00005429 // We only handle extension cast instructions, so far. Enforce this.
5430 if (LHSCI->getOpcode() != Instruction::ZExt &&
5431 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005432 return 0;
5433
Reid Spencer266e42b2006-12-23 06:05:41 +00005434 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5435 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005436
Reid Spencer266e42b2006-12-23 06:05:41 +00005437 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005438 // Not an extension from the same type?
5439 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005440 if (RHSCIOp->getType() != LHSCIOp->getType())
5441 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005442
5443 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5444 // and the other is a zext), then we can't handle this.
5445 if (CI->getOpcode() != LHSCI->getOpcode())
5446 return 0;
5447
5448 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5449 // then we can't handle this.
5450 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5451 return 0;
5452
5453 // Okay, just insert a compare of the reduced operands now!
5454 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005455 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005456
Reid Spencer266e42b2006-12-23 06:05:41 +00005457 // If we aren't dealing with a constant on the RHS, exit early
5458 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5459 if (!CI)
5460 return 0;
5461
5462 // Compute the constant that would happen if we truncated to SrcTy then
5463 // reextended to DestTy.
5464 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5465 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5466
5467 // If the re-extended constant didn't change...
5468 if (Res2 == CI) {
5469 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5470 // For example, we might have:
5471 // %A = sext short %X to uint
5472 // %B = icmp ugt uint %A, 1330
5473 // It is incorrect to transform this into
5474 // %B = icmp ugt short %X, 1330
5475 // because %A may have negative value.
5476 //
5477 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5478 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005479 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005480 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5481 else
5482 return 0;
5483 }
5484
5485 // The re-extended constant changed so the constant cannot be represented
5486 // in the shorter type. Consequently, we cannot emit a simple comparison.
5487
5488 // First, handle some easy cases. We know the result cannot be equal at this
5489 // point so handle the ICI.isEquality() cases
5490 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005491 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005492 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005493 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005494
5495 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5496 // should have been folded away previously and not enter in here.
5497 Value *Result;
5498 if (isSignedCmp) {
5499 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005500 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005501 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005502 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005503 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005504 } else {
5505 // We're performing an unsigned comparison.
5506 if (isSignedExt) {
5507 // We're performing an unsigned comp with a sign extended value.
5508 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005509 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005510 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5511 NegOne, ICI.getName()), ICI);
5512 } else {
5513 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005514 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005515 }
5516 }
5517
5518 // Finally, return the value computed.
5519 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5520 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5521 return ReplaceInstUsesWith(ICI, Result);
5522 } else {
5523 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5524 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5525 "ICmp should be folded!");
5526 if (Constant *CI = dyn_cast<Constant>(Result))
5527 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5528 else
5529 return BinaryOperator::createNot(Result);
5530 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005531}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005532
Reid Spencer2341c222007-02-02 02:16:23 +00005533Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5534 return commonShiftTransforms(I);
5535}
5536
5537Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5538 return commonShiftTransforms(I);
5539}
5540
5541Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5542 return commonShiftTransforms(I);
5543}
5544
5545Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5546 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005547 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005548
5549 // shl X, 0 == X and shr X, 0 == X
5550 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005551 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005552 Op0 == Constant::getNullValue(Op0->getType()))
5553 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005554
Reid Spencer266e42b2006-12-23 06:05:41 +00005555 if (isa<UndefValue>(Op0)) {
5556 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005557 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005558 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005559 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5560 }
5561 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005562 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5563 return ReplaceInstUsesWith(I, Op0);
5564 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005565 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005566 }
5567
Chris Lattnerd4dee402006-11-10 23:38:52 +00005568 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5569 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005570 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005571 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005572 return ReplaceInstUsesWith(I, CSI);
5573
Chris Lattner183b3362004-04-09 19:05:30 +00005574 // Try to fold constant and into select arguments.
5575 if (isa<Constant>(Op0))
5576 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005578 return R;
5579
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005580 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005581 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005582 if (MaskedValueIsZero(Op0,
5583 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005584 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005585 }
5586 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005587
Reid Spencere0fc4df2006-10-20 07:07:24 +00005588 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005589 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5590 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005591 return 0;
5592}
5593
Reid Spencere0fc4df2006-10-20 07:07:24 +00005594Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005595 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005596 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005597
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005598 // See if we can simplify any instructions used by the instruction whose sole
5599 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005600 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5601 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5602 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005603 KnownZero, KnownOne))
5604 return &I;
5605
Chris Lattner14553932006-01-06 07:12:35 +00005606 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5607 // of a signed value.
5608 //
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005609 if (Op1->getValue().getActiveBits() > 64 || Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005610 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005611 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5612 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005613 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005614 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005615 }
Chris Lattner14553932006-01-06 07:12:35 +00005616 }
5617
5618 // ((X*C1) << C2) == (X * (C1 << C2))
5619 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5620 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5621 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5622 return BinaryOperator::createMul(BO->getOperand(0),
5623 ConstantExpr::getShl(BOOp, Op1));
5624
5625 // Try to fold constant and into select arguments.
5626 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5627 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5628 return R;
5629 if (isa<PHINode>(Op0))
5630 if (Instruction *NV = FoldOpIntoPhi(I))
5631 return NV;
5632
5633 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005634 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5635 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5636 Value *V1, *V2;
5637 ConstantInt *CC;
5638 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005639 default: break;
5640 case Instruction::Add:
5641 case Instruction::And:
5642 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005643 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005644 // These operators commute.
5645 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005646 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5647 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005648 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005649 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005650 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005651 Op0BO->getName());
5652 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005653 Instruction *X =
5654 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5655 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005656 InsertNewInstBefore(X, I); // (X + (Y << C))
5657 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005658 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005659 return BinaryOperator::createAnd(X, C2);
5660 }
Chris Lattner14553932006-01-06 07:12:35 +00005661
Chris Lattner797dee72005-09-18 06:30:59 +00005662 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005663 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005664 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005665 match(Op0BOOp1,
5666 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005667 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5668 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005669 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005670 Op0BO->getOperand(0), Op1,
5671 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005672 InsertNewInstBefore(YS, I); // (Y << C)
5673 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005674 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005675 V1->getName()+".mask");
5676 InsertNewInstBefore(XM, I); // X & (CC << C)
5677
5678 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5679 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005680 }
Chris Lattner14553932006-01-06 07:12:35 +00005681
Reid Spencer2f34b982007-02-02 14:41:37 +00005682 // FALL THROUGH.
5683 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005684 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005685 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5686 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005687 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005688 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005689 Op0BO->getOperand(1), Op1,
5690 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005691 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005692 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005693 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005694 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005695 InsertNewInstBefore(X, I); // (X + (Y << C))
5696 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005697 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005698 return BinaryOperator::createAnd(X, C2);
5699 }
Chris Lattner14553932006-01-06 07:12:35 +00005700
Chris Lattner1df0e982006-05-31 21:14:00 +00005701 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005702 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5703 match(Op0BO->getOperand(0),
5704 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005705 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005706 cast<BinaryOperator>(Op0BO->getOperand(0))
5707 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005708 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005709 Op0BO->getOperand(1), Op1,
5710 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005711 InsertNewInstBefore(YS, I); // (Y << C)
5712 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005713 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005714 V1->getName()+".mask");
5715 InsertNewInstBefore(XM, I); // X & (CC << C)
5716
Chris Lattner1df0e982006-05-31 21:14:00 +00005717 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005718 }
Chris Lattner14553932006-01-06 07:12:35 +00005719
Chris Lattner27cb9db2005-09-18 05:12:10 +00005720 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005721 }
Chris Lattner14553932006-01-06 07:12:35 +00005722 }
5723
5724
5725 // If the operand is an bitwise operator with a constant RHS, and the
5726 // shift is the only use, we can pull it out of the shift.
5727 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5728 bool isValid = true; // Valid only for And, Or, Xor
5729 bool highBitSet = false; // Transform if high bit of constant set?
5730
5731 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005732 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005733 case Instruction::Add:
5734 isValid = isLeftShift;
5735 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005736 case Instruction::Or:
5737 case Instruction::Xor:
5738 highBitSet = false;
5739 break;
5740 case Instruction::And:
5741 highBitSet = true;
5742 break;
Chris Lattner14553932006-01-06 07:12:35 +00005743 }
5744
5745 // If this is a signed shift right, and the high bit is modified
5746 // by the logical operation, do not perform the transformation.
5747 // The highBitSet boolean indicates the value of the high bit of
5748 // the constant which would cause it to be modified for this
5749 // operation.
5750 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005751 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005752 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005753 }
5754
5755 if (isValid) {
5756 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5757
5758 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005759 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005760 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005761 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005762
5763 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5764 NewRHS);
5765 }
5766 }
5767 }
5768 }
5769
Chris Lattnereb372a02006-01-06 07:52:12 +00005770 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005771 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5772 if (ShiftOp && !ShiftOp->isShift())
5773 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005774
Reid Spencere0fc4df2006-10-20 07:07:24 +00005775 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005776 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005777 uint32_t ShiftAmt1 = ShiftAmt1C->getValue().getActiveBits() > 64 ?
5778 TypeBits : (uint32_t)ShiftAmt1C->getZExtValue();
5779 uint32_t ShiftAmt2 = Op1->getValue().getActiveBits() > 64 ?
5780 TypeBits : (uint32_t)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005781 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5782 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5783 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005784
Chris Lattner3e009e82007-02-05 00:57:54 +00005785 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005786 if (AmtSum > TypeBits)
5787 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005788
5789 const IntegerType *Ty = cast<IntegerType>(I.getType());
5790
5791 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005792 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005793 return BinaryOperator::create(I.getOpcode(), X,
5794 ConstantInt::get(Ty, AmtSum));
5795 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5796 I.getOpcode() == Instruction::AShr) {
5797 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5798 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5799 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5800 I.getOpcode() == Instruction::LShr) {
5801 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5802 Instruction *Shift =
5803 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5804 InsertNewInstBefore(Shift, I);
5805
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005806 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005807 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005808 }
5809
Chris Lattner3e009e82007-02-05 00:57:54 +00005810 // Okay, if we get here, one shift must be left, and the other shift must be
5811 // right. See if the amounts are equal.
5812 if (ShiftAmt1 == ShiftAmt2) {
5813 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5814 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005815 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005816 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005817 }
5818 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5819 if (I.getOpcode() == Instruction::LShr) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005820 APInt Mask(Ty->getMask().lshr(ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005821 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005822 }
5823 // We can simplify ((X << C) >>s C) into a trunc + sext.
5824 // NOTE: we could do this for any C, but that would make 'unusual' integer
5825 // types. For now, just stick to ones well-supported by the code
5826 // generators.
5827 const Type *SExtType = 0;
5828 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005829 case 1 :
5830 case 8 :
5831 case 16 :
5832 case 32 :
5833 case 64 :
5834 case 128:
5835 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5836 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005837 default: break;
5838 }
5839 if (SExtType) {
5840 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5841 InsertNewInstBefore(NewTrunc, I);
5842 return new SExtInst(NewTrunc, Ty);
5843 }
5844 // Otherwise, we can't handle it yet.
5845 } else if (ShiftAmt1 < ShiftAmt2) {
5846 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005847
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005848 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005849 if (I.getOpcode() == Instruction::Shl) {
5850 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5851 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005852 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005853 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005854 InsertNewInstBefore(Shift, I);
5855
Reid Spencer52830322007-03-25 21:11:44 +00005856 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5857 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005858 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005859
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005860 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005861 if (I.getOpcode() == Instruction::LShr) {
5862 assert(ShiftOp->getOpcode() == Instruction::Shl);
5863 Instruction *Shift =
5864 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5865 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005866
Reid Spencer769a5a82007-03-26 17:18:58 +00005867 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005868 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005869 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005870
5871 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5872 } else {
5873 assert(ShiftAmt2 < ShiftAmt1);
5874 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5875
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005876 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005877 if (I.getOpcode() == Instruction::Shl) {
5878 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5879 ShiftOp->getOpcode() == Instruction::AShr);
5880 Instruction *Shift =
5881 BinaryOperator::create(ShiftOp->getOpcode(), X,
5882 ConstantInt::get(Ty, ShiftDiff));
5883 InsertNewInstBefore(Shift, I);
5884
Reid Spencer52830322007-03-25 21:11:44 +00005885 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005886 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005887 }
5888
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005889 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005890 if (I.getOpcode() == Instruction::LShr) {
5891 assert(ShiftOp->getOpcode() == Instruction::Shl);
5892 Instruction *Shift =
5893 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5894 InsertNewInstBefore(Shift, I);
5895
Reid Spencer441486c2007-03-26 23:45:51 +00005896 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005897 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005898 }
5899
5900 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005901 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005902 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005903 return 0;
5904}
5905
Chris Lattner48a44f72002-05-02 17:06:02 +00005906
Chris Lattner8f663e82005-10-29 04:36:15 +00005907/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5908/// expression. If so, decompose it, returning some value X, such that Val is
5909/// X*Scale+Offset.
5910///
5911static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5912 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005913 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005914 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005915 Offset = CI->getZExtValue();
5916 Scale = 1;
5917 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005918 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5919 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005920 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005921 if (I->getOpcode() == Instruction::Shl) {
5922 // This is a value scaled by '1 << the shift amt'.
5923 Scale = 1U << CUI->getZExtValue();
5924 Offset = 0;
5925 return I->getOperand(0);
5926 } else if (I->getOpcode() == Instruction::Mul) {
5927 // This value is scaled by 'CUI'.
5928 Scale = CUI->getZExtValue();
5929 Offset = 0;
5930 return I->getOperand(0);
5931 } else if (I->getOpcode() == Instruction::Add) {
5932 // We have X+C. Check to see if we really have (X*C2)+C1,
5933 // where C1 is divisible by C2.
5934 unsigned SubScale;
5935 Value *SubVal =
5936 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5937 Offset += CUI->getZExtValue();
5938 if (SubScale > 1 && (Offset % SubScale == 0)) {
5939 Scale = SubScale;
5940 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005941 }
5942 }
5943 }
5944 }
5945 }
5946
5947 // Otherwise, we can't look past this.
5948 Scale = 1;
5949 Offset = 0;
5950 return Val;
5951}
5952
5953
Chris Lattner216be912005-10-24 06:03:58 +00005954/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5955/// try to eliminate the cast by moving the type information into the alloc.
5956Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5957 AllocationInst &AI) {
5958 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005959 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005960
Chris Lattnerac87beb2005-10-24 06:22:12 +00005961 // Remove any uses of AI that are dead.
5962 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005963
Chris Lattnerac87beb2005-10-24 06:22:12 +00005964 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5965 Instruction *User = cast<Instruction>(*UI++);
5966 if (isInstructionTriviallyDead(User)) {
5967 while (UI != E && *UI == User)
5968 ++UI; // If this instruction uses AI more than once, don't break UI.
5969
Chris Lattnerac87beb2005-10-24 06:22:12 +00005970 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005971 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005972 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005973 }
5974 }
5975
Chris Lattner216be912005-10-24 06:03:58 +00005976 // Get the type really allocated and the type casted to.
5977 const Type *AllocElTy = AI.getAllocatedType();
5978 const Type *CastElTy = PTy->getElementType();
5979 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005980
Chris Lattner945e4372007-02-14 05:52:17 +00005981 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5982 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005983 if (CastElTyAlign < AllocElTyAlign) return 0;
5984
Chris Lattner46705b22005-10-24 06:35:18 +00005985 // If the allocation has multiple uses, only promote it if we are strictly
5986 // increasing the alignment of the resultant allocation. If we keep it the
5987 // same, we open the door to infinite loops of various kinds.
5988 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5989
Chris Lattner216be912005-10-24 06:03:58 +00005990 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5991 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005992 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005993
Chris Lattner8270c332005-10-29 03:19:53 +00005994 // See if we can satisfy the modulus by pulling a scale out of the array
5995 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005996 unsigned ArraySizeScale, ArrayOffset;
5997 Value *NumElements = // See if the array size is a decomposable linear expr.
5998 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5999
Chris Lattner8270c332005-10-29 03:19:53 +00006000 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6001 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006002 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6003 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006004
Chris Lattner8270c332005-10-29 03:19:53 +00006005 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6006 Value *Amt = 0;
6007 if (Scale == 1) {
6008 Amt = NumElements;
6009 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006010 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006011 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6012 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006013 Amt = ConstantExpr::getMul(
6014 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6015 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006016 else if (Scale != 1) {
6017 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6018 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006019 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006020 }
6021
Chris Lattner8f663e82005-10-29 04:36:15 +00006022 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006023 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006024 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6025 Amt = InsertNewInstBefore(Tmp, AI);
6026 }
6027
Chris Lattner216be912005-10-24 06:03:58 +00006028 AllocationInst *New;
6029 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006030 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006031 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006032 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006033 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006034 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006035
6036 // If the allocation has multiple uses, insert a cast and change all things
6037 // that used it to use the new cast. This will also hack on CI, but it will
6038 // die soon.
6039 if (!AI.hasOneUse()) {
6040 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006041 // New is the allocation instruction, pointer typed. AI is the original
6042 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6043 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006044 InsertNewInstBefore(NewCast, AI);
6045 AI.replaceAllUsesWith(NewCast);
6046 }
Chris Lattner216be912005-10-24 06:03:58 +00006047 return ReplaceInstUsesWith(CI, New);
6048}
6049
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006050/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006051/// and return it as type Ty without inserting any new casts and without
6052/// changing the computed value. This is used by code that tries to decide
6053/// whether promoting or shrinking integer operations to wider or smaller types
6054/// will allow us to eliminate a truncate or extend.
6055///
6056/// This is a truncation operation if Ty is smaller than V->getType(), or an
6057/// extension operation if Ty is larger.
6058static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006059 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006060 // We can always evaluate constants in another type.
6061 if (isa<ConstantInt>(V))
6062 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006063
6064 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006065 if (!I) return false;
6066
6067 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006068
6069 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006070 case Instruction::Add:
6071 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006072 case Instruction::And:
6073 case Instruction::Or:
6074 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006075 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006076 // These operators can all arbitrarily be extended or truncated.
6077 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6078 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006079
Chris Lattner960acb02006-11-29 07:18:39 +00006080 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006081 if (!I->hasOneUse()) return false;
6082 // If we are truncating the result of this SHL, and if it's a shift of a
6083 // constant amount, we can always perform a SHL in a smaller type.
6084 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6085 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6086 CI->getZExtValue() < Ty->getBitWidth())
6087 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6088 }
6089 break;
6090 case Instruction::LShr:
6091 if (!I->hasOneUse()) return false;
6092 // If this is a truncate of a logical shr, we can truncate it to a smaller
6093 // lshr iff we know that the bits we would otherwise be shifting in are
6094 // already zeros.
6095 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006096 uint32_t BitWidth = OrigTy->getBitWidth();
Zhou Sheng755f04b2007-03-23 02:39:25 +00006097 if (Ty->getBitWidth() < BitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006098 MaskedValueIsZero(I->getOperand(0),
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006099 APInt::getAllOnesValue(BitWidth) &
6100 APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6101 && CI->getZExtValue() < Ty->getBitWidth()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006102 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6103 }
6104 }
Chris Lattner960acb02006-11-29 07:18:39 +00006105 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006106 case Instruction::Trunc:
6107 case Instruction::ZExt:
6108 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006109 // If this is a cast from the destination type, we can trivially eliminate
6110 // it, and this will remove a cast overall.
6111 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006112 // If the first operand is itself a cast, and is eliminable, do not count
6113 // this as an eliminable cast. We would prefer to eliminate those two
6114 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006115 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006116 return true;
6117
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006118 ++NumCastsRemoved;
6119 return true;
6120 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006121 break;
6122 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006123 // TODO: Can handle more cases here.
6124 break;
6125 }
6126
6127 return false;
6128}
6129
6130/// EvaluateInDifferentType - Given an expression that
6131/// CanEvaluateInDifferentType returns true for, actually insert the code to
6132/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006133Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006134 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006135 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006136 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006137
6138 // Otherwise, it must be an instruction.
6139 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006140 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006141 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006142 case Instruction::Add:
6143 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006144 case Instruction::And:
6145 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006146 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006147 case Instruction::AShr:
6148 case Instruction::LShr:
6149 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006150 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006151 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6152 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6153 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006154 break;
6155 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006156 case Instruction::Trunc:
6157 case Instruction::ZExt:
6158 case Instruction::SExt:
6159 case Instruction::BitCast:
6160 // If the source type of the cast is the type we're trying for then we can
6161 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006162 if (I->getOperand(0)->getType() == Ty)
6163 return I->getOperand(0);
6164
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006165 // Some other kind of cast, which shouldn't happen, so just ..
6166 // FALL THROUGH
6167 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006168 // TODO: Can handle more cases here.
6169 assert(0 && "Unreachable!");
6170 break;
6171 }
6172
6173 return InsertNewInstBefore(Res, *I);
6174}
6175
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006176/// @brief Implement the transforms common to all CastInst visitors.
6177Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006178 Value *Src = CI.getOperand(0);
6179
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006180 // Casting undef to anything results in undef so might as just replace it and
6181 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006182 if (isa<UndefValue>(Src)) // cast undef -> undef
6183 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6184
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006185 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6186 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006187 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006188 if (Instruction::CastOps opc =
6189 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6190 // The first cast (CSrc) is eliminable so we need to fix up or replace
6191 // the second cast (CI). CSrc will then have a good chance of being dead.
6192 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006193 }
6194 }
Chris Lattner03841652004-05-25 04:29:21 +00006195
Chris Lattnerd0d51602003-06-21 23:12:02 +00006196 // If casting the result of a getelementptr instruction with no offset, turn
6197 // this into a cast of the original pointer!
6198 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006199 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006200 bool AllZeroOperands = true;
6201 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6202 if (!isa<Constant>(GEP->getOperand(i)) ||
6203 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6204 AllZeroOperands = false;
6205 break;
6206 }
6207 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006208 // Changing the cast operand is usually not a good idea but it is safe
6209 // here because the pointer operand is being replaced with another
6210 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006211 CI.setOperand(0, GEP->getOperand(0));
6212 return &CI;
6213 }
6214 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006215
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006216 // If we are casting a malloc or alloca to a pointer to a type of the same
6217 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006218 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006219 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6220 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006221
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006222 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006223 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6224 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6225 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006226
6227 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006228 if (isa<PHINode>(Src))
6229 if (Instruction *NV = FoldOpIntoPhi(CI))
6230 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006231
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006232 return 0;
6233}
6234
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006235/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6236/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006237/// cases.
6238/// @brief Implement the transforms common to CastInst with integer operands
6239Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6240 if (Instruction *Result = commonCastTransforms(CI))
6241 return Result;
6242
6243 Value *Src = CI.getOperand(0);
6244 const Type *SrcTy = Src->getType();
6245 const Type *DestTy = CI.getType();
6246 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6247 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6248
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006249 // See if we can simplify any instructions used by the LHS whose sole
6250 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006251 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6252 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006253 KnownZero, KnownOne))
6254 return &CI;
6255
6256 // If the source isn't an instruction or has more than one use then we
6257 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006258 Instruction *SrcI = dyn_cast<Instruction>(Src);
6259 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006260 return 0;
6261
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006262 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006263 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006264 if (!isa<BitCastInst>(CI) &&
6265 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6266 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006267 // If this cast is a truncate, evaluting in a different type always
6268 // eliminates the cast, so it is always a win. If this is a noop-cast
6269 // this just removes a noop cast which isn't pointful, but simplifies
6270 // the code. If this is a zero-extension, we need to do an AND to
6271 // maintain the clear top-part of the computation, so we require that
6272 // the input have eliminated at least one cast. If this is a sign
6273 // extension, we insert two new casts (to do the extension) so we
6274 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006275 bool DoXForm;
6276 switch (CI.getOpcode()) {
6277 default:
6278 // All the others use floating point so we shouldn't actually
6279 // get here because of the check above.
6280 assert(0 && "Unknown cast type");
6281 case Instruction::Trunc:
6282 DoXForm = true;
6283 break;
6284 case Instruction::ZExt:
6285 DoXForm = NumCastsRemoved >= 1;
6286 break;
6287 case Instruction::SExt:
6288 DoXForm = NumCastsRemoved >= 2;
6289 break;
6290 case Instruction::BitCast:
6291 DoXForm = false;
6292 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006293 }
6294
6295 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006296 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6297 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006298 assert(Res->getType() == DestTy);
6299 switch (CI.getOpcode()) {
6300 default: assert(0 && "Unknown cast type!");
6301 case Instruction::Trunc:
6302 case Instruction::BitCast:
6303 // Just replace this cast with the result.
6304 return ReplaceInstUsesWith(CI, Res);
6305 case Instruction::ZExt: {
6306 // We need to emit an AND to clear the high bits.
6307 assert(SrcBitSize < DestBitSize && "Not a zext?");
Zhou Sheng2777a312007-03-28 09:19:01 +00006308 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006309 return BinaryOperator::createAnd(Res, C);
6310 }
6311 case Instruction::SExt:
6312 // We need to emit a cast to truncate, then a cast to sext.
6313 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006314 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6315 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006316 }
6317 }
6318 }
6319
6320 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6321 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6322
6323 switch (SrcI->getOpcode()) {
6324 case Instruction::Add:
6325 case Instruction::Mul:
6326 case Instruction::And:
6327 case Instruction::Or:
6328 case Instruction::Xor:
6329 // If we are discarding information, or just changing the sign,
6330 // rewrite.
6331 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6332 // Don't insert two casts if they cannot be eliminated. We allow
6333 // two casts to be inserted if the sizes are the same. This could
6334 // only be converting signedness, which is a noop.
6335 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006336 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6337 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006338 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006339 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6340 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6341 return BinaryOperator::create(
6342 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006343 }
6344 }
6345
6346 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6347 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6348 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006349 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006350 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006351 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006352 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6353 }
6354 break;
6355 case Instruction::SDiv:
6356 case Instruction::UDiv:
6357 case Instruction::SRem:
6358 case Instruction::URem:
6359 // If we are just changing the sign, rewrite.
6360 if (DestBitSize == SrcBitSize) {
6361 // Don't insert two casts if they cannot be eliminated. We allow
6362 // two casts to be inserted if the sizes are the same. This could
6363 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006364 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6365 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006366 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6367 Op0, DestTy, SrcI);
6368 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6369 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006370 return BinaryOperator::create(
6371 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6372 }
6373 }
6374 break;
6375
6376 case Instruction::Shl:
6377 // Allow changing the sign of the source operand. Do not allow
6378 // changing the size of the shift, UNLESS the shift amount is a
6379 // constant. We must not change variable sized shifts to a smaller
6380 // size, because it is undefined to shift more bits out than exist
6381 // in the value.
6382 if (DestBitSize == SrcBitSize ||
6383 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006384 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6385 Instruction::BitCast : Instruction::Trunc);
6386 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006387 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006388 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006389 }
6390 break;
6391 case Instruction::AShr:
6392 // If this is a signed shr, and if all bits shifted in are about to be
6393 // truncated off, turn it into an unsigned shr to allow greater
6394 // simplifications.
6395 if (DestBitSize < SrcBitSize &&
6396 isa<ConstantInt>(Op1)) {
6397 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6398 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6399 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006400 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006401 }
6402 }
6403 break;
6404
Reid Spencer266e42b2006-12-23 06:05:41 +00006405 case Instruction::ICmp:
6406 // If we are just checking for a icmp eq of a single bit and casting it
6407 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006408 // cast to integer to avoid the comparison.
6409 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer4154e732007-03-22 20:56:53 +00006410 APInt Op1CV(Op1C->getValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006411 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6412 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6413 // cast (X == 1) to int --> X iff X has only the low bit set.
6414 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6415 // cast (X != 0) to int --> X iff X has only the low bit set.
6416 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6417 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6418 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006419 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006420 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006421 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6422 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6423 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006424 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006425
6426 // This only works for EQ and NE
6427 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6428 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6429 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006430
Zhou Sheng0900993e2007-03-23 03:13:21 +00006431 APInt KnownZeroMask(KnownZero ^ TypeMask);
6432 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006433 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006434 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006435 // (X&4) == 2 --> false
6436 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006437 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006438 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006439 return ReplaceInstUsesWith(CI, Res);
6440 }
6441
Zhou Sheng0900993e2007-03-23 03:13:21 +00006442 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006443 Value *In = Op0;
6444 if (ShiftAmt) {
6445 // Perform a logical shr by shiftamt.
6446 // Insert the shift to put the result in the low bit.
6447 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006448 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006449 ConstantInt::get(In->getType(), ShiftAmt),
6450 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006451 }
6452
Reid Spencer266e42b2006-12-23 06:05:41 +00006453 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006454 Constant *One = ConstantInt::get(In->getType(), 1);
6455 In = BinaryOperator::createXor(In, One, "tmp");
6456 InsertNewInstBefore(cast<Instruction>(In), CI);
6457 }
6458
6459 if (CI.getType() == In->getType())
6460 return ReplaceInstUsesWith(CI, In);
6461 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006462 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006463 }
6464 }
6465 }
6466 break;
6467 }
6468 return 0;
6469}
6470
6471Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006472 if (Instruction *Result = commonIntCastTransforms(CI))
6473 return Result;
6474
6475 Value *Src = CI.getOperand(0);
6476 const Type *Ty = CI.getType();
6477 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00006478 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006479
6480 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6481 switch (SrcI->getOpcode()) {
6482 default: break;
6483 case Instruction::LShr:
6484 // We can shrink lshr to something smaller if we know the bits shifted in
6485 // are already zeros.
6486 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6487 unsigned ShAmt = ShAmtV->getZExtValue();
6488
6489 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006490 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006491 Value* SrcIOp0 = SrcI->getOperand(0);
6492 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006493 if (ShAmt >= DestBitWidth) // All zeros.
6494 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6495
6496 // Okay, we can shrink this. Truncate the input, then return a new
6497 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006498 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6499 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6500 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006501 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006502 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006503 } else { // This is a variable shr.
6504
6505 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6506 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6507 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006508 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006509 Value *One = ConstantInt::get(SrcI->getType(), 1);
6510
Reid Spencer2341c222007-02-02 02:16:23 +00006511 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006512 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006513 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006514 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6515 SrcI->getOperand(0),
6516 "tmp"), CI);
6517 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006518 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006519 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006520 }
6521 break;
6522 }
6523 }
6524
6525 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006526}
6527
6528Instruction *InstCombiner::visitZExt(CastInst &CI) {
6529 // If one of the common conversion will work ..
6530 if (Instruction *Result = commonIntCastTransforms(CI))
6531 return Result;
6532
6533 Value *Src = CI.getOperand(0);
6534
6535 // If this is a cast of a cast
6536 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006537 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6538 // types and if the sizes are just right we can convert this into a logical
6539 // 'and' which will be much cheaper than the pair of casts.
6540 if (isa<TruncInst>(CSrc)) {
6541 // Get the sizes of the types involved
6542 Value *A = CSrc->getOperand(0);
6543 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6544 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6545 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6546 // If we're actually extending zero bits and the trunc is a no-op
6547 if (MidSize < DstSize && SrcSize == DstSize) {
6548 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006549 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006550 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006551 Instruction *And =
6552 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6553 // Unfortunately, if the type changed, we need to cast it back.
6554 if (And->getType() != CI.getType()) {
6555 And->setName(CSrc->getName()+".mask");
6556 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006557 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006558 }
6559 return And;
6560 }
6561 }
6562 }
6563
6564 return 0;
6565}
6566
6567Instruction *InstCombiner::visitSExt(CastInst &CI) {
6568 return commonIntCastTransforms(CI);
6569}
6570
6571Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6572 return commonCastTransforms(CI);
6573}
6574
6575Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6576 return commonCastTransforms(CI);
6577}
6578
6579Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006580 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006581}
6582
6583Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006584 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006585}
6586
6587Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6588 return commonCastTransforms(CI);
6589}
6590
6591Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6592 return commonCastTransforms(CI);
6593}
6594
6595Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006596 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006597}
6598
6599Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6600 return commonCastTransforms(CI);
6601}
6602
6603Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6604
6605 // If the operands are integer typed then apply the integer transforms,
6606 // otherwise just apply the common ones.
6607 Value *Src = CI.getOperand(0);
6608 const Type *SrcTy = Src->getType();
6609 const Type *DestTy = CI.getType();
6610
Chris Lattner03c49532007-01-15 02:27:26 +00006611 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006612 if (Instruction *Result = commonIntCastTransforms(CI))
6613 return Result;
6614 } else {
6615 if (Instruction *Result = commonCastTransforms(CI))
6616 return Result;
6617 }
6618
6619
6620 // Get rid of casts from one type to the same type. These are useless and can
6621 // be replaced by the operand.
6622 if (DestTy == Src->getType())
6623 return ReplaceInstUsesWith(CI, Src);
6624
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006625 // If the source and destination are pointers, and this cast is equivalent to
6626 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6627 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006628 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6629 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6630 const Type *DstElTy = DstPTy->getElementType();
6631 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006632
Reid Spencerc635f472006-12-31 05:48:39 +00006633 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006634 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006635 while (SrcElTy != DstElTy &&
6636 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6637 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6638 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006639 ++NumZeros;
6640 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006641
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006642 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006643 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006644 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6645 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006646 }
6647 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006648 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006649
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006650 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6651 if (SVI->hasOneUse()) {
6652 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6653 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006654 if (isa<VectorType>(DestTy) &&
6655 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006656 SVI->getType()->getNumElements()) {
6657 CastInst *Tmp;
6658 // If either of the operands is a cast from CI.getType(), then
6659 // evaluating the shuffle in the casted destination's type will allow
6660 // us to eliminate at least one cast.
6661 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6662 Tmp->getOperand(0)->getType() == DestTy) ||
6663 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6664 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006665 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6666 SVI->getOperand(0), DestTy, &CI);
6667 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6668 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006669 // Return a new shuffle vector. Use the same element ID's, as we
6670 // know the vector types match #elts.
6671 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006672 }
6673 }
6674 }
6675 }
Chris Lattner260ab202002-04-18 17:39:14 +00006676 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006677}
6678
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006679/// GetSelectFoldableOperands - We want to turn code that looks like this:
6680/// %C = or %A, %B
6681/// %D = select %cond, %C, %A
6682/// into:
6683/// %C = select %cond, %B, 0
6684/// %D = or %A, %C
6685///
6686/// Assuming that the specified instruction is an operand to the select, return
6687/// a bitmask indicating which operands of this instruction are foldable if they
6688/// equal the other incoming value of the select.
6689///
6690static unsigned GetSelectFoldableOperands(Instruction *I) {
6691 switch (I->getOpcode()) {
6692 case Instruction::Add:
6693 case Instruction::Mul:
6694 case Instruction::And:
6695 case Instruction::Or:
6696 case Instruction::Xor:
6697 return 3; // Can fold through either operand.
6698 case Instruction::Sub: // Can only fold on the amount subtracted.
6699 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006700 case Instruction::LShr:
6701 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006702 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006703 default:
6704 return 0; // Cannot fold
6705 }
6706}
6707
6708/// GetSelectFoldableConstant - For the same transformation as the previous
6709/// function, return the identity constant that goes into the select.
6710static Constant *GetSelectFoldableConstant(Instruction *I) {
6711 switch (I->getOpcode()) {
6712 default: assert(0 && "This cannot happen!"); abort();
6713 case Instruction::Add:
6714 case Instruction::Sub:
6715 case Instruction::Or:
6716 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006717 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006718 case Instruction::LShr:
6719 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006720 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006721 case Instruction::And:
6722 return ConstantInt::getAllOnesValue(I->getType());
6723 case Instruction::Mul:
6724 return ConstantInt::get(I->getType(), 1);
6725 }
6726}
6727
Chris Lattner411336f2005-01-19 21:50:18 +00006728/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6729/// have the same opcode and only one use each. Try to simplify this.
6730Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6731 Instruction *FI) {
6732 if (TI->getNumOperands() == 1) {
6733 // If this is a non-volatile load or a cast from the same type,
6734 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006735 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006736 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6737 return 0;
6738 } else {
6739 return 0; // unknown unary op.
6740 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006741
Chris Lattner411336f2005-01-19 21:50:18 +00006742 // Fold this by inserting a select from the input values.
6743 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6744 FI->getOperand(0), SI.getName()+".v");
6745 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006746 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6747 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006748 }
6749
Reid Spencer2341c222007-02-02 02:16:23 +00006750 // Only handle binary operators here.
6751 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006752 return 0;
6753
6754 // Figure out if the operations have any operands in common.
6755 Value *MatchOp, *OtherOpT, *OtherOpF;
6756 bool MatchIsOpZero;
6757 if (TI->getOperand(0) == FI->getOperand(0)) {
6758 MatchOp = TI->getOperand(0);
6759 OtherOpT = TI->getOperand(1);
6760 OtherOpF = FI->getOperand(1);
6761 MatchIsOpZero = true;
6762 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6763 MatchOp = TI->getOperand(1);
6764 OtherOpT = TI->getOperand(0);
6765 OtherOpF = FI->getOperand(0);
6766 MatchIsOpZero = false;
6767 } else if (!TI->isCommutative()) {
6768 return 0;
6769 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6770 MatchOp = TI->getOperand(0);
6771 OtherOpT = TI->getOperand(1);
6772 OtherOpF = FI->getOperand(0);
6773 MatchIsOpZero = true;
6774 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6775 MatchOp = TI->getOperand(1);
6776 OtherOpT = TI->getOperand(0);
6777 OtherOpF = FI->getOperand(1);
6778 MatchIsOpZero = true;
6779 } else {
6780 return 0;
6781 }
6782
6783 // If we reach here, they do have operations in common.
6784 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6785 OtherOpF, SI.getName()+".v");
6786 InsertNewInstBefore(NewSI, SI);
6787
6788 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6789 if (MatchIsOpZero)
6790 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6791 else
6792 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006793 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006794 assert(0 && "Shouldn't get here");
6795 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006796}
6797
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006798Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006799 Value *CondVal = SI.getCondition();
6800 Value *TrueVal = SI.getTrueValue();
6801 Value *FalseVal = SI.getFalseValue();
6802
6803 // select true, X, Y -> X
6804 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006805 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006806 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006807
6808 // select C, X, X -> X
6809 if (TrueVal == FalseVal)
6810 return ReplaceInstUsesWith(SI, TrueVal);
6811
Chris Lattner81a7a232004-10-16 18:11:37 +00006812 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6813 return ReplaceInstUsesWith(SI, FalseVal);
6814 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6815 return ReplaceInstUsesWith(SI, TrueVal);
6816 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6817 if (isa<Constant>(TrueVal))
6818 return ReplaceInstUsesWith(SI, TrueVal);
6819 else
6820 return ReplaceInstUsesWith(SI, FalseVal);
6821 }
6822
Reid Spencer542964f2007-01-11 18:21:29 +00006823 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006824 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006825 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006826 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006827 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006828 } else {
6829 // Change: A = select B, false, C --> A = and !B, C
6830 Value *NotCond =
6831 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6832 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006833 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006834 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006835 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006836 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006837 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006838 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006839 } else {
6840 // Change: A = select B, C, true --> A = or !B, C
6841 Value *NotCond =
6842 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6843 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006844 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006845 }
6846 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006847 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006848
Chris Lattner183b3362004-04-09 19:05:30 +00006849 // Selecting between two integer constants?
6850 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6851 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6852 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006853 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006854 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006855 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006856 // select C, 0, 1 -> cast !C to int
6857 Value *NotCond =
6858 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006859 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006860 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006861 }
Chris Lattner35167c32004-06-09 07:59:58 +00006862
Reid Spencer266e42b2006-12-23 06:05:41 +00006863 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006864
Reid Spencer266e42b2006-12-23 06:05:41 +00006865 // (x <s 0) ? -1 : 0 -> ashr x, 31
6866 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006867 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006868 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6869 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006870 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006871 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006872 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006873 else {
6874 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006875 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006876 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006877 }
6878
6879 if (CanXForm) {
6880 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006881 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006882 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006883 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006884 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6885 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6886 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006887 InsertNewInstBefore(SRA, SI);
6888
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006889 // Finally, convert to the type of the select RHS. We figure out
6890 // if this requires a SExt, Trunc or BitCast based on the sizes.
6891 Instruction::CastOps opc = Instruction::BitCast;
6892 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6893 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6894 if (SRASize < SISize)
6895 opc = Instruction::SExt;
6896 else if (SRASize > SISize)
6897 opc = Instruction::Trunc;
6898 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006899 }
6900 }
6901
6902
6903 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006904 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006905 // non-constant value, eliminate this whole mess. This corresponds to
6906 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006907 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006908 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006909 cast<Constant>(IC->getOperand(1))->isNullValue())
6910 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6911 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006912 isa<ConstantInt>(ICA->getOperand(1)) &&
6913 (ICA->getOperand(1) == TrueValC ||
6914 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006915 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6916 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006917 // know whether we have a icmp_ne or icmp_eq and whether the
6918 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006919 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006920 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006921 Value *V = ICA;
6922 if (ShouldNotVal)
6923 V = InsertNewInstBefore(BinaryOperator::create(
6924 Instruction::Xor, V, ICA->getOperand(1)), SI);
6925 return ReplaceInstUsesWith(SI, V);
6926 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006927 }
Chris Lattner533bc492004-03-30 19:37:13 +00006928 }
Chris Lattner623fba12004-04-10 22:21:27 +00006929
6930 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006931 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6932 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006933 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006934 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006935 return ReplaceInstUsesWith(SI, FalseVal);
6936 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006937 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006938 return ReplaceInstUsesWith(SI, TrueVal);
6939 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6940
Reid Spencer266e42b2006-12-23 06:05:41 +00006941 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006942 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006943 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006944 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006945 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006946 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6947 return ReplaceInstUsesWith(SI, TrueVal);
6948 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6949 }
6950 }
6951
6952 // See if we are selecting two values based on a comparison of the two values.
6953 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6954 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6955 // Transform (X == Y) ? X : Y -> Y
6956 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6957 return ReplaceInstUsesWith(SI, FalseVal);
6958 // Transform (X != Y) ? X : Y -> X
6959 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6960 return ReplaceInstUsesWith(SI, TrueVal);
6961 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6962
6963 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6964 // Transform (X == Y) ? Y : X -> X
6965 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6966 return ReplaceInstUsesWith(SI, FalseVal);
6967 // Transform (X != Y) ? Y : X -> Y
6968 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006969 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006970 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6971 }
6972 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006973
Chris Lattnera04c9042005-01-13 22:52:24 +00006974 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6975 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6976 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006977 Instruction *AddOp = 0, *SubOp = 0;
6978
Chris Lattner411336f2005-01-19 21:50:18 +00006979 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6980 if (TI->getOpcode() == FI->getOpcode())
6981 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6982 return IV;
6983
6984 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6985 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006986 if (TI->getOpcode() == Instruction::Sub &&
6987 FI->getOpcode() == Instruction::Add) {
6988 AddOp = FI; SubOp = TI;
6989 } else if (FI->getOpcode() == Instruction::Sub &&
6990 TI->getOpcode() == Instruction::Add) {
6991 AddOp = TI; SubOp = FI;
6992 }
6993
6994 if (AddOp) {
6995 Value *OtherAddOp = 0;
6996 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6997 OtherAddOp = AddOp->getOperand(1);
6998 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6999 OtherAddOp = AddOp->getOperand(0);
7000 }
7001
7002 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007003 // So at this point we know we have (Y -> OtherAddOp):
7004 // select C, (add X, Y), (sub X, Z)
7005 Value *NegVal; // Compute -Z
7006 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7007 NegVal = ConstantExpr::getNeg(C);
7008 } else {
7009 NegVal = InsertNewInstBefore(
7010 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007011 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007012
7013 Value *NewTrueOp = OtherAddOp;
7014 Value *NewFalseOp = NegVal;
7015 if (AddOp != TI)
7016 std::swap(NewTrueOp, NewFalseOp);
7017 Instruction *NewSel =
7018 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7019
7020 NewSel = InsertNewInstBefore(NewSel, SI);
7021 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007022 }
7023 }
7024 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007025
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007026 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007027 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007028 // See the comment above GetSelectFoldableOperands for a description of the
7029 // transformation we are doing here.
7030 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7031 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7032 !isa<Constant>(FalseVal))
7033 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7034 unsigned OpToFold = 0;
7035 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7036 OpToFold = 1;
7037 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7038 OpToFold = 2;
7039 }
7040
7041 if (OpToFold) {
7042 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007043 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007044 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007045 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007046 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7048 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007049 else {
7050 assert(0 && "Unknown instruction!!");
7051 }
7052 }
7053 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007054
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007055 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7056 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7057 !isa<Constant>(TrueVal))
7058 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7059 unsigned OpToFold = 0;
7060 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7061 OpToFold = 1;
7062 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7063 OpToFold = 2;
7064 }
7065
7066 if (OpToFold) {
7067 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007068 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007069 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007070 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007071 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007072 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7073 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007074 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007075 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007076 }
7077 }
7078 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007079
7080 if (BinaryOperator::isNot(CondVal)) {
7081 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7082 SI.setOperand(1, FalseVal);
7083 SI.setOperand(2, TrueVal);
7084 return &SI;
7085 }
7086
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007087 return 0;
7088}
7089
Chris Lattner82f2ef22006-03-06 20:18:44 +00007090/// GetKnownAlignment - If the specified pointer has an alignment that we can
7091/// determine, return it, otherwise return 0.
7092static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7093 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7094 unsigned Align = GV->getAlignment();
7095 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007096 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007097 return Align;
7098 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7099 unsigned Align = AI->getAlignment();
7100 if (Align == 0 && TD) {
7101 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007102 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007103 else if (isa<MallocInst>(AI)) {
7104 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007105 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007106 Align =
7107 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007108 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007109 Align =
7110 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007111 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007112 }
7113 }
7114 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007115 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007116 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007117 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007118 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007119 if (isa<PointerType>(CI->getOperand(0)->getType()))
7120 return GetKnownAlignment(CI->getOperand(0), TD);
7121 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007122 } else if (isa<GetElementPtrInst>(V) ||
7123 (isa<ConstantExpr>(V) &&
7124 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7125 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007126 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7127 if (BaseAlignment == 0) return 0;
7128
7129 // If all indexes are zero, it is just the alignment of the base pointer.
7130 bool AllZeroOperands = true;
7131 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7132 if (!isa<Constant>(GEPI->getOperand(i)) ||
7133 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7134 AllZeroOperands = false;
7135 break;
7136 }
7137 if (AllZeroOperands)
7138 return BaseAlignment;
7139
7140 // Otherwise, if the base alignment is >= the alignment we expect for the
7141 // base pointer type, then we know that the resultant pointer is aligned at
7142 // least as much as its type requires.
7143 if (!TD) return 0;
7144
7145 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007146 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007147 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007148 <= BaseAlignment) {
7149 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007150 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007151 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007152 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007153 return 0;
7154 }
7155 return 0;
7156}
7157
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007158
Chris Lattnerc66b2232006-01-13 20:11:04 +00007159/// visitCallInst - CallInst simplification. This mostly only handles folding
7160/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7161/// the heavy lifting.
7162///
Chris Lattner970c33a2003-06-19 17:00:31 +00007163Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007164 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7165 if (!II) return visitCallSite(&CI);
7166
Chris Lattner51ea1272004-02-28 05:22:00 +00007167 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7168 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007169 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007170 bool Changed = false;
7171
7172 // memmove/cpy/set of zero bytes is a noop.
7173 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7174 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7175
Chris Lattner00648e12004-10-12 04:52:52 +00007176 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007177 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007178 // Replace the instruction with just byte operations. We would
7179 // transform other cases to loads/stores, but we don't know if
7180 // alignment is sufficient.
7181 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007182 }
7183
Chris Lattner00648e12004-10-12 04:52:52 +00007184 // If we have a memmove and the source operation is a constant global,
7185 // then the source and dest pointers can't alias, so we can change this
7186 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007187 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007188 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7189 if (GVSrc->isConstant()) {
7190 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007191 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007192 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007193 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007194 Name = "llvm.memcpy.i32";
7195 else
7196 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007197 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007198 CI.getCalledFunction()->getFunctionType());
7199 CI.setOperand(0, MemCpy);
7200 Changed = true;
7201 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007202 }
Chris Lattner00648e12004-10-12 04:52:52 +00007203
Chris Lattner82f2ef22006-03-06 20:18:44 +00007204 // If we can determine a pointer alignment that is bigger than currently
7205 // set, update the alignment.
7206 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7207 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7208 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7209 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007210 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007211 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007212 Changed = true;
7213 }
7214 } else if (isa<MemSetInst>(MI)) {
7215 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007216 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007217 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007218 Changed = true;
7219 }
7220 }
7221
Chris Lattnerc66b2232006-01-13 20:11:04 +00007222 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007223 } else {
7224 switch (II->getIntrinsicID()) {
7225 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007226 case Intrinsic::ppc_altivec_lvx:
7227 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007228 case Intrinsic::x86_sse_loadu_ps:
7229 case Intrinsic::x86_sse2_loadu_pd:
7230 case Intrinsic::x86_sse2_loadu_dq:
7231 // Turn PPC lvx -> load if the pointer is known aligned.
7232 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007233 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007234 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007235 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007236 return new LoadInst(Ptr);
7237 }
7238 break;
7239 case Intrinsic::ppc_altivec_stvx:
7240 case Intrinsic::ppc_altivec_stvxl:
7241 // Turn stvx -> store if the pointer is known aligned.
7242 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007243 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007244 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7245 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007246 return new StoreInst(II->getOperand(1), Ptr);
7247 }
7248 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007249 case Intrinsic::x86_sse_storeu_ps:
7250 case Intrinsic::x86_sse2_storeu_pd:
7251 case Intrinsic::x86_sse2_storeu_dq:
7252 case Intrinsic::x86_sse2_storel_dq:
7253 // Turn X86 storeu -> store if the pointer is known aligned.
7254 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7255 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007256 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7257 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007258 return new StoreInst(II->getOperand(2), Ptr);
7259 }
7260 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007261
7262 case Intrinsic::x86_sse_cvttss2si: {
7263 // These intrinsics only demands the 0th element of its input vector. If
7264 // we can simplify the input based on that, do so now.
7265 uint64_t UndefElts;
7266 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7267 UndefElts)) {
7268 II->setOperand(1, V);
7269 return II;
7270 }
7271 break;
7272 }
7273
Chris Lattnere79d2492006-04-06 19:19:17 +00007274 case Intrinsic::ppc_altivec_vperm:
7275 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007276 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007277 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7278
7279 // Check that all of the elements are integer constants or undefs.
7280 bool AllEltsOk = true;
7281 for (unsigned i = 0; i != 16; ++i) {
7282 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7283 !isa<UndefValue>(Mask->getOperand(i))) {
7284 AllEltsOk = false;
7285 break;
7286 }
7287 }
7288
7289 if (AllEltsOk) {
7290 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007291 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7292 II->getOperand(1), Mask->getType(), CI);
7293 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7294 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007295 Value *Result = UndefValue::get(Op0->getType());
7296
7297 // Only extract each element once.
7298 Value *ExtractedElts[32];
7299 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7300
7301 for (unsigned i = 0; i != 16; ++i) {
7302 if (isa<UndefValue>(Mask->getOperand(i)))
7303 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007304 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007305 Idx &= 31; // Match the hardware behavior.
7306
7307 if (ExtractedElts[Idx] == 0) {
7308 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007309 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007310 InsertNewInstBefore(Elt, CI);
7311 ExtractedElts[Idx] = Elt;
7312 }
7313
7314 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007315 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007316 InsertNewInstBefore(cast<Instruction>(Result), CI);
7317 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007318 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007319 }
7320 }
7321 break;
7322
Chris Lattner503221f2006-01-13 21:28:09 +00007323 case Intrinsic::stackrestore: {
7324 // If the save is right next to the restore, remove the restore. This can
7325 // happen when variable allocas are DCE'd.
7326 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7327 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7328 BasicBlock::iterator BI = SS;
7329 if (&*++BI == II)
7330 return EraseInstFromFunction(CI);
7331 }
7332 }
7333
7334 // If the stack restore is in a return/unwind block and if there are no
7335 // allocas or calls between the restore and the return, nuke the restore.
7336 TerminatorInst *TI = II->getParent()->getTerminator();
7337 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7338 BasicBlock::iterator BI = II;
7339 bool CannotRemove = false;
7340 for (++BI; &*BI != TI; ++BI) {
7341 if (isa<AllocaInst>(BI) ||
7342 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7343 CannotRemove = true;
7344 break;
7345 }
7346 }
7347 if (!CannotRemove)
7348 return EraseInstFromFunction(CI);
7349 }
7350 break;
7351 }
7352 }
Chris Lattner00648e12004-10-12 04:52:52 +00007353 }
7354
Chris Lattnerc66b2232006-01-13 20:11:04 +00007355 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007356}
7357
7358// InvokeInst simplification
7359//
7360Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007361 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007362}
7363
Chris Lattneraec3d942003-10-07 22:32:43 +00007364// visitCallSite - Improvements for call and invoke instructions.
7365//
7366Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007367 bool Changed = false;
7368
7369 // If the callee is a constexpr cast of a function, attempt to move the cast
7370 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007371 if (transformConstExprCastCall(CS)) return 0;
7372
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007373 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007374
Chris Lattner61d9d812005-05-13 07:09:09 +00007375 if (Function *CalleeF = dyn_cast<Function>(Callee))
7376 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7377 Instruction *OldCall = CS.getInstruction();
7378 // If the call and callee calling conventions don't match, this call must
7379 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007380 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007381 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007382 if (!OldCall->use_empty())
7383 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7384 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7385 return EraseInstFromFunction(*OldCall);
7386 return 0;
7387 }
7388
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007389 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7390 // This instruction is not reachable, just remove it. We insert a store to
7391 // undef so that we know that this code is not reachable, despite the fact
7392 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007393 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007394 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007395 CS.getInstruction());
7396
7397 if (!CS.getInstruction()->use_empty())
7398 CS.getInstruction()->
7399 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7400
7401 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7402 // Don't break the CFG, insert a dummy cond branch.
7403 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007404 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007405 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007406 return EraseInstFromFunction(*CS.getInstruction());
7407 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007408
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007409 const PointerType *PTy = cast<PointerType>(Callee->getType());
7410 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7411 if (FTy->isVarArg()) {
7412 // See if we can optimize any arguments passed through the varargs area of
7413 // the call.
7414 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7415 E = CS.arg_end(); I != E; ++I)
7416 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7417 // If this cast does not effect the value passed through the varargs
7418 // area, we can eliminate the use of the cast.
7419 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007420 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007421 *I = Op;
7422 Changed = true;
7423 }
7424 }
7425 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007426
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007427 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007428}
7429
Chris Lattner970c33a2003-06-19 17:00:31 +00007430// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7431// attempt to move the cast to the arguments of the call/invoke.
7432//
7433bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7434 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7435 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007436 if (CE->getOpcode() != Instruction::BitCast ||
7437 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007438 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007439 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007440 Instruction *Caller = CS.getInstruction();
7441
7442 // Okay, this is a cast from a function to a different type. Unless doing so
7443 // would cause a type conversion of one of our arguments, change this call to
7444 // be a direct call with arguments casted to the appropriate types.
7445 //
7446 const FunctionType *FT = Callee->getFunctionType();
7447 const Type *OldRetTy = Caller->getType();
7448
Chris Lattner1f7942f2004-01-14 06:06:08 +00007449 // Check to see if we are changing the return type...
7450 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007451 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007452 // Conversion is ok if changing from pointer to int of same size.
7453 !(isa<PointerType>(FT->getReturnType()) &&
7454 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007455 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007456
7457 // If the callsite is an invoke instruction, and the return value is used by
7458 // a PHI node in a successor, we cannot change the return type of the call
7459 // because there is no place to put the cast instruction (without breaking
7460 // the critical edge). Bail out in this case.
7461 if (!Caller->use_empty())
7462 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7463 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7464 UI != E; ++UI)
7465 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7466 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007467 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007468 return false;
7469 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007470
7471 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7472 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007473
Chris Lattner970c33a2003-06-19 17:00:31 +00007474 CallSite::arg_iterator AI = CS.arg_begin();
7475 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7476 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007477 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007478 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007479 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007480 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007481 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007482 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007483 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7484 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007485 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007486 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007487 }
7488
7489 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007490 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007491 return false; // Do not delete arguments unless we have a function body...
7492
7493 // Okay, we decided that this is a safe thing to do: go ahead and start
7494 // inserting cast instructions as necessary...
7495 std::vector<Value*> Args;
7496 Args.reserve(NumActualArgs);
7497
7498 AI = CS.arg_begin();
7499 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7500 const Type *ParamTy = FT->getParamType(i);
7501 if ((*AI)->getType() == ParamTy) {
7502 Args.push_back(*AI);
7503 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007504 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007505 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007506 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007507 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007508 }
7509 }
7510
7511 // If the function takes more arguments than the call was taking, add them
7512 // now...
7513 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7514 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7515
7516 // If we are removing arguments to the function, emit an obnoxious warning...
7517 if (FT->getNumParams() < NumActualArgs)
7518 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007519 cerr << "WARNING: While resolving call to function '"
7520 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007521 } else {
7522 // Add all of the arguments in their promoted form to the arg list...
7523 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7524 const Type *PTy = getPromotedType((*AI)->getType());
7525 if (PTy != (*AI)->getType()) {
7526 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007527 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7528 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007529 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007530 InsertNewInstBefore(Cast, *Caller);
7531 Args.push_back(Cast);
7532 } else {
7533 Args.push_back(*AI);
7534 }
7535 }
7536 }
7537
7538 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007539 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007540
7541 Instruction *NC;
7542 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007543 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007544 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007545 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007546 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007547 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007548 if (cast<CallInst>(Caller)->isTailCall())
7549 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007550 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007551 }
7552
Chris Lattner6e0123b2007-02-11 01:23:03 +00007553 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007554 Value *NV = NC;
7555 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7556 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007557 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007558 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7559 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007560 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007561
7562 // If this is an invoke instruction, we should insert it after the first
7563 // non-phi, instruction in the normal successor block.
7564 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7565 BasicBlock::iterator I = II->getNormalDest()->begin();
7566 while (isa<PHINode>(I)) ++I;
7567 InsertNewInstBefore(NC, *I);
7568 } else {
7569 // Otherwise, it's a call, just insert cast right after the call instr
7570 InsertNewInstBefore(NC, *Caller);
7571 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007572 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007573 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007574 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007575 }
7576 }
7577
7578 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7579 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007580 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007581 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007582 return true;
7583}
7584
Chris Lattnercadac0c2006-11-01 04:51:18 +00007585/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7586/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7587/// and a single binop.
7588Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7589 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007590 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7591 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007592 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007593 Value *LHSVal = FirstInst->getOperand(0);
7594 Value *RHSVal = FirstInst->getOperand(1);
7595
7596 const Type *LHSType = LHSVal->getType();
7597 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007598
7599 // Scan to see if all operands are the same opcode, all have one use, and all
7600 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007601 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007602 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007603 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007604 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007605 // types or GEP's with different index types.
7606 I->getOperand(0)->getType() != LHSType ||
7607 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007608 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007609
7610 // If they are CmpInst instructions, check their predicates
7611 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7612 if (cast<CmpInst>(I)->getPredicate() !=
7613 cast<CmpInst>(FirstInst)->getPredicate())
7614 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007615
7616 // Keep track of which operand needs a phi node.
7617 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7618 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007619 }
7620
Chris Lattner4f218d52006-11-08 19:42:28 +00007621 // Otherwise, this is safe to transform, determine if it is profitable.
7622
7623 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7624 // Indexes are often folded into load/store instructions, so we don't want to
7625 // hide them behind a phi.
7626 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7627 return 0;
7628
Chris Lattnercadac0c2006-11-01 04:51:18 +00007629 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007630 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007631 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007632 if (LHSVal == 0) {
7633 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7634 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7635 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007636 InsertNewInstBefore(NewLHS, PN);
7637 LHSVal = NewLHS;
7638 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007639
7640 if (RHSVal == 0) {
7641 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7642 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7643 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007644 InsertNewInstBefore(NewRHS, PN);
7645 RHSVal = NewRHS;
7646 }
7647
Chris Lattnercd62f112006-11-08 19:29:23 +00007648 // Add all operands to the new PHIs.
7649 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7650 if (NewLHS) {
7651 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7652 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7653 }
7654 if (NewRHS) {
7655 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7656 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7657 }
7658 }
7659
Chris Lattnercadac0c2006-11-01 04:51:18 +00007660 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007661 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007662 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7663 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7664 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007665 else {
7666 assert(isa<GetElementPtrInst>(FirstInst));
7667 return new GetElementPtrInst(LHSVal, RHSVal);
7668 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007669}
7670
Chris Lattner14f82c72006-11-01 07:13:54 +00007671/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7672/// of the block that defines it. This means that it must be obvious the value
7673/// of the load is not changed from the point of the load to the end of the
7674/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007675///
7676/// Finally, it is safe, but not profitable, to sink a load targetting a
7677/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7678/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007679static bool isSafeToSinkLoad(LoadInst *L) {
7680 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7681
7682 for (++BBI; BBI != E; ++BBI)
7683 if (BBI->mayWriteToMemory())
7684 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007685
7686 // Check for non-address taken alloca. If not address-taken already, it isn't
7687 // profitable to do this xform.
7688 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7689 bool isAddressTaken = false;
7690 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7691 UI != E; ++UI) {
7692 if (isa<LoadInst>(UI)) continue;
7693 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7694 // If storing TO the alloca, then the address isn't taken.
7695 if (SI->getOperand(1) == AI) continue;
7696 }
7697 isAddressTaken = true;
7698 break;
7699 }
7700
7701 if (!isAddressTaken)
7702 return false;
7703 }
7704
Chris Lattner14f82c72006-11-01 07:13:54 +00007705 return true;
7706}
7707
Chris Lattner970c33a2003-06-19 17:00:31 +00007708
Chris Lattner7515cab2004-11-14 19:13:23 +00007709// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7710// operator and they all are only used by the PHI, PHI together their
7711// inputs, and do the operation once, to the result of the PHI.
7712Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7713 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7714
7715 // Scan the instruction, looking for input operations that can be folded away.
7716 // If all input operands to the phi are the same instruction (e.g. a cast from
7717 // the same type or "+42") we can pull the operation through the PHI, reducing
7718 // code size and simplifying code.
7719 Constant *ConstantOp = 0;
7720 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007721 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007722 if (isa<CastInst>(FirstInst)) {
7723 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007724 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007725 // Can fold binop, compare or shift here if the RHS is a constant,
7726 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007727 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007728 if (ConstantOp == 0)
7729 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007730 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7731 isVolatile = LI->isVolatile();
7732 // We can't sink the load if the loaded value could be modified between the
7733 // load and the PHI.
7734 if (LI->getParent() != PN.getIncomingBlock(0) ||
7735 !isSafeToSinkLoad(LI))
7736 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007737 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007738 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007739 return FoldPHIArgBinOpIntoPHI(PN);
7740 // Can't handle general GEPs yet.
7741 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007742 } else {
7743 return 0; // Cannot fold this operation.
7744 }
7745
7746 // Check to see if all arguments are the same operation.
7747 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7748 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7749 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007750 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007751 return 0;
7752 if (CastSrcTy) {
7753 if (I->getOperand(0)->getType() != CastSrcTy)
7754 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007755 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007756 // We can't sink the load if the loaded value could be modified between
7757 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007758 if (LI->isVolatile() != isVolatile ||
7759 LI->getParent() != PN.getIncomingBlock(i) ||
7760 !isSafeToSinkLoad(LI))
7761 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007762 } else if (I->getOperand(1) != ConstantOp) {
7763 return 0;
7764 }
7765 }
7766
7767 // Okay, they are all the same operation. Create a new PHI node of the
7768 // correct type, and PHI together all of the LHS's of the instructions.
7769 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7770 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007771 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007772
7773 Value *InVal = FirstInst->getOperand(0);
7774 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007775
7776 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007777 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7778 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7779 if (NewInVal != InVal)
7780 InVal = 0;
7781 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7782 }
7783
7784 Value *PhiVal;
7785 if (InVal) {
7786 // The new PHI unions all of the same values together. This is really
7787 // common, so we handle it intelligently here for compile-time speed.
7788 PhiVal = InVal;
7789 delete NewPN;
7790 } else {
7791 InsertNewInstBefore(NewPN, PN);
7792 PhiVal = NewPN;
7793 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007794
Chris Lattner7515cab2004-11-14 19:13:23 +00007795 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007796 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7797 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007798 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007799 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007800 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007801 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007802 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7803 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7804 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007805 else
Reid Spencer2341c222007-02-02 02:16:23 +00007806 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007807 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007808}
Chris Lattner48a44f72002-05-02 17:06:02 +00007809
Chris Lattner71536432005-01-17 05:10:15 +00007810/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7811/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007812static bool DeadPHICycle(PHINode *PN,
7813 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00007814 if (PN->use_empty()) return true;
7815 if (!PN->hasOneUse()) return false;
7816
7817 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007818 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00007819 return true;
7820
7821 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7822 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007823
Chris Lattner71536432005-01-17 05:10:15 +00007824 return false;
7825}
7826
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007827// PHINode simplification
7828//
Chris Lattner113f4f42002-06-25 16:13:24 +00007829Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007830 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007831 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007832
Owen Andersonae8aa642006-07-10 22:03:18 +00007833 if (Value *V = PN.hasConstantValue())
7834 return ReplaceInstUsesWith(PN, V);
7835
Owen Andersonae8aa642006-07-10 22:03:18 +00007836 // If all PHI operands are the same operation, pull them through the PHI,
7837 // reducing code size.
7838 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7839 PN.getIncomingValue(0)->hasOneUse())
7840 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7841 return Result;
7842
7843 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7844 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7845 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007846 if (PN.hasOneUse()) {
7847 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7848 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00007849 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00007850 PotentiallyDeadPHIs.insert(&PN);
7851 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7852 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7853 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007854
7855 // If this phi has a single use, and if that use just computes a value for
7856 // the next iteration of a loop, delete the phi. This occurs with unused
7857 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7858 // common case here is good because the only other things that catch this
7859 // are induction variable analysis (sometimes) and ADCE, which is only run
7860 // late.
7861 if (PHIUser->hasOneUse() &&
7862 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7863 PHIUser->use_back() == &PN) {
7864 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7865 }
7866 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007867
Chris Lattner91daeb52003-12-19 05:58:40 +00007868 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007869}
7870
Reid Spencer13bc5d72006-12-12 09:18:51 +00007871static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7872 Instruction *InsertPoint,
7873 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007874 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7875 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007876 // We must cast correctly to the pointer type. Ensure that we
7877 // sign extend the integer value if it is smaller as this is
7878 // used for address computation.
7879 Instruction::CastOps opcode =
7880 (VTySize < PtrSize ? Instruction::SExt :
7881 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7882 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007883}
7884
Chris Lattner48a44f72002-05-02 17:06:02 +00007885
Chris Lattner113f4f42002-06-25 16:13:24 +00007886Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007887 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007888 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007889 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007890 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007891 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007892
Chris Lattner81a7a232004-10-16 18:11:37 +00007893 if (isa<UndefValue>(GEP.getOperand(0)))
7894 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7895
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007896 bool HasZeroPointerIndex = false;
7897 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7898 HasZeroPointerIndex = C->isNullValue();
7899
7900 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007901 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007902
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007903 // Keep track of whether all indices are zero constants integers.
7904 bool AllZeroIndices = true;
7905
Chris Lattner69193f92004-04-05 01:30:19 +00007906 // Eliminate unneeded casts for indices.
7907 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007908
Chris Lattner2b2412d2004-04-07 18:38:20 +00007909 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007910 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
7911 // Track whether this GEP has all zero indices, if so, it doesn't move the
7912 // input pointer, it just changes its type.
7913 if (AllZeroIndices) {
7914 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
7915 AllZeroIndices = CI->isNullValue();
7916 else
7917 AllZeroIndices = false;
7918 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007919 if (isa<SequentialType>(*GTI)) {
7920 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007921 if (CI->getOpcode() == Instruction::ZExt ||
7922 CI->getOpcode() == Instruction::SExt) {
7923 const Type *SrcTy = CI->getOperand(0)->getType();
7924 // We can eliminate a cast from i32 to i64 iff the target
7925 // is a 32-bit pointer target.
7926 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7927 MadeChange = true;
7928 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007929 }
7930 }
7931 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007932 // If we are using a wider index than needed for this platform, shrink it
7933 // to what we need. If the incoming value needs a cast instruction,
7934 // insert it. This explicit cast can make subsequent optimizations more
7935 // obvious.
7936 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007937 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007938 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007939 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007940 MadeChange = true;
7941 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007942 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7943 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007944 GEP.setOperand(i, Op);
7945 MadeChange = true;
7946 }
Chris Lattner69193f92004-04-05 01:30:19 +00007947 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007948 }
Chris Lattner69193f92004-04-05 01:30:19 +00007949 if (MadeChange) return &GEP;
7950
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007951 // If this GEP instruction doesn't move the pointer, and if the input operand
7952 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
7953 // real input to the dest type.
7954 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
7955 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
7956 GEP.getType());
7957
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007958 // Combine Indices - If the source pointer to this getelementptr instruction
7959 // is a getelementptr instruction, combine the indices of the two
7960 // getelementptr instructions into a single instruction.
7961 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007962 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007963 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007964 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007965
7966 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007967 // Note that if our source is a gep chain itself that we wait for that
7968 // chain to be resolved before we perform this transformation. This
7969 // avoids us creating a TON of code in some cases.
7970 //
7971 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7972 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7973 return 0; // Wait until our source is folded to completion.
7974
Chris Lattneraf6094f2007-02-15 22:48:32 +00007975 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007976
7977 // Find out whether the last index in the source GEP is a sequential idx.
7978 bool EndsWithSequential = false;
7979 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7980 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007981 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007982
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007983 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007984 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007985 // Replace: gep (gep %P, long B), long A, ...
7986 // With: T = long A+B; gep %P, T, ...
7987 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007988 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007989 if (SO1 == Constant::getNullValue(SO1->getType())) {
7990 Sum = GO1;
7991 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7992 Sum = SO1;
7993 } else {
7994 // If they aren't the same type, convert both to an integer of the
7995 // target's pointer size.
7996 if (SO1->getType() != GO1->getType()) {
7997 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007998 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007999 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008000 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008001 } else {
8002 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008003 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008004 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008005 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008006
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008007 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008008 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008009 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008010 } else {
8011 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008012 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8013 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008014 }
8015 }
8016 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008017 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8018 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8019 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008020 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8021 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008022 }
Chris Lattner69193f92004-04-05 01:30:19 +00008023 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008024
8025 // Recycle the GEP we already have if possible.
8026 if (SrcGEPOperands.size() == 2) {
8027 GEP.setOperand(0, SrcGEPOperands[0]);
8028 GEP.setOperand(1, Sum);
8029 return &GEP;
8030 } else {
8031 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8032 SrcGEPOperands.end()-1);
8033 Indices.push_back(Sum);
8034 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8035 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008036 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008037 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008038 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008039 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008040 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8041 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008042 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8043 }
8044
8045 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008046 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8047 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008048
Chris Lattner5f667a62004-05-07 22:09:22 +00008049 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008050 // GEP of global variable. If all of the indices for this GEP are
8051 // constants, we can promote this to a constexpr instead of an instruction.
8052
8053 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008054 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008055 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8056 for (; I != E && isa<Constant>(*I); ++I)
8057 Indices.push_back(cast<Constant>(*I));
8058
8059 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008060 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8061 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008062
8063 // Replace all uses of the GEP with the new constexpr...
8064 return ReplaceInstUsesWith(GEP, CE);
8065 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008066 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008067 if (!isa<PointerType>(X->getType())) {
8068 // Not interesting. Source pointer must be a cast from pointer.
8069 } else if (HasZeroPointerIndex) {
8070 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8071 // into : GEP [10 x ubyte]* X, long 0, ...
8072 //
8073 // This occurs when the program declares an array extern like "int X[];"
8074 //
8075 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8076 const PointerType *XTy = cast<PointerType>(X->getType());
8077 if (const ArrayType *XATy =
8078 dyn_cast<ArrayType>(XTy->getElementType()))
8079 if (const ArrayType *CATy =
8080 dyn_cast<ArrayType>(CPTy->getElementType()))
8081 if (CATy->getElementType() == XATy->getElementType()) {
8082 // At this point, we know that the cast source type is a pointer
8083 // to an array of the same type as the destination pointer
8084 // array. Because the array type is never stepped over (there
8085 // is a leading zero) we can fold the cast into this GEP.
8086 GEP.setOperand(0, X);
8087 return &GEP;
8088 }
8089 } else if (GEP.getNumOperands() == 2) {
8090 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008091 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8092 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008093 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8094 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8095 if (isa<ArrayType>(SrcElTy) &&
8096 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8097 TD->getTypeSize(ResElTy)) {
8098 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008099 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008100 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008101 // V and GEP are both pointer types --> BitCast
8102 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008103 }
Chris Lattner2a893292005-09-13 18:36:04 +00008104
8105 // Transform things like:
8106 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8107 // (where tmp = 8*tmp2) into:
8108 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8109
8110 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008111 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008112 uint64_t ArrayEltSize =
8113 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8114
8115 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8116 // allow either a mul, shift, or constant here.
8117 Value *NewIdx = 0;
8118 ConstantInt *Scale = 0;
8119 if (ArrayEltSize == 1) {
8120 NewIdx = GEP.getOperand(1);
8121 Scale = ConstantInt::get(NewIdx->getType(), 1);
8122 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008123 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008124 Scale = CI;
8125 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8126 if (Inst->getOpcode() == Instruction::Shl &&
8127 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008128 unsigned ShAmt =
8129 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008130 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008131 NewIdx = Inst->getOperand(0);
8132 } else if (Inst->getOpcode() == Instruction::Mul &&
8133 isa<ConstantInt>(Inst->getOperand(1))) {
8134 Scale = cast<ConstantInt>(Inst->getOperand(1));
8135 NewIdx = Inst->getOperand(0);
8136 }
8137 }
8138
8139 // If the index will be to exactly the right offset with the scale taken
8140 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008141 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008142 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008143 Scale = ConstantInt::get(Scale->getType(),
8144 Scale->getZExtValue() / ArrayEltSize);
8145 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008146 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8147 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008148 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8149 NewIdx = InsertNewInstBefore(Sc, GEP);
8150 }
8151
8152 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008153 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008154 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008155 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008156 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8157 // The NewGEP must be pointer typed, so must the old one -> BitCast
8158 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008159 }
8160 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008161 }
Chris Lattnerca081252001-12-14 16:52:21 +00008162 }
8163
Chris Lattnerca081252001-12-14 16:52:21 +00008164 return 0;
8165}
8166
Chris Lattner1085bdf2002-11-04 16:18:53 +00008167Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8168 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8169 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008170 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8171 const Type *NewTy =
8172 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008173 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008174
8175 // Create and insert the replacement instruction...
8176 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008177 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008178 else {
8179 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008180 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008181 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008182
8183 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008184
Chris Lattner1085bdf2002-11-04 16:18:53 +00008185 // Scan to the end of the allocation instructions, to skip over a block of
8186 // allocas if possible...
8187 //
8188 BasicBlock::iterator It = New;
8189 while (isa<AllocationInst>(*It)) ++It;
8190
8191 // Now that I is pointing to the first non-allocation-inst in the block,
8192 // insert our getelementptr instruction...
8193 //
Reid Spencerc635f472006-12-31 05:48:39 +00008194 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008195 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8196 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008197
8198 // Now make everything use the getelementptr instead of the original
8199 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008200 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008201 } else if (isa<UndefValue>(AI.getArraySize())) {
8202 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008203 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008204
8205 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8206 // Note that we only do this for alloca's, because malloc should allocate and
8207 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008208 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008209 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008210 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8211
Chris Lattner1085bdf2002-11-04 16:18:53 +00008212 return 0;
8213}
8214
Chris Lattner8427bff2003-12-07 01:24:23 +00008215Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8216 Value *Op = FI.getOperand(0);
8217
8218 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8219 if (CastInst *CI = dyn_cast<CastInst>(Op))
8220 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8221 FI.setOperand(0, CI->getOperand(0));
8222 return &FI;
8223 }
8224
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008225 // free undef -> unreachable.
8226 if (isa<UndefValue>(Op)) {
8227 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008228 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008229 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008230 return EraseInstFromFunction(FI);
8231 }
8232
Chris Lattnerf3a36602004-02-28 04:57:37 +00008233 // If we have 'free null' delete the instruction. This can happen in stl code
8234 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008235 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008236 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008237
Chris Lattner8427bff2003-12-07 01:24:23 +00008238 return 0;
8239}
8240
8241
Chris Lattner72684fe2005-01-31 05:51:45 +00008242/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008243static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8244 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008245 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008246
8247 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008248 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008249 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008250
Reid Spencer31a4ef42007-01-22 05:51:25 +00008251 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008252 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008253 // If the source is an array, the code below will not succeed. Check to
8254 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8255 // constants.
8256 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8257 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8258 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008259 Value *Idxs[2];
8260 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8261 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008262 SrcTy = cast<PointerType>(CastOp->getType());
8263 SrcPTy = SrcTy->getElementType();
8264 }
8265
Reid Spencer31a4ef42007-01-22 05:51:25 +00008266 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008267 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008268 // Do not allow turning this into a load of an integer, which is then
8269 // casted to a pointer, this pessimizes pointer analysis a lot.
8270 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008271 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8272 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008273
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008274 // Okay, we are casting from one integer or pointer type to another of
8275 // the same size. Instead of casting the pointer before the load, cast
8276 // the result of the loaded value.
8277 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8278 CI->getName(),
8279 LI.isVolatile()),LI);
8280 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008281 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008282 }
Chris Lattner35e24772004-07-13 01:49:43 +00008283 }
8284 }
8285 return 0;
8286}
8287
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008288/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008289/// from this value cannot trap. If it is not obviously safe to load from the
8290/// specified pointer, we do a quick local scan of the basic block containing
8291/// ScanFrom, to determine if the address is already accessed.
8292static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8293 // If it is an alloca or global variable, it is always safe to load from.
8294 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8295
8296 // Otherwise, be a little bit agressive by scanning the local block where we
8297 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008298 // from/to. If so, the previous load or store would have already trapped,
8299 // so there is no harm doing an extra load (also, CSE will later eliminate
8300 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008301 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8302
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008303 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008304 --BBI;
8305
8306 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8307 if (LI->getOperand(0) == V) return true;
8308 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8309 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008310
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008311 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008312 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008313}
8314
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008315Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8316 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008317
Chris Lattnera9d84e32005-05-01 04:24:53 +00008318 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008319 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008320 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8321 return Res;
8322
8323 // None of the following transforms are legal for volatile loads.
8324 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008325
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008326 if (&LI.getParent()->front() != &LI) {
8327 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008328 // If the instruction immediately before this is a store to the same
8329 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008330 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8331 if (SI->getOperand(1) == LI.getOperand(0))
8332 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008333 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8334 if (LIB->getOperand(0) == LI.getOperand(0))
8335 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008336 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008337
8338 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8339 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8340 isa<UndefValue>(GEPI->getOperand(0))) {
8341 // Insert a new store to null instruction before the load to indicate
8342 // that this code is not reachable. We do this instead of inserting
8343 // an unreachable instruction directly because we cannot modify the
8344 // CFG.
8345 new StoreInst(UndefValue::get(LI.getType()),
8346 Constant::getNullValue(Op->getType()), &LI);
8347 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8348 }
8349
Chris Lattner81a7a232004-10-16 18:11:37 +00008350 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008351 // load null/undef -> undef
8352 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008353 // Insert a new store to null instruction before the load to indicate that
8354 // this code is not reachable. We do this instead of inserting an
8355 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008356 new StoreInst(UndefValue::get(LI.getType()),
8357 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008358 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008359 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008360
Chris Lattner81a7a232004-10-16 18:11:37 +00008361 // Instcombine load (constant global) into the value loaded.
8362 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008363 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008364 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008365
Chris Lattner81a7a232004-10-16 18:11:37 +00008366 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8368 if (CE->getOpcode() == Instruction::GetElementPtr) {
8369 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008370 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008371 if (Constant *V =
8372 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008373 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008374 if (CE->getOperand(0)->isNullValue()) {
8375 // Insert a new store to null instruction before the load to indicate
8376 // that this code is not reachable. We do this instead of inserting
8377 // an unreachable instruction directly because we cannot modify the
8378 // CFG.
8379 new StoreInst(UndefValue::get(LI.getType()),
8380 Constant::getNullValue(Op->getType()), &LI);
8381 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8382 }
8383
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008384 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008385 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8386 return Res;
8387 }
8388 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008389
Chris Lattnera9d84e32005-05-01 04:24:53 +00008390 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008391 // Change select and PHI nodes to select values instead of addresses: this
8392 // helps alias analysis out a lot, allows many others simplifications, and
8393 // exposes redundancy in the code.
8394 //
8395 // Note that we cannot do the transformation unless we know that the
8396 // introduced loads cannot trap! Something like this is valid as long as
8397 // the condition is always false: load (select bool %C, int* null, int* %G),
8398 // but it would not be valid if we transformed it to load from null
8399 // unconditionally.
8400 //
8401 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8402 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008403 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8404 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008405 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008406 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008407 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008408 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008409 return new SelectInst(SI->getCondition(), V1, V2);
8410 }
8411
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008412 // load (select (cond, null, P)) -> load P
8413 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8414 if (C->isNullValue()) {
8415 LI.setOperand(0, SI->getOperand(2));
8416 return &LI;
8417 }
8418
8419 // load (select (cond, P, null)) -> load P
8420 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8421 if (C->isNullValue()) {
8422 LI.setOperand(0, SI->getOperand(1));
8423 return &LI;
8424 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008425 }
8426 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008427 return 0;
8428}
8429
Reid Spencere928a152007-01-19 21:20:31 +00008430/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008431/// when possible.
8432static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8433 User *CI = cast<User>(SI.getOperand(1));
8434 Value *CastOp = CI->getOperand(0);
8435
8436 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8437 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8438 const Type *SrcPTy = SrcTy->getElementType();
8439
Reid Spencer31a4ef42007-01-22 05:51:25 +00008440 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008441 // If the source is an array, the code below will not succeed. Check to
8442 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8443 // constants.
8444 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8445 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8446 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008447 Value* Idxs[2];
8448 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8449 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008450 SrcTy = cast<PointerType>(CastOp->getType());
8451 SrcPTy = SrcTy->getElementType();
8452 }
8453
Reid Spencer9a4bed02007-01-20 23:35:48 +00008454 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8455 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8456 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008457
8458 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008459 // the same size. Instead of casting the pointer before
8460 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008461 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008462 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008463 Instruction::CastOps opcode = Instruction::BitCast;
8464 const Type* CastSrcTy = SIOp0->getType();
8465 const Type* CastDstTy = SrcPTy;
8466 if (isa<PointerType>(CastDstTy)) {
8467 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008468 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008469 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008470 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008471 opcode = Instruction::PtrToInt;
8472 }
8473 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008474 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008475 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008476 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008477 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8478 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008479 return new StoreInst(NewCast, CastOp);
8480 }
8481 }
8482 }
8483 return 0;
8484}
8485
Chris Lattner31f486c2005-01-31 05:36:43 +00008486Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8487 Value *Val = SI.getOperand(0);
8488 Value *Ptr = SI.getOperand(1);
8489
8490 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008491 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008492 ++NumCombined;
8493 return 0;
8494 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008495
8496 // If the RHS is an alloca with a single use, zapify the store, making the
8497 // alloca dead.
8498 if (Ptr->hasOneUse()) {
8499 if (isa<AllocaInst>(Ptr)) {
8500 EraseInstFromFunction(SI);
8501 ++NumCombined;
8502 return 0;
8503 }
8504
8505 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8506 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8507 GEP->getOperand(0)->hasOneUse()) {
8508 EraseInstFromFunction(SI);
8509 ++NumCombined;
8510 return 0;
8511 }
8512 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008513
Chris Lattner5997cf92006-02-08 03:25:32 +00008514 // Do really simple DSE, to catch cases where there are several consequtive
8515 // stores to the same location, separated by a few arithmetic operations. This
8516 // situation often occurs with bitfield accesses.
8517 BasicBlock::iterator BBI = &SI;
8518 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8519 --ScanInsts) {
8520 --BBI;
8521
8522 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8523 // Prev store isn't volatile, and stores to the same location?
8524 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8525 ++NumDeadStore;
8526 ++BBI;
8527 EraseInstFromFunction(*PrevSI);
8528 continue;
8529 }
8530 break;
8531 }
8532
Chris Lattnerdab43b22006-05-26 19:19:20 +00008533 // If this is a load, we have to stop. However, if the loaded value is from
8534 // the pointer we're loading and is producing the pointer we're storing,
8535 // then *this* store is dead (X = load P; store X -> P).
8536 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8537 if (LI == Val && LI->getOperand(0) == Ptr) {
8538 EraseInstFromFunction(SI);
8539 ++NumCombined;
8540 return 0;
8541 }
8542 // Otherwise, this is a load from some other location. Stores before it
8543 // may not be dead.
8544 break;
8545 }
8546
Chris Lattner5997cf92006-02-08 03:25:32 +00008547 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008548 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008549 break;
8550 }
8551
8552
8553 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008554
8555 // store X, null -> turns into 'unreachable' in SimplifyCFG
8556 if (isa<ConstantPointerNull>(Ptr)) {
8557 if (!isa<UndefValue>(Val)) {
8558 SI.setOperand(0, UndefValue::get(Val->getType()));
8559 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008560 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008561 ++NumCombined;
8562 }
8563 return 0; // Do not modify these!
8564 }
8565
8566 // store undef, Ptr -> noop
8567 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008568 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008569 ++NumCombined;
8570 return 0;
8571 }
8572
Chris Lattner72684fe2005-01-31 05:51:45 +00008573 // If the pointer destination is a cast, see if we can fold the cast into the
8574 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008575 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008576 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8577 return Res;
8578 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008579 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008580 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8581 return Res;
8582
Chris Lattner219175c2005-09-12 23:23:25 +00008583
8584 // If this store is the last instruction in the basic block, and if the block
8585 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008586 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008587 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8588 if (BI->isUnconditional()) {
8589 // Check to see if the successor block has exactly two incoming edges. If
8590 // so, see if the other predecessor contains a store to the same location.
8591 // if so, insert a PHI node (if needed) and move the stores down.
8592 BasicBlock *Dest = BI->getSuccessor(0);
8593
8594 pred_iterator PI = pred_begin(Dest);
8595 BasicBlock *Other = 0;
8596 if (*PI != BI->getParent())
8597 Other = *PI;
8598 ++PI;
8599 if (PI != pred_end(Dest)) {
8600 if (*PI != BI->getParent())
8601 if (Other)
8602 Other = 0;
8603 else
8604 Other = *PI;
8605 if (++PI != pred_end(Dest))
8606 Other = 0;
8607 }
8608 if (Other) { // If only one other pred...
8609 BBI = Other->getTerminator();
8610 // Make sure this other block ends in an unconditional branch and that
8611 // there is an instruction before the branch.
8612 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8613 BBI != Other->begin()) {
8614 --BBI;
8615 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8616
8617 // If this instruction is a store to the same location.
8618 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8619 // Okay, we know we can perform this transformation. Insert a PHI
8620 // node now if we need it.
8621 Value *MergedVal = OtherStore->getOperand(0);
8622 if (MergedVal != SI.getOperand(0)) {
8623 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8624 PN->reserveOperandSpace(2);
8625 PN->addIncoming(SI.getOperand(0), SI.getParent());
8626 PN->addIncoming(OtherStore->getOperand(0), Other);
8627 MergedVal = InsertNewInstBefore(PN, Dest->front());
8628 }
8629
8630 // Advance to a place where it is safe to insert the new store and
8631 // insert it.
8632 BBI = Dest->begin();
8633 while (isa<PHINode>(BBI)) ++BBI;
8634 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8635 OtherStore->isVolatile()), *BBI);
8636
8637 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008638 EraseInstFromFunction(SI);
8639 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008640 ++NumCombined;
8641 return 0;
8642 }
8643 }
8644 }
8645 }
8646
Chris Lattner31f486c2005-01-31 05:36:43 +00008647 return 0;
8648}
8649
8650
Chris Lattner9eef8a72003-06-04 04:46:00 +00008651Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8652 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008653 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008654 BasicBlock *TrueDest;
8655 BasicBlock *FalseDest;
8656 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8657 !isa<Constant>(X)) {
8658 // Swap Destinations and condition...
8659 BI.setCondition(X);
8660 BI.setSuccessor(0, FalseDest);
8661 BI.setSuccessor(1, TrueDest);
8662 return &BI;
8663 }
8664
Reid Spencer266e42b2006-12-23 06:05:41 +00008665 // Cannonicalize fcmp_one -> fcmp_oeq
8666 FCmpInst::Predicate FPred; Value *Y;
8667 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8668 TrueDest, FalseDest)))
8669 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8670 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8671 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008672 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008673 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8674 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008675 // Swap Destinations and condition...
8676 BI.setCondition(NewSCC);
8677 BI.setSuccessor(0, FalseDest);
8678 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008679 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008680 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008681 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008682 return &BI;
8683 }
8684
8685 // Cannonicalize icmp_ne -> icmp_eq
8686 ICmpInst::Predicate IPred;
8687 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8688 TrueDest, FalseDest)))
8689 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8690 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8691 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8692 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008693 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008694 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8695 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008696 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008697 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008698 BI.setSuccessor(0, FalseDest);
8699 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008700 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008701 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008702 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008703 return &BI;
8704 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008705
Chris Lattner9eef8a72003-06-04 04:46:00 +00008706 return 0;
8707}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008708
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008709Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8710 Value *Cond = SI.getCondition();
8711 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8712 if (I->getOpcode() == Instruction::Add)
8713 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8714 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8715 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008716 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008717 AddRHS));
8718 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008719 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008720 return &SI;
8721 }
8722 }
8723 return 0;
8724}
8725
Chris Lattner6bc98652006-03-05 00:22:33 +00008726/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8727/// is to leave as a vector operation.
8728static bool CheapToScalarize(Value *V, bool isConstant) {
8729 if (isa<ConstantAggregateZero>(V))
8730 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008731 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008732 if (isConstant) return true;
8733 // If all elts are the same, we can extract.
8734 Constant *Op0 = C->getOperand(0);
8735 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8736 if (C->getOperand(i) != Op0)
8737 return false;
8738 return true;
8739 }
8740 Instruction *I = dyn_cast<Instruction>(V);
8741 if (!I) return false;
8742
8743 // Insert element gets simplified to the inserted element or is deleted if
8744 // this is constant idx extract element and its a constant idx insertelt.
8745 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8746 isa<ConstantInt>(I->getOperand(2)))
8747 return true;
8748 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8749 return true;
8750 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8751 if (BO->hasOneUse() &&
8752 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8753 CheapToScalarize(BO->getOperand(1), isConstant)))
8754 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008755 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8756 if (CI->hasOneUse() &&
8757 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8758 CheapToScalarize(CI->getOperand(1), isConstant)))
8759 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008760
8761 return false;
8762}
8763
Chris Lattner945e4372007-02-14 05:52:17 +00008764/// Read and decode a shufflevector mask.
8765///
8766/// It turns undef elements into values that are larger than the number of
8767/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008768static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8769 unsigned NElts = SVI->getType()->getNumElements();
8770 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8771 return std::vector<unsigned>(NElts, 0);
8772 if (isa<UndefValue>(SVI->getOperand(2)))
8773 return std::vector<unsigned>(NElts, 2*NElts);
8774
8775 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008776 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008777 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8778 if (isa<UndefValue>(CP->getOperand(i)))
8779 Result.push_back(NElts*2); // undef -> 8
8780 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008781 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008782 return Result;
8783}
8784
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008785/// FindScalarElement - Given a vector and an element number, see if the scalar
8786/// value is already around as a register, for example if it were inserted then
8787/// extracted from the vector.
8788static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008789 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8790 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008791 unsigned Width = PTy->getNumElements();
8792 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008793 return UndefValue::get(PTy->getElementType());
8794
8795 if (isa<UndefValue>(V))
8796 return UndefValue::get(PTy->getElementType());
8797 else if (isa<ConstantAggregateZero>(V))
8798 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008799 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008800 return CP->getOperand(EltNo);
8801 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8802 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008803 if (!isa<ConstantInt>(III->getOperand(2)))
8804 return 0;
8805 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008806
8807 // If this is an insert to the element we are looking for, return the
8808 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008809 if (EltNo == IIElt)
8810 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008811
8812 // Otherwise, the insertelement doesn't modify the value, recurse on its
8813 // vector input.
8814 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008815 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008816 unsigned InEl = getShuffleMask(SVI)[EltNo];
8817 if (InEl < Width)
8818 return FindScalarElement(SVI->getOperand(0), InEl);
8819 else if (InEl < Width*2)
8820 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8821 else
8822 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008823 }
8824
8825 // Otherwise, we don't know.
8826 return 0;
8827}
8828
Robert Bocchinoa8352962006-01-13 22:48:06 +00008829Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008830
Chris Lattner92346c32006-03-31 18:25:14 +00008831 // If packed val is undef, replace extract with scalar undef.
8832 if (isa<UndefValue>(EI.getOperand(0)))
8833 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8834
8835 // If packed val is constant 0, replace extract with scalar 0.
8836 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8837 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8838
Reid Spencerd84d35b2007-02-15 02:26:10 +00008839 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008840 // If packed val is constant with uniform operands, replace EI
8841 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008842 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008843 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008844 if (C->getOperand(i) != op0) {
8845 op0 = 0;
8846 break;
8847 }
8848 if (op0)
8849 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008850 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008851
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008852 // If extracting a specified index from the vector, see if we can recursively
8853 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008854 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008855 // This instruction only demands the single element from the input vector.
8856 // If the input vector has a single use, simplify it based on this use
8857 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008858 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008859 if (EI.getOperand(0)->hasOneUse()) {
8860 uint64_t UndefElts;
8861 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008862 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008863 UndefElts)) {
8864 EI.setOperand(0, V);
8865 return &EI;
8866 }
8867 }
8868
Reid Spencere0fc4df2006-10-20 07:07:24 +00008869 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008870 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008871 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008872
Chris Lattner83f65782006-05-25 22:53:38 +00008873 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008874 if (I->hasOneUse()) {
8875 // Push extractelement into predecessor operation if legal and
8876 // profitable to do so
8877 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008878 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8879 if (CheapToScalarize(BO, isConstantElt)) {
8880 ExtractElementInst *newEI0 =
8881 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8882 EI.getName()+".lhs");
8883 ExtractElementInst *newEI1 =
8884 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8885 EI.getName()+".rhs");
8886 InsertNewInstBefore(newEI0, EI);
8887 InsertNewInstBefore(newEI1, EI);
8888 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8889 }
Reid Spencerde46e482006-11-02 20:25:50 +00008890 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008891 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008892 PointerType::get(EI.getType()), EI);
8893 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008894 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008895 InsertNewInstBefore(GEP, EI);
8896 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008897 }
8898 }
8899 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8900 // Extracting the inserted element?
8901 if (IE->getOperand(2) == EI.getOperand(1))
8902 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8903 // If the inserted and extracted elements are constants, they must not
8904 // be the same value, extract from the pre-inserted value instead.
8905 if (isa<Constant>(IE->getOperand(2)) &&
8906 isa<Constant>(EI.getOperand(1))) {
8907 AddUsesToWorkList(EI);
8908 EI.setOperand(0, IE->getOperand(0));
8909 return &EI;
8910 }
8911 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8912 // If this is extracting an element from a shufflevector, figure out where
8913 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008914 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8915 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008916 Value *Src;
8917 if (SrcIdx < SVI->getType()->getNumElements())
8918 Src = SVI->getOperand(0);
8919 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8920 SrcIdx -= SVI->getType()->getNumElements();
8921 Src = SVI->getOperand(1);
8922 } else {
8923 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008924 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008925 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008926 }
8927 }
Chris Lattner83f65782006-05-25 22:53:38 +00008928 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008929 return 0;
8930}
8931
Chris Lattner90951862006-04-16 00:51:47 +00008932/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8933/// elements from either LHS or RHS, return the shuffle mask and true.
8934/// Otherwise, return false.
8935static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8936 std::vector<Constant*> &Mask) {
8937 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8938 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008939 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008940
8941 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008942 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008943 return true;
8944 } else if (V == LHS) {
8945 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008946 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008947 return true;
8948 } else if (V == RHS) {
8949 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008950 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008951 return true;
8952 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8953 // If this is an insert of an extract from some other vector, include it.
8954 Value *VecOp = IEI->getOperand(0);
8955 Value *ScalarOp = IEI->getOperand(1);
8956 Value *IdxOp = IEI->getOperand(2);
8957
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008958 if (!isa<ConstantInt>(IdxOp))
8959 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008960 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008961
8962 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8963 // Okay, we can handle this if the vector we are insertinting into is
8964 // transitively ok.
8965 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8966 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008967 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008968 return true;
8969 }
8970 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8971 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008972 EI->getOperand(0)->getType() == V->getType()) {
8973 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008974 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008975
8976 // This must be extracting from either LHS or RHS.
8977 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8978 // Okay, we can handle this if the vector we are insertinting into is
8979 // transitively ok.
8980 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8981 // If so, update the mask to reflect the inserted value.
8982 if (EI->getOperand(0) == LHS) {
8983 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008984 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008985 } else {
8986 assert(EI->getOperand(0) == RHS);
8987 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008988 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008989
8990 }
8991 return true;
8992 }
8993 }
8994 }
8995 }
8996 }
8997 // TODO: Handle shufflevector here!
8998
8999 return false;
9000}
9001
9002/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9003/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9004/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009005static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009006 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009007 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009008 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009009 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009010 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009011
9012 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009013 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009014 return V;
9015 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009016 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009017 return V;
9018 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9019 // If this is an insert of an extract from some other vector, include it.
9020 Value *VecOp = IEI->getOperand(0);
9021 Value *ScalarOp = IEI->getOperand(1);
9022 Value *IdxOp = IEI->getOperand(2);
9023
9024 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9025 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9026 EI->getOperand(0)->getType() == V->getType()) {
9027 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009028 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9029 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009030
9031 // Either the extracted from or inserted into vector must be RHSVec,
9032 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009033 if (EI->getOperand(0) == RHS || RHS == 0) {
9034 RHS = EI->getOperand(0);
9035 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009036 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009037 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009038 return V;
9039 }
9040
Chris Lattner90951862006-04-16 00:51:47 +00009041 if (VecOp == RHS) {
9042 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009043 // Everything but the extracted element is replaced with the RHS.
9044 for (unsigned i = 0; i != NumElts; ++i) {
9045 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009046 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009047 }
9048 return V;
9049 }
Chris Lattner90951862006-04-16 00:51:47 +00009050
9051 // If this insertelement is a chain that comes from exactly these two
9052 // vectors, return the vector and the effective shuffle.
9053 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9054 return EI->getOperand(0);
9055
Chris Lattner39fac442006-04-15 01:39:45 +00009056 }
9057 }
9058 }
Chris Lattner90951862006-04-16 00:51:47 +00009059 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009060
9061 // Otherwise, can't do anything fancy. Return an identity vector.
9062 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009063 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009064 return V;
9065}
9066
9067Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9068 Value *VecOp = IE.getOperand(0);
9069 Value *ScalarOp = IE.getOperand(1);
9070 Value *IdxOp = IE.getOperand(2);
9071
9072 // If the inserted element was extracted from some other vector, and if the
9073 // indexes are constant, try to turn this into a shufflevector operation.
9074 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9075 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9076 EI->getOperand(0)->getType() == IE.getType()) {
9077 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009078 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9079 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009080
9081 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9082 return ReplaceInstUsesWith(IE, VecOp);
9083
9084 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9085 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9086
9087 // If we are extracting a value from a vector, then inserting it right
9088 // back into the same place, just use the input vector.
9089 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9090 return ReplaceInstUsesWith(IE, VecOp);
9091
9092 // We could theoretically do this for ANY input. However, doing so could
9093 // turn chains of insertelement instructions into a chain of shufflevector
9094 // instructions, and right now we do not merge shufflevectors. As such,
9095 // only do this in a situation where it is clear that there is benefit.
9096 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9097 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9098 // the values of VecOp, except then one read from EIOp0.
9099 // Build a new shuffle mask.
9100 std::vector<Constant*> Mask;
9101 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009102 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009103 else {
9104 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009105 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009106 NumVectorElts));
9107 }
Reid Spencerc635f472006-12-31 05:48:39 +00009108 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009109 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009110 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009111 }
9112
9113 // If this insertelement isn't used by some other insertelement, turn it
9114 // (and any insertelements it points to), into one big shuffle.
9115 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9116 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009117 Value *RHS = 0;
9118 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9119 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9120 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009121 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009122 }
9123 }
9124 }
9125
9126 return 0;
9127}
9128
9129
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009130Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9131 Value *LHS = SVI.getOperand(0);
9132 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009133 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009134
9135 bool MadeChange = false;
9136
Chris Lattner2deeaea2006-10-05 06:55:50 +00009137 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009138 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009139 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9140
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009141 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009142 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009143 if (isa<UndefValue>(SVI.getOperand(1))) {
9144 // Scan to see if there are any references to the RHS. If so, replace them
9145 // with undef element refs and set MadeChange to true.
9146 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9147 if (Mask[i] >= e && Mask[i] != 2*e) {
9148 Mask[i] = 2*e;
9149 MadeChange = true;
9150 }
9151 }
9152
9153 if (MadeChange) {
9154 // Remap any references to RHS to use LHS.
9155 std::vector<Constant*> Elts;
9156 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9157 if (Mask[i] == 2*e)
9158 Elts.push_back(UndefValue::get(Type::Int32Ty));
9159 else
9160 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9161 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009162 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009163 }
9164 }
Chris Lattner39fac442006-04-15 01:39:45 +00009165
Chris Lattner12249be2006-05-25 23:48:38 +00009166 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9167 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9168 if (LHS == RHS || isa<UndefValue>(LHS)) {
9169 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009170 // shuffle(undef,undef,mask) -> undef.
9171 return ReplaceInstUsesWith(SVI, LHS);
9172 }
9173
Chris Lattner12249be2006-05-25 23:48:38 +00009174 // Remap any references to RHS to use LHS.
9175 std::vector<Constant*> Elts;
9176 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009177 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009178 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009179 else {
9180 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9181 (Mask[i] < e && isa<UndefValue>(LHS)))
9182 Mask[i] = 2*e; // Turn into undef.
9183 else
9184 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009185 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009186 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009187 }
Chris Lattner12249be2006-05-25 23:48:38 +00009188 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009189 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009190 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009191 LHS = SVI.getOperand(0);
9192 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009193 MadeChange = true;
9194 }
9195
Chris Lattner0e477162006-05-26 00:29:06 +00009196 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009197 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009198
Chris Lattner12249be2006-05-25 23:48:38 +00009199 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9200 if (Mask[i] >= e*2) continue; // Ignore undef values.
9201 // Is this an identity shuffle of the LHS value?
9202 isLHSID &= (Mask[i] == i);
9203
9204 // Is this an identity shuffle of the RHS value?
9205 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009206 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009207
Chris Lattner12249be2006-05-25 23:48:38 +00009208 // Eliminate identity shuffles.
9209 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9210 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009211
Chris Lattner0e477162006-05-26 00:29:06 +00009212 // If the LHS is a shufflevector itself, see if we can combine it with this
9213 // one without producing an unusual shuffle. Here we are really conservative:
9214 // we are absolutely afraid of producing a shuffle mask not in the input
9215 // program, because the code gen may not be smart enough to turn a merged
9216 // shuffle into two specific shuffles: it may produce worse code. As such,
9217 // we only merge two shuffles if the result is one of the two input shuffle
9218 // masks. In this case, merging the shuffles just removes one instruction,
9219 // which we know is safe. This is good for things like turning:
9220 // (splat(splat)) -> splat.
9221 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9222 if (isa<UndefValue>(RHS)) {
9223 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9224
9225 std::vector<unsigned> NewMask;
9226 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9227 if (Mask[i] >= 2*e)
9228 NewMask.push_back(2*e);
9229 else
9230 NewMask.push_back(LHSMask[Mask[i]]);
9231
9232 // If the result mask is equal to the src shuffle or this shuffle mask, do
9233 // the replacement.
9234 if (NewMask == LHSMask || NewMask == Mask) {
9235 std::vector<Constant*> Elts;
9236 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9237 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009238 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009239 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009240 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009241 }
9242 }
9243 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9244 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009245 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009246 }
9247 }
9248 }
Chris Lattner4284f642007-01-30 22:32:46 +00009249
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009250 return MadeChange ? &SVI : 0;
9251}
9252
9253
Robert Bocchinoa8352962006-01-13 22:48:06 +00009254
Chris Lattner39c98bb2004-12-08 23:43:58 +00009255
9256/// TryToSinkInstruction - Try to move the specified instruction from its
9257/// current block into the beginning of DestBlock, which can only happen if it's
9258/// safe to move the instruction past all of the instructions between it and the
9259/// end of its block.
9260static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9261 assert(I->hasOneUse() && "Invariants didn't hold!");
9262
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009263 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9264 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009265
Chris Lattner39c98bb2004-12-08 23:43:58 +00009266 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009267 if (isa<AllocaInst>(I) && I->getParent() ==
9268 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009269 return false;
9270
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009271 // We can only sink load instructions if there is nothing between the load and
9272 // the end of block that could change the value.
9273 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009274 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9275 Scan != E; ++Scan)
9276 if (Scan->mayWriteToMemory())
9277 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009278 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009279
9280 BasicBlock::iterator InsertPos = DestBlock->begin();
9281 while (isa<PHINode>(InsertPos)) ++InsertPos;
9282
Chris Lattner9f269e42005-08-08 19:11:57 +00009283 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009284 ++NumSunkInst;
9285 return true;
9286}
9287
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009288
9289/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9290/// all reachable code to the worklist.
9291///
9292/// This has a couple of tricks to make the code faster and more powerful. In
9293/// particular, we constant fold and DCE instructions as we go, to avoid adding
9294/// them to the worklist (this significantly speeds up instcombine on code where
9295/// many instructions are dead or constant). Additionally, if we find a branch
9296/// whose condition is a known constant, we only visit the reachable successors.
9297///
9298static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009299 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009300 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009301 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009302 std::vector<BasicBlock*> Worklist;
9303 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009304
Chris Lattner12b89cc2007-03-23 19:17:18 +00009305 while (!Worklist.empty()) {
9306 BB = Worklist.back();
9307 Worklist.pop_back();
9308
9309 // We have now visited this block! If we've already been here, ignore it.
9310 if (!Visited.insert(BB)) continue;
9311
9312 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9313 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009314
Chris Lattner12b89cc2007-03-23 19:17:18 +00009315 // DCE instruction if trivially dead.
9316 if (isInstructionTriviallyDead(Inst)) {
9317 ++NumDeadInst;
9318 DOUT << "IC: DCE: " << *Inst;
9319 Inst->eraseFromParent();
9320 continue;
9321 }
9322
9323 // ConstantProp instruction if trivially constant.
9324 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9325 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9326 Inst->replaceAllUsesWith(C);
9327 ++NumConstProp;
9328 Inst->eraseFromParent();
9329 continue;
9330 }
9331
9332 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009333 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009334
9335 // Recursively visit successors. If this is a branch or switch on a
9336 // constant, only visit the reachable successor.
9337 TerminatorInst *TI = BB->getTerminator();
9338 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9339 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9340 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9341 Worklist.push_back(BI->getSuccessor(!CondVal));
9342 continue;
9343 }
9344 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9345 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9346 // See if this is an explicit destination.
9347 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9348 if (SI->getCaseValue(i) == Cond) {
9349 Worklist.push_back(SI->getSuccessor(i));
9350 continue;
9351 }
9352
9353 // Otherwise it is the default destination.
9354 Worklist.push_back(SI->getSuccessor(0));
9355 continue;
9356 }
9357 }
9358
9359 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9360 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009361 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009362}
9363
Chris Lattner960a5432007-03-03 02:04:50 +00009364bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009365 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009366 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009367
9368 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9369 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009370
Chris Lattner4ed40f72005-07-07 20:40:38 +00009371 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009372 // Do a depth-first traversal of the function, populate the worklist with
9373 // the reachable instructions. Ignore blocks that are not reachable. Keep
9374 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009375 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009376 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009377
Chris Lattner4ed40f72005-07-07 20:40:38 +00009378 // Do a quick scan over the function. If we find any blocks that are
9379 // unreachable, remove any instructions inside of them. This prevents
9380 // the instcombine code from having to deal with some bad special cases.
9381 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9382 if (!Visited.count(BB)) {
9383 Instruction *Term = BB->getTerminator();
9384 while (Term != BB->begin()) { // Remove instrs bottom-up
9385 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009386
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009387 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009388 ++NumDeadInst;
9389
9390 if (!I->use_empty())
9391 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9392 I->eraseFromParent();
9393 }
9394 }
9395 }
Chris Lattnerca081252001-12-14 16:52:21 +00009396
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009397 while (!Worklist.empty()) {
9398 Instruction *I = RemoveOneFromWorkList();
9399 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009400
Chris Lattner1443bc52006-05-11 17:11:52 +00009401 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009402 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009403 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009404 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009405 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009406 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009407
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009408 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009409
9410 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009411 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009412 continue;
9413 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009414
Chris Lattner1443bc52006-05-11 17:11:52 +00009415 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009416 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009417 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009418
Chris Lattner1443bc52006-05-11 17:11:52 +00009419 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009420 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009421 ReplaceInstUsesWith(*I, C);
9422
Chris Lattner99f48c62002-09-02 04:59:56 +00009423 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009424 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009425 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009426 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009427 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009428
Chris Lattner39c98bb2004-12-08 23:43:58 +00009429 // See if we can trivially sink this instruction to a successor basic block.
9430 if (I->hasOneUse()) {
9431 BasicBlock *BB = I->getParent();
9432 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9433 if (UserParent != BB) {
9434 bool UserIsSuccessor = false;
9435 // See if the user is one of our successors.
9436 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9437 if (*SI == UserParent) {
9438 UserIsSuccessor = true;
9439 break;
9440 }
9441
9442 // If the user is one of our immediate successors, and if that successor
9443 // only has us as a predecessors (we'd have to split the critical edge
9444 // otherwise), we can keep going.
9445 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9446 next(pred_begin(UserParent)) == pred_end(UserParent))
9447 // Okay, the CFG is simple enough, try to sink this instruction.
9448 Changed |= TryToSinkInstruction(I, UserParent);
9449 }
9450 }
9451
Chris Lattnerca081252001-12-14 16:52:21 +00009452 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009453#ifndef NDEBUG
9454 std::string OrigI;
9455#endif
9456 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009457 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009458 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009459 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009460 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009461 DOUT << "IC: Old = " << *I
9462 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009463
Chris Lattner396dbfe2004-06-09 05:08:07 +00009464 // Everything uses the new instruction now.
9465 I->replaceAllUsesWith(Result);
9466
9467 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009468 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009469 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009470
Chris Lattner6e0123b2007-02-11 01:23:03 +00009471 // Move the name to the new instruction first.
9472 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009473
9474 // Insert the new instruction into the basic block...
9475 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009476 BasicBlock::iterator InsertPos = I;
9477
9478 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9479 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9480 ++InsertPos;
9481
9482 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009483
Chris Lattner63d75af2004-05-01 23:27:23 +00009484 // Make sure that we reprocess all operands now that we reduced their
9485 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009486 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009487
Chris Lattner396dbfe2004-06-09 05:08:07 +00009488 // Instructions can end up on the worklist more than once. Make sure
9489 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009490 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009491
9492 // Erase the old instruction.
9493 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009494 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009495#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009496 DOUT << "IC: Mod = " << OrigI
9497 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009498#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009499
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009500 // If the instruction was modified, it's possible that it is now dead.
9501 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009502 if (isInstructionTriviallyDead(I)) {
9503 // Make sure we process all operands now that we are reducing their
9504 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009505 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009506
Chris Lattner63d75af2004-05-01 23:27:23 +00009507 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009508 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009509 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009510 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009511 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009512 AddToWorkList(I);
9513 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009514 }
Chris Lattner053c0932002-05-14 15:24:07 +00009515 }
Chris Lattner260ab202002-04-18 17:39:14 +00009516 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009517 }
9518 }
9519
Chris Lattner960a5432007-03-03 02:04:50 +00009520 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009521 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009522}
9523
Chris Lattner960a5432007-03-03 02:04:50 +00009524
9525bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009526 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9527
Chris Lattner960a5432007-03-03 02:04:50 +00009528 bool EverMadeChange = false;
9529
9530 // Iterate while there is work to do.
9531 unsigned Iteration = 0;
9532 while (DoOneIteration(F, Iteration++))
9533 EverMadeChange = true;
9534 return EverMadeChange;
9535}
9536
Brian Gaeke38b79e82004-07-27 17:43:21 +00009537FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009538 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009539}
Brian Gaeke960707c2003-11-11 22:41:34 +00009540