blob: d72783a0de6944f239e079af51ff7214af5429f6 [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.
Reid Spencer624766f2007-03-25 19:55:33 +0000543 Constant *One = ConstantInt::get(V->getType(), 1);
544 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 return I->getOperand(0);
546 }
547 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000548 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000549}
Chris Lattner31ae8632002-08-14 17:51:49 +0000550
Chris Lattner0798af32005-01-13 20:14:25 +0000551/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
552/// expression, return it.
553static User *dyn_castGetElementPtr(Value *V) {
554 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556 if (CE->getOpcode() == Instruction::GetElementPtr)
557 return cast<User>(V);
558 return false;
559}
560
Reid Spencer80263aa2007-03-25 05:33:51 +0000561/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000562static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000563 APInt Val(C->getValue());
564 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000565}
Reid Spencer80263aa2007-03-25 05:33:51 +0000566/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000567static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000568 APInt Val(C->getValue());
569 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000570}
571/// Add - Add two ConstantInts together
572static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
573 return ConstantInt::get(C1->getValue() + C2->getValue());
574}
575/// And - Bitwise AND two ConstantInts together
576static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
577 return ConstantInt::get(C1->getValue() & C2->getValue());
578}
579/// Subtract - Subtract one ConstantInt from another
580static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
581 return ConstantInt::get(C1->getValue() - C2->getValue());
582}
583/// Multiply - Multiply two ConstantInts together
584static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
585 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000586}
587
Chris Lattner4534dd592006-02-09 07:38:58 +0000588/// ComputeMaskedBits - Determine which of the bits specified in Mask are
589/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000590/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
591/// processing.
592/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
593/// we cannot optimize based on the assumption that it is zero without changing
594/// it to be an explicit zero. If we don't change it to zero, other code could
595/// optimized based on the contradictory assumption that it is non-zero.
596/// Because instcombine aggressively folds operations with undef args anyway,
597/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000598static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000599 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000600 assert(V && "No Value?");
601 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000602 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000603 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000604 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000605 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000606 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000607 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
608 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000609 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000610 KnownZero = ~KnownOne & Mask;
611 return;
612 }
613
Reid Spenceraa696402007-03-08 01:46:38 +0000614 if (Depth == 6 || Mask == 0)
615 return; // Limit search depth.
616
617 Instruction *I = dyn_cast<Instruction>(V);
618 if (!I) return;
619
Zhou Shengaf4341d2007-03-13 02:23:10 +0000620 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000621 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000622
623 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000624 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000625 // If either the LHS or the RHS are Zero, the result is zero.
626 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000627 APInt Mask2(Mask & ~KnownZero);
628 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000629 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
630 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
631
632 // Output known-1 bits are only known if set in both the LHS & RHS.
633 KnownOne &= KnownOne2;
634 // Output known-0 are known to be clear if zero in either the LHS | RHS.
635 KnownZero |= KnownZero2;
636 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000637 }
638 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000639 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000640 APInt Mask2(Mask & ~KnownOne);
641 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000642 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
643 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
644
645 // Output known-0 bits are only known if clear in both the LHS & RHS.
646 KnownZero &= KnownZero2;
647 // Output known-1 are known to be set if set in either the LHS | RHS.
648 KnownOne |= KnownOne2;
649 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000650 }
Reid Spenceraa696402007-03-08 01:46:38 +0000651 case Instruction::Xor: {
652 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
655 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
656
657 // Output known-0 bits are known if clear or set in both the LHS & RHS.
658 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
659 // Output known-1 are known to be set if set in only one of the LHS, RHS.
660 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
661 KnownZero = KnownZeroOut;
662 return;
663 }
664 case Instruction::Select:
665 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
666 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
667 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
668 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
669
670 // Only known if known in both the LHS and RHS.
671 KnownOne &= KnownOne2;
672 KnownZero &= KnownZero2;
673 return;
674 case Instruction::FPTrunc:
675 case Instruction::FPExt:
676 case Instruction::FPToUI:
677 case Instruction::FPToSI:
678 case Instruction::SIToFP:
679 case Instruction::PtrToInt:
680 case Instruction::UIToFP:
681 case Instruction::IntToPtr:
682 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000683 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000684 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000685 uint32_t SrcBitWidth =
686 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000687 APInt MaskIn(Mask);
688 MaskIn.zext(SrcBitWidth);
689 KnownZero.zext(SrcBitWidth);
690 KnownOne.zext(SrcBitWidth);
691 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000692 KnownZero.trunc(BitWidth);
693 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000694 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000695 }
Reid Spenceraa696402007-03-08 01:46:38 +0000696 case Instruction::BitCast: {
697 const Type *SrcTy = I->getOperand(0)->getType();
698 if (SrcTy->isInteger()) {
699 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
700 return;
701 }
702 break;
703 }
704 case Instruction::ZExt: {
705 // Compute the bits in the result that are not present in the input.
706 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000707 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000708
Zhou Sheng57e3f732007-03-28 02:19:03 +0000709 APInt MaskIn(Mask);
710 MaskIn.trunc(SrcBitWidth);
711 KnownZero.trunc(SrcBitWidth);
712 KnownOne.trunc(SrcBitWidth);
713 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000714 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
715 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000716 KnownZero.zext(BitWidth);
717 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000718 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000719 return;
720 }
721 case Instruction::SExt: {
722 // Compute the bits in the result that are not present in the input.
723 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000724 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000725
Zhou Sheng57e3f732007-03-28 02:19:03 +0000726 APInt MaskIn(Mask);
727 MaskIn.trunc(SrcBitWidth);
728 KnownZero.trunc(SrcBitWidth);
729 KnownOne.trunc(SrcBitWidth);
730 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000732 KnownZero.zext(BitWidth);
733 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000734
735 // If the sign bit of the input is known set or clear, then we know the
736 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000737 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000738 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000739 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000740 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000741 return;
742 }
743 case Instruction::Shl:
744 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
745 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
746 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencerd8aad612007-03-25 02:03:12 +0000747 APInt Mask2(Mask.lshr(ShiftAmt));
748 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000749 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000750 KnownZero <<= ShiftAmt;
751 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000752 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000753 return;
754 }
755 break;
756 case Instruction::LShr:
757 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
758 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
759 // Compute the new bits that are at the top now.
760 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spenceraa696402007-03-08 01:46:38 +0000761
762 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000763 APInt Mask2(Mask.shl(ShiftAmt));
764 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000765 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
766 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
767 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000768 // high bits known zero.
769 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000770 return;
771 }
772 break;
773 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000774 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000775 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
776 // Compute the new bits that are at the top now.
777 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spenceraa696402007-03-08 01:46:38 +0000778
779 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000780 APInt Mask2(Mask.shl(ShiftAmt));
781 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000782 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
783 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
784 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
785
Zhou Sheng57e3f732007-03-28 02:19:03 +0000786 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
787 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000788 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000789 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000790 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000791 return;
792 }
793 break;
794 }
795}
796
Reid Spencerbb5741f2007-03-08 01:52:58 +0000797/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
798/// this predicate to simplify operations downstream. Mask is known to be zero
799/// for bits that V cannot have.
800static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000801 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000802 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
803 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
804 return (KnownZero & Mask) == Mask;
805}
806
Chris Lattner0157e7f2006-02-11 09:31:47 +0000807/// ShrinkDemandedConstant - Check to see if the specified operand of the
808/// specified instruction is a constant integer. If so, check to see if there
809/// are any bits set in the constant that are not demanded. If so, shrink the
810/// constant and return true.
811static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000812 APInt Demanded) {
813 assert(I && "No instruction?");
814 assert(OpNo < I->getNumOperands() && "Operand index too large");
815
816 // If the operand is not a constant integer, nothing to do.
817 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
818 if (!OpC) return false;
819
820 // If there are no bits set that aren't demanded, nothing to do.
821 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
822 if ((~Demanded & OpC->getValue()) == 0)
823 return false;
824
825 // This instruction is producing bits that are not demanded. Shrink the RHS.
826 Demanded &= OpC->getValue();
827 I->setOperand(OpNo, ConstantInt::get(Demanded));
828 return true;
829}
830
Chris Lattneree0f2802006-02-12 02:07:56 +0000831// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
832// set of known zero and one bits, compute the maximum and minimum values that
833// could have the specified known zero and known one bits, returning them in
834// min/max.
835static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000836 const APInt& KnownZero,
837 const APInt& KnownOne,
838 APInt& Min, APInt& Max) {
839 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
840 assert(KnownZero.getBitWidth() == BitWidth &&
841 KnownOne.getBitWidth() == BitWidth &&
842 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
843 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000844 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000845
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000846 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +0000847
848 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
849 // bit if it is unknown.
850 Min = KnownOne;
851 Max = KnownOne|UnknownBits;
852
Zhou Shengc2d33092007-03-28 05:15:57 +0000853 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Chris Lattneree0f2802006-02-12 02:07:56 +0000854 Min |= SignBit;
855 Max &= ~SignBit;
856 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000857}
858
859// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
860// a set of known zero and one bits, compute the maximum and minimum values that
861// could have the specified known zero and known one bits, returning them in
862// min/max.
863static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000864 const APInt& KnownZero,
865 const APInt& KnownOne,
866 APInt& Min,
867 APInt& Max) {
868 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
869 assert(KnownZero.getBitWidth() == BitWidth &&
870 KnownOne.getBitWidth() == BitWidth &&
871 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
872 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000873 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000874
875 // The minimum value is when the unknown bits are all zeros.
876 Min = KnownOne;
877 // The maximum value is when the unknown bits are all ones.
878 Max = KnownOne|UnknownBits;
879}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000880
Reid Spencer1791f232007-03-12 17:25:59 +0000881/// SimplifyDemandedBits - This function attempts to replace V with a simpler
882/// value based on the demanded bits. When this function is called, it is known
883/// that only the bits set in DemandedMask of the result of V are ever used
884/// downstream. Consequently, depending on the mask and V, it may be possible
885/// to replace V with a constant or one of its operands. In such cases, this
886/// function does the replacement and returns true. In all other cases, it
887/// returns false after analyzing the expression and setting KnownOne and known
888/// to be one in the expression. KnownZero contains all the bits that are known
889/// to be zero in the expression. These are provided to potentially allow the
890/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
891/// the expression. KnownOne and KnownZero always follow the invariant that
892/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
893/// the bits in KnownOne and KnownZero may only be accurate for those bits set
894/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
895/// and KnownOne must all be the same.
896bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
897 APInt& KnownZero, APInt& KnownOne,
898 unsigned Depth) {
899 assert(V != 0 && "Null pointer of Value???");
900 assert(Depth <= 6 && "Limit Search Depth");
901 uint32_t BitWidth = DemandedMask.getBitWidth();
902 const IntegerType *VTy = cast<IntegerType>(V->getType());
903 assert(VTy->getBitWidth() == BitWidth &&
904 KnownZero.getBitWidth() == BitWidth &&
905 KnownOne.getBitWidth() == BitWidth &&
906 "Value *V, DemandedMask, KnownZero and KnownOne \
907 must have same BitWidth");
908 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
909 // We know all of the bits for a constant!
910 KnownOne = CI->getValue() & DemandedMask;
911 KnownZero = ~KnownOne & DemandedMask;
912 return false;
913 }
914
Zhou Shengb9128442007-03-14 03:21:24 +0000915 KnownZero.clear();
916 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000917 if (!V->hasOneUse()) { // Other users may use these bits.
918 if (Depth != 0) { // Not at the root.
919 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
920 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
921 return false;
922 }
923 // If this is the root being simplified, allow it to have multiple uses,
924 // just set the DemandedMask to all bits.
925 DemandedMask = APInt::getAllOnesValue(BitWidth);
926 } else if (DemandedMask == 0) { // Not demanding any bits from V.
927 if (V != UndefValue::get(VTy))
928 return UpdateValueUsesWith(V, UndefValue::get(VTy));
929 return false;
930 } else if (Depth == 6) { // Limit search depth.
931 return false;
932 }
933
934 Instruction *I = dyn_cast<Instruction>(V);
935 if (!I) return false; // Only analyze instructions.
936
Reid Spencer1791f232007-03-12 17:25:59 +0000937 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
938 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
939 switch (I->getOpcode()) {
940 default: break;
941 case Instruction::And:
942 // If either the LHS or the RHS are Zero, the result is zero.
943 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1))
945 return true;
946 assert((RHSKnownZero & RHSKnownOne) == 0 &&
947 "Bits known to be one AND zero?");
948
949 // If something is known zero on the RHS, the bits aren't demanded on the
950 // LHS.
951 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
952 LHSKnownZero, LHSKnownOne, Depth+1))
953 return true;
954 assert((LHSKnownZero & LHSKnownOne) == 0 &&
955 "Bits known to be one AND zero?");
956
957 // If all of the demanded bits are known 1 on one side, return the other.
958 // These bits cannot contribute to the result of the 'and'.
959 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
960 (DemandedMask & ~LHSKnownZero))
961 return UpdateValueUsesWith(I, I->getOperand(0));
962 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
963 (DemandedMask & ~RHSKnownZero))
964 return UpdateValueUsesWith(I, I->getOperand(1));
965
966 // If all of the demanded bits in the inputs are known zeros, return zero.
967 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
968 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
969
970 // If the RHS is a constant, see if we can simplify it.
971 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
972 return UpdateValueUsesWith(I, I);
973
974 // Output known-1 bits are only known if set in both the LHS & RHS.
975 RHSKnownOne &= LHSKnownOne;
976 // Output known-0 are known to be clear if zero in either the LHS | RHS.
977 RHSKnownZero |= LHSKnownZero;
978 break;
979 case Instruction::Or:
980 // If either the LHS or the RHS are One, the result is One.
981 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
982 RHSKnownZero, RHSKnownOne, Depth+1))
983 return true;
984 assert((RHSKnownZero & RHSKnownOne) == 0 &&
985 "Bits known to be one AND zero?");
986 // If something is known one on the RHS, the bits aren't demanded on the
987 // LHS.
988 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
989 LHSKnownZero, LHSKnownOne, Depth+1))
990 return true;
991 assert((LHSKnownZero & LHSKnownOne) == 0 &&
992 "Bits known to be one AND zero?");
993
994 // If all of the demanded bits are known zero on one side, return the other.
995 // These bits cannot contribute to the result of the 'or'.
996 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
997 (DemandedMask & ~LHSKnownOne))
998 return UpdateValueUsesWith(I, I->getOperand(0));
999 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1000 (DemandedMask & ~RHSKnownOne))
1001 return UpdateValueUsesWith(I, I->getOperand(1));
1002
1003 // If all of the potentially set bits on one side are known to be set on
1004 // the other side, just use the 'other' side.
1005 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1006 (DemandedMask & (~RHSKnownZero)))
1007 return UpdateValueUsesWith(I, I->getOperand(0));
1008 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1009 (DemandedMask & (~LHSKnownZero)))
1010 return UpdateValueUsesWith(I, I->getOperand(1));
1011
1012 // If the RHS is a constant, see if we can simplify it.
1013 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1014 return UpdateValueUsesWith(I, I);
1015
1016 // Output known-0 bits are only known if clear in both the LHS & RHS.
1017 RHSKnownZero &= LHSKnownZero;
1018 // Output known-1 are known to be set if set in either the LHS | RHS.
1019 RHSKnownOne |= LHSKnownOne;
1020 break;
1021 case Instruction::Xor: {
1022 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1023 RHSKnownZero, RHSKnownOne, Depth+1))
1024 return true;
1025 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1026 "Bits known to be one AND zero?");
1027 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1028 LHSKnownZero, LHSKnownOne, Depth+1))
1029 return true;
1030 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1031 "Bits known to be one AND zero?");
1032
1033 // If all of the demanded bits are known zero on one side, return the other.
1034 // These bits cannot contribute to the result of the 'xor'.
1035 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1036 return UpdateValueUsesWith(I, I->getOperand(0));
1037 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1038 return UpdateValueUsesWith(I, I->getOperand(1));
1039
1040 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1041 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1042 (RHSKnownOne & LHSKnownOne);
1043 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1044 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1045 (RHSKnownOne & LHSKnownZero);
1046
1047 // If all of the demanded bits are known to be zero on one side or the
1048 // other, turn this into an *inclusive* or.
1049 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1050 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1051 Instruction *Or =
1052 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1053 I->getName());
1054 InsertNewInstBefore(Or, *I);
1055 return UpdateValueUsesWith(I, Or);
1056 }
1057
1058 // If all of the demanded bits on one side are known, and all of the set
1059 // bits on that side are also known to be set on the other side, turn this
1060 // into an AND, as we know the bits will be cleared.
1061 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1062 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1063 // all known
1064 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1065 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1066 Instruction *And =
1067 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1068 InsertNewInstBefore(And, *I);
1069 return UpdateValueUsesWith(I, And);
1070 }
1071 }
1072
1073 // If the RHS is a constant, see if we can simplify it.
1074 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1075 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1076 return UpdateValueUsesWith(I, I);
1077
1078 RHSKnownZero = KnownZeroOut;
1079 RHSKnownOne = KnownOneOut;
1080 break;
1081 }
1082 case Instruction::Select:
1083 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1084 RHSKnownZero, RHSKnownOne, Depth+1))
1085 return true;
1086 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1087 LHSKnownZero, LHSKnownOne, Depth+1))
1088 return true;
1089 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1090 "Bits known to be one AND zero?");
1091 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1092 "Bits known to be one AND zero?");
1093
1094 // If the operands are constants, see if we can simplify them.
1095 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1096 return UpdateValueUsesWith(I, I);
1097 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1098 return UpdateValueUsesWith(I, I);
1099
1100 // Only known if known in both the LHS and RHS.
1101 RHSKnownOne &= LHSKnownOne;
1102 RHSKnownZero &= LHSKnownZero;
1103 break;
1104 case Instruction::Trunc: {
1105 uint32_t truncBf =
1106 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1107 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1108 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1109 return true;
1110 DemandedMask.trunc(BitWidth);
1111 RHSKnownZero.trunc(BitWidth);
1112 RHSKnownOne.trunc(BitWidth);
1113 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1114 "Bits known to be one AND zero?");
1115 break;
1116 }
1117 case Instruction::BitCast:
1118 if (!I->getOperand(0)->getType()->isInteger())
1119 return false;
1120
1121 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1122 RHSKnownZero, RHSKnownOne, Depth+1))
1123 return true;
1124 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1125 "Bits known to be one AND zero?");
1126 break;
1127 case Instruction::ZExt: {
1128 // Compute the bits in the result that are not present in the input.
1129 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001130 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1131 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001132
1133 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1134 uint32_t zextBf = SrcTy->getBitWidth();
1135 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1136 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1137 return true;
1138 DemandedMask.zext(BitWidth);
1139 RHSKnownZero.zext(BitWidth);
1140 RHSKnownOne.zext(BitWidth);
1141 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1142 "Bits known to be one AND zero?");
1143 // The top bits are known to be zero.
1144 RHSKnownZero |= NewBits;
1145 break;
1146 }
1147 case Instruction::SExt: {
1148 // Compute the bits in the result that are not present in the input.
1149 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001150 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1151 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001152
1153 // Get the sign bit for the source type
1154 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1155 InSignBit.zext(BitWidth);
1156 APInt InputDemandedBits = DemandedMask &
1157 SrcTy->getMask().zext(BitWidth);
1158
1159 // If any of the sign extended bits are demanded, we know that the sign
1160 // bit is demanded.
1161 if ((NewBits & DemandedMask) != 0)
1162 InputDemandedBits |= InSignBit;
1163
1164 uint32_t sextBf = SrcTy->getBitWidth();
1165 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1166 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1167 return true;
1168 InputDemandedBits.zext(BitWidth);
1169 RHSKnownZero.zext(BitWidth);
1170 RHSKnownOne.zext(BitWidth);
1171 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1172 "Bits known to be one AND zero?");
1173
1174 // If the sign bit of the input is known set or clear, then we know the
1175 // top bits of the result.
1176
1177 // If the input sign bit is known zero, or if the NewBits are not demanded
1178 // convert this into a zero extension.
1179 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1180 {
1181 // Convert to ZExt cast
1182 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1183 return UpdateValueUsesWith(I, NewCast);
1184 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1185 RHSKnownOne |= NewBits;
1186 RHSKnownZero &= ~NewBits;
1187 } else { // Input sign bit unknown
1188 RHSKnownZero &= ~NewBits;
1189 RHSKnownOne &= ~NewBits;
1190 }
1191 break;
1192 }
1193 case Instruction::Add: {
1194 // Figure out what the input bits are. If the top bits of the and result
1195 // are not demanded, then the add doesn't demand them from its input
1196 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001197 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001198
1199 // If there is a constant on the RHS, there are a variety of xformations
1200 // we can do.
1201 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1202 // If null, this should be simplified elsewhere. Some of the xforms here
1203 // won't work if the RHS is zero.
1204 if (RHS->isZero())
1205 break;
1206
1207 // If the top bit of the output is demanded, demand everything from the
1208 // input. Otherwise, we demand all the input bits except NLZ top bits.
1209 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1210
1211 // Find information about known zero/one bits in the input.
1212 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1213 LHSKnownZero, LHSKnownOne, Depth+1))
1214 return true;
1215
1216 // If the RHS of the add has bits set that can't affect the input, reduce
1217 // the constant.
1218 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1219 return UpdateValueUsesWith(I, I);
1220
1221 // Avoid excess work.
1222 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1223 break;
1224
1225 // Turn it into OR if input bits are zero.
1226 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1227 Instruction *Or =
1228 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1229 I->getName());
1230 InsertNewInstBefore(Or, *I);
1231 return UpdateValueUsesWith(I, Or);
1232 }
1233
1234 // We can say something about the output known-zero and known-one bits,
1235 // depending on potential carries from the input constant and the
1236 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1237 // bits set and the RHS constant is 0x01001, then we know we have a known
1238 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1239
1240 // To compute this, we first compute the potential carry bits. These are
1241 // the bits which may be modified. I'm not aware of a better way to do
1242 // this scan.
1243 APInt RHSVal(RHS->getValue());
1244
1245 bool CarryIn = false;
1246 APInt CarryBits(BitWidth, 0);
1247 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1248 *RHSRawVal = RHSVal.getRawData();
1249 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1250 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1251 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1252 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1253 if (AddVal < RHSRawVal[i])
1254 CarryIn = true;
1255 else
1256 CarryIn = false;
1257 CarryBits.setWordToValue(i, WordCarryBits);
1258 }
1259
1260 // Now that we know which bits have carries, compute the known-1/0 sets.
1261
1262 // Bits are known one if they are known zero in one operand and one in the
1263 // other, and there is no input carry.
1264 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1265 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1266
1267 // Bits are known zero if they are known zero in both operands and there
1268 // is no input carry.
1269 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1270 } else {
1271 // If the high-bits of this ADD are not demanded, then it does not demand
1272 // the high bits of its LHS or RHS.
1273 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1274 // Right fill the mask of bits for this ADD to demand the most
1275 // significant bit and all those below it.
1276 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1277 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1278 LHSKnownZero, LHSKnownOne, Depth+1))
1279 return true;
1280 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1281 LHSKnownZero, LHSKnownOne, Depth+1))
1282 return true;
1283 }
1284 }
1285 break;
1286 }
1287 case Instruction::Sub:
1288 // If the high-bits of this SUB are not demanded, then it does not demand
1289 // the high bits of its LHS or RHS.
1290 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1291 // Right fill the mask of bits for this SUB to demand the most
1292 // significant bit and all those below it.
Reid Spencer52830322007-03-25 21:11:44 +00001293 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001294 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1296 LHSKnownZero, LHSKnownOne, Depth+1))
1297 return true;
1298 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1299 LHSKnownZero, LHSKnownOne, Depth+1))
1300 return true;
1301 }
1302 break;
1303 case Instruction::Shl:
1304 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1305 uint64_t ShiftAmt = SA->getZExtValue();
1306 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1307 RHSKnownZero, RHSKnownOne, Depth+1))
1308 return true;
1309 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1310 "Bits known to be one AND zero?");
1311 RHSKnownZero <<= ShiftAmt;
1312 RHSKnownOne <<= ShiftAmt;
1313 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001314 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001315 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001316 }
1317 break;
1318 case Instruction::LShr:
1319 // For a logical shift right
1320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1321 unsigned ShiftAmt = SA->getZExtValue();
1322
1323 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1324 // Unsigned shift right.
1325 if (SimplifyDemandedBits(I->getOperand(0),
1326 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1327 RHSKnownZero, RHSKnownOne, Depth+1))
1328 return true;
1329 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1330 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001331 RHSKnownZero &= TypeMask;
1332 RHSKnownOne &= TypeMask;
1333 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1334 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001335 if (ShiftAmt) {
1336 // Compute the new bits that are at the top now.
1337 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
1338 BitWidth - ShiftAmt));
1339 RHSKnownZero |= HighBits; // high bits known zero.
1340 }
Reid Spencer1791f232007-03-12 17:25:59 +00001341 }
1342 break;
1343 case Instruction::AShr:
1344 // If this is an arithmetic shift right and only the low-bit is set, we can
1345 // always convert this into a logical shr, even if the shift amount is
1346 // variable. The low bit of the shift cannot be an input sign bit unless
1347 // the shift amount is >= the size of the datatype, which is undefined.
1348 if (DemandedMask == 1) {
1349 // Perform the logical shift right.
1350 Value *NewVal = BinaryOperator::createLShr(
1351 I->getOperand(0), I->getOperand(1), I->getName());
1352 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1353 return UpdateValueUsesWith(I, NewVal);
1354 }
1355
1356 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1357 unsigned ShiftAmt = SA->getZExtValue();
1358
1359 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1360 // Signed shift right.
1361 if (SimplifyDemandedBits(I->getOperand(0),
1362 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1363 RHSKnownZero, RHSKnownOne, Depth+1))
1364 return true;
1365 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1366 "Bits known to be one AND zero?");
1367 // Compute the new bits that are at the top now.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001368 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001369 RHSKnownZero &= TypeMask;
1370 RHSKnownOne &= TypeMask;
1371 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1372 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1373
1374 // Handle the sign bits.
1375 APInt SignBit(APInt::getSignBit(BitWidth));
1376 // Adjust to where it is now in the mask.
1377 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1378
1379 // If the input sign bit is known to be zero, or if none of the top bits
1380 // are demanded, turn this into an unsigned shift right.
1381 if ((RHSKnownZero & SignBit) != 0 ||
1382 (HighBits & ~DemandedMask) == HighBits) {
1383 // Perform the logical shift right.
1384 Value *NewVal = BinaryOperator::createLShr(
1385 I->getOperand(0), SA, I->getName());
1386 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1387 return UpdateValueUsesWith(I, NewVal);
1388 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1389 RHSKnownOne |= HighBits;
1390 }
1391 }
1392 break;
1393 }
1394
1395 // If the client is only demanding bits that we know, return the known
1396 // constant.
1397 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1398 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1399 return false;
1400}
1401
Chris Lattner2deeaea2006-10-05 06:55:50 +00001402
1403/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1404/// 64 or fewer elements. DemandedElts contains the set of elements that are
1405/// actually used by the caller. This method analyzes which elements of the
1406/// operand are undef and returns that information in UndefElts.
1407///
1408/// If the information about demanded elements can be used to simplify the
1409/// operation, the operation is simplified, then the resultant value is
1410/// returned. This returns null if no change was made.
1411Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1412 uint64_t &UndefElts,
1413 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001414 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001415 assert(VWidth <= 64 && "Vector too wide to analyze!");
1416 uint64_t EltMask = ~0ULL >> (64-VWidth);
1417 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1418 "Invalid DemandedElts!");
1419
1420 if (isa<UndefValue>(V)) {
1421 // If the entire vector is undefined, just return this info.
1422 UndefElts = EltMask;
1423 return 0;
1424 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1425 UndefElts = EltMask;
1426 return UndefValue::get(V->getType());
1427 }
1428
1429 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001430 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1431 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001432 Constant *Undef = UndefValue::get(EltTy);
1433
1434 std::vector<Constant*> Elts;
1435 for (unsigned i = 0; i != VWidth; ++i)
1436 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1437 Elts.push_back(Undef);
1438 UndefElts |= (1ULL << i);
1439 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1440 Elts.push_back(Undef);
1441 UndefElts |= (1ULL << i);
1442 } else { // Otherwise, defined.
1443 Elts.push_back(CP->getOperand(i));
1444 }
1445
1446 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001447 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001448 return NewCP != CP ? NewCP : 0;
1449 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001450 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001451 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001453 Constant *Zero = Constant::getNullValue(EltTy);
1454 Constant *Undef = UndefValue::get(EltTy);
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
1457 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1458 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001459 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001460 }
1461
1462 if (!V->hasOneUse()) { // Other users may use these bits.
1463 if (Depth != 0) { // Not at the root.
1464 // TODO: Just compute the UndefElts information recursively.
1465 return false;
1466 }
1467 return false;
1468 } else if (Depth == 10) { // Limit search depth.
1469 return false;
1470 }
1471
1472 Instruction *I = dyn_cast<Instruction>(V);
1473 if (!I) return false; // Only analyze instructions.
1474
1475 bool MadeChange = false;
1476 uint64_t UndefElts2;
1477 Value *TmpV;
1478 switch (I->getOpcode()) {
1479 default: break;
1480
1481 case Instruction::InsertElement: {
1482 // If this is a variable index, we don't know which element it overwrites.
1483 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001484 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001485 if (Idx == 0) {
1486 // Note that we can't propagate undef elt info, because we don't know
1487 // which elt is getting updated.
1488 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1489 UndefElts2, Depth+1);
1490 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1491 break;
1492 }
1493
1494 // If this is inserting an element that isn't demanded, remove this
1495 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001496 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001497 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1498 return AddSoonDeadInstToWorklist(*I, 0);
1499
1500 // Otherwise, the element inserted overwrites whatever was there, so the
1501 // input demanded set is simpler than the output set.
1502 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1503 DemandedElts & ~(1ULL << IdxNo),
1504 UndefElts, Depth+1);
1505 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1506
1507 // The inserted element is defined.
1508 UndefElts |= 1ULL << IdxNo;
1509 break;
1510 }
1511
1512 case Instruction::And:
1513 case Instruction::Or:
1514 case Instruction::Xor:
1515 case Instruction::Add:
1516 case Instruction::Sub:
1517 case Instruction::Mul:
1518 // div/rem demand all inputs, because they don't want divide by zero.
1519 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1520 UndefElts, Depth+1);
1521 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1522 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1523 UndefElts2, Depth+1);
1524 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1525
1526 // Output elements are undefined if both are undefined. Consider things
1527 // like undef&0. The result is known zero, not undef.
1528 UndefElts &= UndefElts2;
1529 break;
1530
1531 case Instruction::Call: {
1532 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1533 if (!II) break;
1534 switch (II->getIntrinsicID()) {
1535 default: break;
1536
1537 // Binary vector operations that work column-wise. A dest element is a
1538 // function of the corresponding input elements from the two inputs.
1539 case Intrinsic::x86_sse_sub_ss:
1540 case Intrinsic::x86_sse_mul_ss:
1541 case Intrinsic::x86_sse_min_ss:
1542 case Intrinsic::x86_sse_max_ss:
1543 case Intrinsic::x86_sse2_sub_sd:
1544 case Intrinsic::x86_sse2_mul_sd:
1545 case Intrinsic::x86_sse2_min_sd:
1546 case Intrinsic::x86_sse2_max_sd:
1547 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1548 UndefElts, Depth+1);
1549 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1550 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1551 UndefElts2, Depth+1);
1552 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1553
1554 // If only the low elt is demanded and this is a scalarizable intrinsic,
1555 // scalarize it now.
1556 if (DemandedElts == 1) {
1557 switch (II->getIntrinsicID()) {
1558 default: break;
1559 case Intrinsic::x86_sse_sub_ss:
1560 case Intrinsic::x86_sse_mul_ss:
1561 case Intrinsic::x86_sse2_sub_sd:
1562 case Intrinsic::x86_sse2_mul_sd:
1563 // TODO: Lower MIN/MAX/ABS/etc
1564 Value *LHS = II->getOperand(1);
1565 Value *RHS = II->getOperand(2);
1566 // Extract the element as scalars.
1567 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1568 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1569
1570 switch (II->getIntrinsicID()) {
1571 default: assert(0 && "Case stmts out of sync!");
1572 case Intrinsic::x86_sse_sub_ss:
1573 case Intrinsic::x86_sse2_sub_sd:
1574 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1575 II->getName()), *II);
1576 break;
1577 case Intrinsic::x86_sse_mul_ss:
1578 case Intrinsic::x86_sse2_mul_sd:
1579 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1580 II->getName()), *II);
1581 break;
1582 }
1583
1584 Instruction *New =
1585 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1586 II->getName());
1587 InsertNewInstBefore(New, *II);
1588 AddSoonDeadInstToWorklist(*II, 0);
1589 return New;
1590 }
1591 }
1592
1593 // Output elements are undefined if both are undefined. Consider things
1594 // like undef&0. The result is known zero, not undef.
1595 UndefElts &= UndefElts2;
1596 break;
1597 }
1598 break;
1599 }
1600 }
1601 return MadeChange ? I : 0;
1602}
1603
Reid Spencer266e42b2006-12-23 06:05:41 +00001604/// @returns true if the specified compare instruction is
1605/// true when both operands are equal...
1606/// @brief Determine if the ICmpInst returns true if both operands are equal
1607static bool isTrueWhenEqual(ICmpInst &ICI) {
1608 ICmpInst::Predicate pred = ICI.getPredicate();
1609 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1610 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1611 pred == ICmpInst::ICMP_SLE;
1612}
1613
Chris Lattnerb8b97502003-08-13 19:01:45 +00001614/// AssociativeOpt - Perform an optimization on an associative operator. This
1615/// function is designed to check a chain of associative operators for a
1616/// potential to apply a certain optimization. Since the optimization may be
1617/// applicable if the expression was reassociated, this checks the chain, then
1618/// reassociates the expression as necessary to expose the optimization
1619/// opportunity. This makes use of a special Functor, which must define
1620/// 'shouldApply' and 'apply' methods.
1621///
1622template<typename Functor>
1623Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1624 unsigned Opcode = Root.getOpcode();
1625 Value *LHS = Root.getOperand(0);
1626
1627 // Quick check, see if the immediate LHS matches...
1628 if (F.shouldApply(LHS))
1629 return F.apply(Root);
1630
1631 // Otherwise, if the LHS is not of the same opcode as the root, return.
1632 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001633 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001634 // Should we apply this transform to the RHS?
1635 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1636
1637 // If not to the RHS, check to see if we should apply to the LHS...
1638 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1639 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1640 ShouldApply = true;
1641 }
1642
1643 // If the functor wants to apply the optimization to the RHS of LHSI,
1644 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1645 if (ShouldApply) {
1646 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001647
Chris Lattnerb8b97502003-08-13 19:01:45 +00001648 // Now all of the instructions are in the current basic block, go ahead
1649 // and perform the reassociation.
1650 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1651
1652 // First move the selected RHS to the LHS of the root...
1653 Root.setOperand(0, LHSI->getOperand(1));
1654
1655 // Make what used to be the LHS of the root be the user of the root...
1656 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001657 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001658 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1659 return 0;
1660 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001661 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001662 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001663 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1664 BasicBlock::iterator ARI = &Root; ++ARI;
1665 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1666 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001667
1668 // Now propagate the ExtraOperand down the chain of instructions until we
1669 // get to LHSI.
1670 while (TmpLHSI != LHSI) {
1671 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001672 // Move the instruction to immediately before the chain we are
1673 // constructing to avoid breaking dominance properties.
1674 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1675 BB->getInstList().insert(ARI, NextLHSI);
1676 ARI = NextLHSI;
1677
Chris Lattnerb8b97502003-08-13 19:01:45 +00001678 Value *NextOp = NextLHSI->getOperand(1);
1679 NextLHSI->setOperand(1, ExtraOperand);
1680 TmpLHSI = NextLHSI;
1681 ExtraOperand = NextOp;
1682 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001683
Chris Lattnerb8b97502003-08-13 19:01:45 +00001684 // Now that the instructions are reassociated, have the functor perform
1685 // the transformation...
1686 return F.apply(Root);
1687 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001688
Chris Lattnerb8b97502003-08-13 19:01:45 +00001689 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1690 }
1691 return 0;
1692}
1693
1694
1695// AddRHS - Implements: X + X --> X << 1
1696struct AddRHS {
1697 Value *RHS;
1698 AddRHS(Value *rhs) : RHS(rhs) {}
1699 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1700 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001701 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001702 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001703 }
1704};
1705
1706// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1707// iff C1&C2 == 0
1708struct AddMaskingAnd {
1709 Constant *C2;
1710 AddMaskingAnd(Constant *c) : C2(c) {}
1711 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001712 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001713 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001714 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001715 }
1716 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001717 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001718 }
1719};
1720
Chris Lattner86102b82005-01-01 16:22:27 +00001721static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001722 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001723 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001724 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001725 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001726
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001727 return IC->InsertNewInstBefore(CastInst::create(
1728 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001729 }
1730
Chris Lattner183b3362004-04-09 19:05:30 +00001731 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001732 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1733 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001734
Chris Lattner183b3362004-04-09 19:05:30 +00001735 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1736 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001737 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1738 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001739 }
1740
1741 Value *Op0 = SO, *Op1 = ConstOperand;
1742 if (!ConstIsRHS)
1743 std::swap(Op0, Op1);
1744 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001745 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1746 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001747 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1748 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1749 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001750 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001751 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001752 abort();
1753 }
Chris Lattner86102b82005-01-01 16:22:27 +00001754 return IC->InsertNewInstBefore(New, I);
1755}
1756
1757// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1758// constant as the other operand, try to fold the binary operator into the
1759// select arguments. This also works for Cast instructions, which obviously do
1760// not have a second operand.
1761static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1762 InstCombiner *IC) {
1763 // Don't modify shared select instructions
1764 if (!SI->hasOneUse()) return 0;
1765 Value *TV = SI->getOperand(1);
1766 Value *FV = SI->getOperand(2);
1767
1768 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001769 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001770 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001771
Chris Lattner86102b82005-01-01 16:22:27 +00001772 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1773 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1774
1775 return new SelectInst(SI->getCondition(), SelectTrueVal,
1776 SelectFalseVal);
1777 }
1778 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001779}
1780
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001781
1782/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1783/// node as operand #0, see if we can fold the instruction into the PHI (which
1784/// is only possible if all operands to the PHI are constants).
1785Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1786 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001787 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001788 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001789
Chris Lattner04689872006-09-09 22:02:56 +00001790 // Check to see if all of the operands of the PHI are constants. If there is
1791 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001792 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001793 BasicBlock *NonConstBB = 0;
1794 for (unsigned i = 0; i != NumPHIValues; ++i)
1795 if (!isa<Constant>(PN->getIncomingValue(i))) {
1796 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001797 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001798 NonConstBB = PN->getIncomingBlock(i);
1799
1800 // If the incoming non-constant value is in I's block, we have an infinite
1801 // loop.
1802 if (NonConstBB == I.getParent())
1803 return 0;
1804 }
1805
1806 // If there is exactly one non-constant value, we can insert a copy of the
1807 // operation in that block. However, if this is a critical edge, we would be
1808 // inserting the computation one some other paths (e.g. inside a loop). Only
1809 // do this if the pred block is unconditionally branching into the phi block.
1810 if (NonConstBB) {
1811 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1812 if (!BI || !BI->isUnconditional()) return 0;
1813 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001814
1815 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001816 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001817 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001818 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001819 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001820
1821 // Next, add all of the operands to the PHI.
1822 if (I.getNumOperands() == 2) {
1823 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001824 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001825 Value *InV;
1826 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001827 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1828 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1829 else
1830 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001831 } else {
1832 assert(PN->getIncomingBlock(i) == NonConstBB);
1833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1834 InV = BinaryOperator::create(BO->getOpcode(),
1835 PN->getIncomingValue(i), C, "phitmp",
1836 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001837 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1838 InV = CmpInst::create(CI->getOpcode(),
1839 CI->getPredicate(),
1840 PN->getIncomingValue(i), C, "phitmp",
1841 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001842 else
1843 assert(0 && "Unknown binop!");
1844
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001845 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001846 }
1847 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001848 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001849 } else {
1850 CastInst *CI = cast<CastInst>(&I);
1851 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001852 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001853 Value *InV;
1854 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001855 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001856 } else {
1857 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001858 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1859 I.getType(), "phitmp",
1860 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001861 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001862 }
1863 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001864 }
1865 }
1866 return ReplaceInstUsesWith(I, NewPN);
1867}
1868
Chris Lattner113f4f42002-06-25 16:13:24 +00001869Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001870 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001871 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001872
Chris Lattnercf4a9962004-04-10 22:01:55 +00001873 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001874 // X + undef -> undef
1875 if (isa<UndefValue>(RHS))
1876 return ReplaceInstUsesWith(I, RHS);
1877
Chris Lattnercf4a9962004-04-10 22:01:55 +00001878 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001879 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001880 if (RHSC->isNullValue())
1881 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001882 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1883 if (CFP->isExactlyValue(-0.0))
1884 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001885 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001886
Chris Lattnercf4a9962004-04-10 22:01:55 +00001887 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001888 // X + (signbit) --> X ^ signbit
Reid Spencer959a21d2007-03-23 21:24:59 +00001889 APInt Val(CI->getValue());
1890 unsigned BitWidth = Val.getBitWidth();
1891 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001892 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001893
1894 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1895 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001896 if (!isa<VectorType>(I.getType())) {
1897 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1898 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1899 KnownZero, KnownOne))
1900 return &I;
1901 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001902 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001903
1904 if (isa<PHINode>(LHS))
1905 if (Instruction *NV = FoldOpIntoPhi(I))
1906 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001907
Chris Lattner330628a2006-01-06 17:59:59 +00001908 ConstantInt *XorRHS = 0;
1909 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001910 if (isa<ConstantInt>(RHSC) &&
1911 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001912 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00001913 APInt RHSVal(cast<ConstantInt>(RHSC)->getValue());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001914
Reid Spencer959a21d2007-03-23 21:24:59 +00001915 unsigned Size = TySizeBits / 2;
1916 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1917 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001918 do {
1919 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001920 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1921 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001922 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1923 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001924 // This is a sign extend if the top bits are known zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00001925 APInt Mask(APInt::getAllOnesValue(TySizeBits));
1926 Mask <<= Size;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001927 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001928 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001929 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001930 }
1931 }
1932 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001933 C0080Val = APIntOps::lshr(C0080Val, Size);
1934 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1935 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001936
Reid Spencera5c18bf2007-03-28 01:36:16 +00001937 // FIXME: This shouldn't be necessary. When the backends can handle types
1938 // with funny bit widths then this whole cascade of if statements should
1939 // be removed. It is just here to get the size of the "middle" type back
1940 // up to something that the back ends can handle.
1941 const Type *MiddleType = 0;
1942 switch (Size) {
1943 default: break;
1944 case 32: MiddleType = Type::Int32Ty; break;
1945 case 16: MiddleType = Type::Int16Ty; break;
1946 case 8: MiddleType = Type::Int8Ty; break;
1947 }
1948 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001949 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001950 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001951 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001952 }
1953 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001954 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001955
Chris Lattnerb8b97502003-08-13 19:01:45 +00001956 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001957 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001958 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001959
1960 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1961 if (RHSI->getOpcode() == Instruction::Sub)
1962 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1963 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1964 }
1965 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1966 if (LHSI->getOpcode() == Instruction::Sub)
1967 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1968 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1969 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001970 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001971
Chris Lattner147e9752002-05-08 22:46:53 +00001972 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001973 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001974 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001975
1976 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001977 if (!isa<Constant>(RHS))
1978 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001979 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001980
Misha Brukmanb1c93172005-04-21 23:48:37 +00001981
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001982 ConstantInt *C2;
1983 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1984 if (X == RHS) // X*C + X --> X * (C+1)
1985 return BinaryOperator::createMul(RHS, AddOne(C2));
1986
1987 // X*C1 + X*C2 --> X * (C1+C2)
1988 ConstantInt *C1;
1989 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00001990 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001991 }
1992
1993 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001994 if (dyn_castFoldableMul(RHS, C2) == LHS)
1995 return BinaryOperator::createMul(LHS, AddOne(C2));
1996
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001997 // X + ~X --> -1 since ~X = -X-1
1998 if (dyn_castNotVal(LHS) == RHS ||
1999 dyn_castNotVal(RHS) == LHS)
2000 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2001
Chris Lattner57c8d992003-02-18 19:57:07 +00002002
Chris Lattnerb8b97502003-08-13 19:01:45 +00002003 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002004 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002005 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2006 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002007
Chris Lattnerb9cde762003-10-02 15:11:26 +00002008 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002009 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002010 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2011 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002012
Chris Lattnerbff91d92004-10-08 05:07:56 +00002013 // (X & FF00) + xx00 -> (X+xx00) & FF00
2014 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002015 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002016 if (Anded == CRHS) {
2017 // See if all bits from the first bit set in the Add RHS up are included
2018 // in the mask. First, get the rightmost bit.
Reid Spencer959a21d2007-03-23 21:24:59 +00002019 APInt AddRHSV(CRHS->getValue());
Chris Lattnerbff91d92004-10-08 05:07:56 +00002020
2021 // Form a mask of all bits from the lowest bit added through the top.
Reid Spencer959a21d2007-03-23 21:24:59 +00002022 APInt AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2023 AddRHSHighBits &= C2->getType()->getMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002024
2025 // See if the and mask includes all of these bits.
Reid Spencer959a21d2007-03-23 21:24:59 +00002026 APInt AddRHSHighBitsAnd = AddRHSHighBits & C2->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002027
Chris Lattnerbff91d92004-10-08 05:07:56 +00002028 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2029 // Okay, the xform is safe. Insert the new add pronto.
2030 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2031 LHS->getName()), I);
2032 return BinaryOperator::createAnd(NewAdd, C2);
2033 }
2034 }
2035 }
2036
Chris Lattnerd4252a72004-07-30 07:50:03 +00002037 // Try to fold constant add into select arguments.
2038 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002039 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002040 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002041 }
2042
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002043 // add (cast *A to intptrtype) B ->
2044 // cast (GEP (cast *A to sbyte*) B) ->
2045 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002046 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002047 CastInst *CI = dyn_cast<CastInst>(LHS);
2048 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002049 if (!CI) {
2050 CI = dyn_cast<CastInst>(RHS);
2051 Other = LHS;
2052 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002053 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002054 (CI->getType()->getPrimitiveSizeInBits() ==
2055 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002056 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002057 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002058 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002059 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002060 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002061 }
2062 }
2063
Chris Lattner113f4f42002-06-25 16:13:24 +00002064 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002065}
2066
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002067// isSignBit - Return true if the value represented by the constant only has the
2068// highest order bit set.
2069static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002070 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002071 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002072}
2073
Chris Lattner113f4f42002-06-25 16:13:24 +00002074Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002075 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002076
Chris Lattnere6794492002-08-12 21:17:25 +00002077 if (Op0 == Op1) // sub X, X -> 0
2078 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002079
Chris Lattnere6794492002-08-12 21:17:25 +00002080 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002081 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002082 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002083
Chris Lattner81a7a232004-10-16 18:11:37 +00002084 if (isa<UndefValue>(Op0))
2085 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2086 if (isa<UndefValue>(Op1))
2087 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2088
Chris Lattner8f2f5982003-11-05 01:06:05 +00002089 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2090 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002091 if (C->isAllOnesValue())
2092 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002093
Chris Lattner8f2f5982003-11-05 01:06:05 +00002094 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002095 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002096 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002097 return BinaryOperator::createAdd(X, AddOne(C));
2098
Chris Lattner27df1db2007-01-15 07:02:54 +00002099 // -(X >>u 31) -> (X >>s 31)
2100 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002101 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002102 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002103 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002104 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002105 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002106 if (CU->getZExtValue() ==
2107 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002108 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002109 return BinaryOperator::create(Instruction::AShr,
2110 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002111 }
2112 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002113 }
2114 else if (SI->getOpcode() == Instruction::AShr) {
2115 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2116 // Check to see if we are shifting out everything but the sign bit.
2117 if (CU->getZExtValue() ==
2118 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002119 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002120 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002121 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002122 }
2123 }
2124 }
Chris Lattner022167f2004-03-13 00:11:49 +00002125 }
Chris Lattner183b3362004-04-09 19:05:30 +00002126
2127 // Try to fold constant sub into select arguments.
2128 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002130 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002131
2132 if (isa<PHINode>(Op0))
2133 if (Instruction *NV = FoldOpIntoPhi(I))
2134 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002135 }
2136
Chris Lattnera9be4492005-04-07 16:15:25 +00002137 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2138 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002139 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002140 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002141 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002142 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002143 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002144 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2145 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2146 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002147 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002148 Op1I->getOperand(0));
2149 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002150 }
2151
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002152 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002153 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2154 // is not used by anyone else...
2155 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002156 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002157 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002158 // Swap the two operands of the subexpr...
2159 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2160 Op1I->setOperand(0, IIOp1);
2161 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002162
Chris Lattner3082c5a2003-02-18 19:28:33 +00002163 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002164 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002165 }
2166
2167 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2168 //
2169 if (Op1I->getOpcode() == Instruction::And &&
2170 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2171 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2172
Chris Lattner396dbfe2004-06-09 05:08:07 +00002173 Value *NewNot =
2174 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002175 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002176 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002177
Reid Spencer3c514952006-10-16 23:08:08 +00002178 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002179 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002180 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002181 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002182 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002183 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002184 ConstantExpr::getNeg(DivRHS));
2185
Chris Lattner57c8d992003-02-18 19:57:07 +00002186 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002187 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002188 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002189 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002190 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002191 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002192 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002193 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002194
Chris Lattner7a002fe2006-12-02 00:13:08 +00002195 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002196 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2197 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002198 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2199 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2200 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2201 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002202 } else if (Op0I->getOpcode() == Instruction::Sub) {
2203 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2204 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002205 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002206
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002207 ConstantInt *C1;
2208 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002209 if (X == Op1) // X*C - X --> X * (C-1)
2210 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002211
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002212 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2213 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002214 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002215 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002216 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002217}
2218
Reid Spencer266e42b2006-12-23 06:05:41 +00002219/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002220/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002221static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2222 switch (pred) {
2223 case ICmpInst::ICMP_SLT:
2224 // True if LHS s< RHS and RHS == 0
2225 return RHS->isNullValue();
2226 case ICmpInst::ICMP_SLE:
2227 // True if LHS s<= RHS and RHS == -1
2228 return RHS->isAllOnesValue();
2229 case ICmpInst::ICMP_UGE:
2230 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002231 return RHS->getValue() ==
2232 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002233 case ICmpInst::ICMP_UGT:
2234 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002235 return RHS->getValue() ==
2236 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002237 default:
2238 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002239 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002240}
2241
Chris Lattner113f4f42002-06-25 16:13:24 +00002242Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002243 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002244 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002245
Chris Lattner81a7a232004-10-16 18:11:37 +00002246 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2247 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2248
Chris Lattnere6794492002-08-12 21:17:25 +00002249 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002250 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2251 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002252
2253 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002254 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002255 if (SI->getOpcode() == Instruction::Shl)
2256 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002257 return BinaryOperator::createMul(SI->getOperand(0),
2258 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002259
Chris Lattnercce81be2003-09-11 22:24:54 +00002260 if (CI->isNullValue())
2261 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2262 if (CI->equalsInt(1)) // X * 1 == X
2263 return ReplaceInstUsesWith(I, Op0);
2264 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002265 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002266
Reid Spencer6d392062007-03-23 20:05:17 +00002267 APInt Val(cast<ConstantInt>(CI)->getValue());
2268 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002269 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002270 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002271 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002272 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002273 if (Op1F->isNullValue())
2274 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002275
Chris Lattner3082c5a2003-02-18 19:28:33 +00002276 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2277 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2278 if (Op1F->getValue() == 1.0)
2279 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2280 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002281
2282 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2283 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2284 isa<ConstantInt>(Op0I->getOperand(1))) {
2285 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2286 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2287 Op1, "tmp");
2288 InsertNewInstBefore(Add, I);
2289 Value *C1C2 = ConstantExpr::getMul(Op1,
2290 cast<Constant>(Op0I->getOperand(1)));
2291 return BinaryOperator::createAdd(Add, C1C2);
2292
2293 }
Chris Lattner183b3362004-04-09 19:05:30 +00002294
2295 // Try to fold constant mul into select arguments.
2296 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002297 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002298 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002299
2300 if (isa<PHINode>(Op0))
2301 if (Instruction *NV = FoldOpIntoPhi(I))
2302 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002303 }
2304
Chris Lattner934a64cf2003-03-10 23:23:04 +00002305 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2306 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002307 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002308
Chris Lattner2635b522004-02-23 05:39:21 +00002309 // If one of the operands of the multiply is a cast from a boolean value, then
2310 // we know the bool is either zero or one, so this is a 'masking' multiply.
2311 // See if we can simplify things based on how the boolean was originally
2312 // formed.
2313 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002314 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002315 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002316 BoolCast = CI;
2317 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002318 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002319 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002320 BoolCast = CI;
2321 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002322 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002323 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2324 const Type *SCOpTy = SCIOp0->getType();
2325
Reid Spencer266e42b2006-12-23 06:05:41 +00002326 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002327 // multiply into a shift/and combination.
2328 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002329 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002330 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002331 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002332 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002333 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002334 InsertNewInstBefore(
2335 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002336 BoolCast->getOperand(0)->getName()+
2337 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002338
2339 // If the multiply type is not the same as the source type, sign extend
2340 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002341 if (I.getType() != V->getType()) {
2342 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2343 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2344 Instruction::CastOps opcode =
2345 (SrcBits == DstBits ? Instruction::BitCast :
2346 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2347 V = InsertCastBefore(opcode, V, I.getType(), I);
2348 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002349
Chris Lattner2635b522004-02-23 05:39:21 +00002350 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002351 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002352 }
2353 }
2354 }
2355
Chris Lattner113f4f42002-06-25 16:13:24 +00002356 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002357}
2358
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002359/// This function implements the transforms on div instructions that work
2360/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2361/// used by the visitors to those instructions.
2362/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002363Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002364 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002365
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366 // undef / X -> 0
2367 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369
2370 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002371 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002372 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002373
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002374 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002375 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2376 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 // same basic block, then we replace the select with Y, and the condition
2378 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002379 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002380 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002381 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2382 if (ST->isNullValue()) {
2383 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2384 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002385 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002386 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2387 I.setOperand(1, SI->getOperand(2));
2388 else
2389 UpdateValueUsesWith(SI, SI->getOperand(2));
2390 return &I;
2391 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002392
Chris Lattnerd79dc792006-09-09 20:26:32 +00002393 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2394 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2395 if (ST->isNullValue()) {
2396 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2397 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002398 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002399 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2400 I.setOperand(1, SI->getOperand(1));
2401 else
2402 UpdateValueUsesWith(SI, SI->getOperand(1));
2403 return &I;
2404 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002405 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002406
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002407 return 0;
2408}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002409
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002410/// This function implements the transforms common to both integer division
2411/// instructions (udiv and sdiv). It is called by the visitors to those integer
2412/// division instructions.
2413/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002414Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2416
2417 if (Instruction *Common = commonDivTransforms(I))
2418 return Common;
2419
2420 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2421 // div X, 1 == X
2422 if (RHS->equalsInt(1))
2423 return ReplaceInstUsesWith(I, Op0);
2424
2425 // (X / C1) / C2 -> X / (C1*C2)
2426 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2427 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2428 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2429 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002430 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002431 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002432
Reid Spencer6d392062007-03-23 20:05:17 +00002433 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002434 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2435 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2436 return R;
2437 if (isa<PHINode>(Op0))
2438 if (Instruction *NV = FoldOpIntoPhi(I))
2439 return NV;
2440 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002441 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002442
Chris Lattner3082c5a2003-02-18 19:28:33 +00002443 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002444 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002445 if (LHS->equalsInt(0))
2446 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2447
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002448 return 0;
2449}
2450
2451Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2452 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2453
2454 // Handle the integer div common cases
2455 if (Instruction *Common = commonIDivTransforms(I))
2456 return Common;
2457
2458 // X udiv C^2 -> X >> C
2459 // Check to see if this is an unsigned division with an exact power of 2,
2460 // if so, convert to a right shift.
2461 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002462 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002463 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002464 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002465 }
2466
2467 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002468 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002469 if (RHSI->getOpcode() == Instruction::Shl &&
2470 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002471 APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2472 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002473 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002474 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002475 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002476 Constant *C2V = ConstantInt::get(NTy, C2);
2477 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002478 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002479 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002480 }
2481 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002482 }
2483
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002484 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2485 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002486 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002487 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002488 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002489 APInt TVA(STO->getValue()), FVA(SFO->getValue());
2490 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002491 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002492 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002493 // Construct the "on true" case of the select
2494 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2495 Instruction *TSI = BinaryOperator::createLShr(
2496 Op0, TC, SI->getName()+".t");
2497 TSI = InsertNewInstBefore(TSI, I);
2498
2499 // Construct the "on false" case of the select
2500 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2501 Instruction *FSI = BinaryOperator::createLShr(
2502 Op0, FC, SI->getName()+".f");
2503 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002504
Reid Spencer3939b1a2007-03-05 23:36:13 +00002505 // construct the select instruction and return it.
2506 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002507 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002508 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002509 return 0;
2510}
2511
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002512Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2514
2515 // Handle the integer div common cases
2516 if (Instruction *Common = commonIDivTransforms(I))
2517 return Common;
2518
2519 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2520 // sdiv X, -1 == -X
2521 if (RHS->isAllOnesValue())
2522 return BinaryOperator::createNeg(Op0);
2523
2524 // -X/C -> X/-C
2525 if (Value *LHSNeg = dyn_castNegVal(Op0))
2526 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2527 }
2528
2529 // If the sign bits of both operands are zero (i.e. we can prove they are
2530 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002531 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002532 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002533 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2534 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2535 }
2536 }
2537
2538 return 0;
2539}
2540
2541Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2542 return commonDivTransforms(I);
2543}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002544
Chris Lattner85dda9a2006-03-02 06:50:58 +00002545/// GetFactor - If we can prove that the specified value is at least a multiple
2546/// of some factor, return that factor.
2547static Constant *GetFactor(Value *V) {
2548 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2549 return CI;
2550
2551 // Unless we can be tricky, we know this is a multiple of 1.
2552 Constant *Result = ConstantInt::get(V->getType(), 1);
2553
2554 Instruction *I = dyn_cast<Instruction>(V);
2555 if (!I) return Result;
2556
2557 if (I->getOpcode() == Instruction::Mul) {
2558 // Handle multiplies by a constant, etc.
2559 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2560 GetFactor(I->getOperand(1)));
2561 } else if (I->getOpcode() == Instruction::Shl) {
2562 // (X<<C) -> X * (1 << C)
2563 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2564 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2565 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2566 }
2567 } else if (I->getOpcode() == Instruction::And) {
2568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2569 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002570 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002571 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2572 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002573 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002574 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002575 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002576 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002577 if (!CI->isIntegerCast())
2578 return Result;
2579 Value *Op = CI->getOperand(0);
2580 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002581 }
2582 return Result;
2583}
2584
Reid Spencer7eb55b32006-11-02 01:53:59 +00002585/// This function implements the transforms on rem instructions that work
2586/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2587/// is used by the visitors to those instructions.
2588/// @brief Transforms common to all three rem instructions
2589Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002591
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002592 // 0 % X == 0, we don't need to preserve faults!
2593 if (Constant *LHS = dyn_cast<Constant>(Op0))
2594 if (LHS->isNullValue())
2595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2596
2597 if (isa<UndefValue>(Op0)) // undef % X -> 0
2598 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2599 if (isa<UndefValue>(Op1))
2600 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002601
2602 // Handle cases involving: rem X, (select Cond, Y, Z)
2603 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2604 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2605 // the same basic block, then we replace the select with Y, and the
2606 // condition of the select with false (if the cond value is in the same
2607 // BB). If the select has uses other than the div, this allows them to be
2608 // simplified also.
2609 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2610 if (ST->isNullValue()) {
2611 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2612 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002613 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002614 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2615 I.setOperand(1, SI->getOperand(2));
2616 else
2617 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002618 return &I;
2619 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002620 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2621 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2622 if (ST->isNullValue()) {
2623 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2624 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002625 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002626 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2627 I.setOperand(1, SI->getOperand(1));
2628 else
2629 UpdateValueUsesWith(SI, SI->getOperand(1));
2630 return &I;
2631 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002632 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002633
Reid Spencer7eb55b32006-11-02 01:53:59 +00002634 return 0;
2635}
2636
2637/// This function implements the transforms common to both integer remainder
2638/// instructions (urem and srem). It is called by the visitors to those integer
2639/// remainder instructions.
2640/// @brief Common integer remainder transforms
2641Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2643
2644 if (Instruction *common = commonRemTransforms(I))
2645 return common;
2646
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002647 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002648 // X % 0 == undef, we don't need to preserve faults!
2649 if (RHS->equalsInt(0))
2650 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2651
Chris Lattner3082c5a2003-02-18 19:28:33 +00002652 if (RHS->equalsInt(1)) // X % 1 == 0
2653 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2654
Chris Lattnerb70f1412006-02-28 05:49:21 +00002655 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2656 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2657 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2658 return R;
2659 } else if (isa<PHINode>(Op0I)) {
2660 if (Instruction *NV = FoldOpIntoPhi(I))
2661 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002662 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002663 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2664 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002665 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002666 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002667 }
2668
Reid Spencer7eb55b32006-11-02 01:53:59 +00002669 return 0;
2670}
2671
2672Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2673 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2674
2675 if (Instruction *common = commonIRemTransforms(I))
2676 return common;
2677
2678 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2679 // X urem C^2 -> X and C
2680 // Check to see if this is an unsigned remainder with an exact power of 2,
2681 // if so, convert to a bitwise and.
2682 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002683 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002684 return BinaryOperator::createAnd(Op0, SubOne(C));
2685 }
2686
Chris Lattner2e90b732006-02-05 07:54:04 +00002687 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002688 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2689 if (RHSI->getOpcode() == Instruction::Shl &&
2690 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002691 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002692 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2693 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2694 "tmp"), I);
2695 return BinaryOperator::createAnd(Op0, Add);
2696 }
2697 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002698 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002699
Reid Spencer7eb55b32006-11-02 01:53:59 +00002700 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2701 // where C1&C2 are powers of two.
2702 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2703 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2704 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2705 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002706 if ((STO->getValue().isPowerOf2()) &&
2707 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002708 Value *TrueAnd = InsertNewInstBefore(
2709 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2710 Value *FalseAnd = InsertNewInstBefore(
2711 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2712 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2713 }
2714 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002715 }
2716
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002717 return 0;
2718}
2719
Reid Spencer7eb55b32006-11-02 01:53:59 +00002720Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2721 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2722
2723 if (Instruction *common = commonIRemTransforms(I))
2724 return common;
2725
2726 if (Value *RHSNeg = dyn_castNegVal(Op1))
2727 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002728 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002729 // X % -Y -> X % Y
2730 AddUsesToWorkList(I);
2731 I.setOperand(1, RHSNeg);
2732 return &I;
2733 }
2734
2735 // If the top bits of both operands are zero (i.e. we can prove they are
2736 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002737 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002738 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2739 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2740 return BinaryOperator::createURem(Op0, Op1, I.getName());
2741 }
2742
2743 return 0;
2744}
2745
2746Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002747 return commonRemTransforms(I);
2748}
2749
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002750// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002751static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002752 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002753 if (isSigned) {
2754 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002755 APInt Val(APInt::getSignedMaxValue(TypeBits));
2756 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002757 }
Reid Spenceref599b02007-03-19 21:10:28 +00002758 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002759}
2760
2761// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002762static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2763 if (isSigned) {
2764 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002765 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2766 APInt Val(APInt::getSignedMinValue(TypeBits));
2767 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002768 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002769 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002770}
2771
Chris Lattner35167c32004-06-09 07:59:58 +00002772// isOneBitSet - Return true if there is exactly one bit set in the specified
2773// constant.
2774static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002775 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002776}
2777
Chris Lattner8fc5af42004-09-23 21:46:38 +00002778// isHighOnes - Return true if the constant is of the form 1+0+.
2779// This is the same as lowones(~X).
2780static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002781 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002782}
2783
Reid Spencer266e42b2006-12-23 06:05:41 +00002784/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002785/// are carefully arranged to allow folding of expressions such as:
2786///
2787/// (A < B) | (A > B) --> (A != B)
2788///
Reid Spencer266e42b2006-12-23 06:05:41 +00002789/// Note that this is only valid if the first and second predicates have the
2790/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791///
Reid Spencer266e42b2006-12-23 06:05:41 +00002792/// Three bits are used to represent the condition, as follows:
2793/// 0 A > B
2794/// 1 A == B
2795/// 2 A < B
2796///
2797/// <=> Value Definition
2798/// 000 0 Always false
2799/// 001 1 A > B
2800/// 010 2 A == B
2801/// 011 3 A >= B
2802/// 100 4 A < B
2803/// 101 5 A != B
2804/// 110 6 A <= B
2805/// 111 7 Always true
2806///
2807static unsigned getICmpCode(const ICmpInst *ICI) {
2808 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002809 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002810 case ICmpInst::ICMP_UGT: return 1; // 001
2811 case ICmpInst::ICMP_SGT: return 1; // 001
2812 case ICmpInst::ICMP_EQ: return 2; // 010
2813 case ICmpInst::ICMP_UGE: return 3; // 011
2814 case ICmpInst::ICMP_SGE: return 3; // 011
2815 case ICmpInst::ICMP_ULT: return 4; // 100
2816 case ICmpInst::ICMP_SLT: return 4; // 100
2817 case ICmpInst::ICMP_NE: return 5; // 101
2818 case ICmpInst::ICMP_ULE: return 6; // 110
2819 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002820 // True -> 7
2821 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002822 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002823 return 0;
2824 }
2825}
2826
Reid Spencer266e42b2006-12-23 06:05:41 +00002827/// getICmpValue - This is the complement of getICmpCode, which turns an
2828/// opcode and two operands into either a constant true or false, or a brand
2829/// new /// ICmp instruction. The sign is passed in to determine which kind
2830/// of predicate to use in new icmp instructions.
2831static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2832 switch (code) {
2833 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002834 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002835 case 1:
2836 if (sign)
2837 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2838 else
2839 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2840 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2841 case 3:
2842 if (sign)
2843 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2844 else
2845 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2846 case 4:
2847 if (sign)
2848 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2849 else
2850 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2851 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2852 case 6:
2853 if (sign)
2854 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2855 else
2856 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002857 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002858 }
2859}
2860
Reid Spencer266e42b2006-12-23 06:05:41 +00002861static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2862 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2863 (ICmpInst::isSignedPredicate(p1) &&
2864 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2865 (ICmpInst::isSignedPredicate(p2) &&
2866 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2867}
2868
2869namespace {
2870// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2871struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002872 InstCombiner &IC;
2873 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002874 ICmpInst::Predicate pred;
2875 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2876 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2877 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002878 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002879 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2880 if (PredicatesFoldable(pred, ICI->getPredicate()))
2881 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2882 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002883 return false;
2884 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002885 Instruction *apply(Instruction &Log) const {
2886 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2887 if (ICI->getOperand(0) != LHS) {
2888 assert(ICI->getOperand(1) == LHS);
2889 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002890 }
2891
Chris Lattnerd1bce952007-03-13 14:27:42 +00002892 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002893 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002894 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002895 unsigned Code;
2896 switch (Log.getOpcode()) {
2897 case Instruction::And: Code = LHSCode & RHSCode; break;
2898 case Instruction::Or: Code = LHSCode | RHSCode; break;
2899 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002900 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002901 }
2902
Chris Lattnerd1bce952007-03-13 14:27:42 +00002903 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2904 ICmpInst::isSignedPredicate(ICI->getPredicate());
2905
2906 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002907 if (Instruction *I = dyn_cast<Instruction>(RV))
2908 return I;
2909 // Otherwise, it's a constant boolean value...
2910 return IC.ReplaceInstUsesWith(Log, RV);
2911 }
2912};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002913} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002914
Chris Lattnerba1cb382003-09-19 17:17:26 +00002915// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2916// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002917// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002918Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002919 ConstantInt *OpRHS,
2920 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002921 BinaryOperator &TheAnd) {
2922 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002923 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002924 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002925 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002926
Chris Lattnerba1cb382003-09-19 17:17:26 +00002927 switch (Op->getOpcode()) {
2928 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002929 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002930 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002931 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002932 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002933 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002934 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002935 }
2936 break;
2937 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002938 if (Together == AndRHS) // (X | C) & C --> C
2939 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002940
Chris Lattner86102b82005-01-01 16:22:27 +00002941 if (Op->hasOneUse() && Together != OpRHS) {
2942 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002943 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002944 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002945 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002946 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002947 }
2948 break;
2949 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002950 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002951 // Adding a one to a single bit bit-field should be turned into an XOR
2952 // of the bit. First thing to check is to see if this AND is with a
2953 // single bit constant.
Reid Spencer6274c722007-03-23 18:46:34 +00002954 APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
Chris Lattnerba1cb382003-09-19 17:17:26 +00002955
2956 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002957 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002958 // Ok, at this point, we know that we are masking the result of the
2959 // ADD down to exactly one bit. If the constant we are adding has
2960 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencer6274c722007-03-23 18:46:34 +00002961 APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002962
Chris Lattnerba1cb382003-09-19 17:17:26 +00002963 // Check to see if any bits below the one bit set in AndRHSV are set.
2964 if ((AddRHS & (AndRHSV-1)) == 0) {
2965 // If not, the only thing that can effect the output of the AND is
2966 // the bit specified by AndRHSV. If that bit is set, the effect of
2967 // the XOR is to toggle the bit. If it is clear, then the ADD has
2968 // no effect.
2969 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2970 TheAnd.setOperand(0, X);
2971 return &TheAnd;
2972 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002973 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002974 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002975 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002976 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002977 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002978 }
2979 }
2980 }
2981 }
2982 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002983
2984 case Instruction::Shl: {
2985 // We know that the AND will not produce any of the bits shifted in, so if
2986 // the anded constant includes them, clear them now!
2987 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002988 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002989 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2990 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002991
Chris Lattner7e794272004-09-24 15:21:34 +00002992 if (CI == ShlMask) { // Masking out bits that the shift already masks
2993 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2994 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002995 TheAnd.setOperand(1, CI);
2996 return &TheAnd;
2997 }
2998 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002999 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003000 case Instruction::LShr:
3001 {
Chris Lattner2da29172003-09-19 19:05:02 +00003002 // We know that the AND will not produce any of the bits shifted in, so if
3003 // the anded constant includes them, clear them now! This only applies to
3004 // unsigned shifts, because a signed shr may bring in set bits!
3005 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003006 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003007 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3008 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003009
Reid Spencerfdff9382006-11-08 06:47:33 +00003010 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3011 return ReplaceInstUsesWith(TheAnd, Op);
3012 } else if (CI != AndRHS) {
3013 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3014 return &TheAnd;
3015 }
3016 break;
3017 }
3018 case Instruction::AShr:
3019 // Signed shr.
3020 // See if this is shifting in some sign extension, then masking it out
3021 // with an and.
3022 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003023 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003024 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003025 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3026 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003027 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003028 // Make the argument unsigned.
3029 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003030 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003031 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003032 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003033 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003034 }
Chris Lattner2da29172003-09-19 19:05:02 +00003035 }
3036 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003037 }
3038 return 0;
3039}
3040
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003041
Chris Lattner6862fbd2004-09-29 17:40:11 +00003042/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3043/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003044/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3045/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003046/// insert new instructions.
3047Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003048 bool isSigned, bool Inside,
3049 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003050 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003051 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003052 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003053
Chris Lattner6862fbd2004-09-29 17:40:11 +00003054 if (Inside) {
3055 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003056 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003057
Reid Spencer266e42b2006-12-23 06:05:41 +00003058 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003059 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003060 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003061 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3062 return new ICmpInst(pred, V, Hi);
3063 }
3064
3065 // Emit V-Lo <u Hi-Lo
3066 Constant *NegLo = ConstantExpr::getNeg(Lo);
3067 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003068 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003069 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3070 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003071 }
3072
3073 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003074 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003075
Reid Spencerf4071162007-03-21 23:19:50 +00003076 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003077 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003078 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003079 ICmpInst::Predicate pred = (isSigned ?
3080 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3081 return new ICmpInst(pred, V, Hi);
3082 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003083
Reid Spencerf4071162007-03-21 23:19:50 +00003084 // Emit V-Lo >u Hi-1-Lo
3085 // Note that Hi has already had one subtracted from it, above.
3086 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003087 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003088 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003089 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3090 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003091}
3092
Chris Lattnerb4b25302005-09-18 07:22:02 +00003093// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3094// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3095// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3096// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003097static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencera962d182007-03-24 00:42:08 +00003098 APInt V = Val->getValue();
3099 uint32_t BitWidth = Val->getType()->getBitWidth();
3100 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003101
3102 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003103 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003104 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003105 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003106 return true;
3107}
3108
Chris Lattnerb4b25302005-09-18 07:22:02 +00003109/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3110/// where isSub determines whether the operator is a sub. If we can fold one of
3111/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003112///
3113/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3114/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3115/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3116///
3117/// return (A +/- B).
3118///
3119Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003120 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003121 Instruction &I) {
3122 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3123 if (!LHSI || LHSI->getNumOperands() != 2 ||
3124 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3125
3126 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3127
3128 switch (LHSI->getOpcode()) {
3129 default: return 0;
3130 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003131 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003132 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003133 if ((Mask->getValue().countLeadingZeros() +
3134 Mask->getValue().countPopulation()) ==
3135 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003136 break;
3137
3138 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3139 // part, we don't need any explicit masks to take them out of A. If that
3140 // is all N is, ignore it.
Reid Spencer755d0e72007-03-26 17:44:01 +00003141 unsigned MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003142 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003143 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3144 APInt Mask(APInt::getAllOnesValue(BitWidth));
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003145 Mask = Mask.lshr(BitWidth-MB+1);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003146 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003147 break;
3148 }
3149 }
Chris Lattneraf517572005-09-18 04:24:45 +00003150 return 0;
3151 case Instruction::Or:
3152 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003153 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003154 if ((Mask->getValue().countLeadingZeros() +
3155 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003156 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003157 break;
3158 return 0;
3159 }
3160
3161 Instruction *New;
3162 if (isSub)
3163 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3164 else
3165 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3166 return InsertNewInstBefore(New, I);
3167}
3168
Chris Lattner113f4f42002-06-25 16:13:24 +00003169Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003170 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003172
Chris Lattner81a7a232004-10-16 18:11:37 +00003173 if (isa<UndefValue>(Op1)) // X & undef -> 0
3174 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3175
Chris Lattner86102b82005-01-01 16:22:27 +00003176 // and X, X = X
3177 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003178 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003179
Chris Lattner5b2edb12006-02-12 08:02:11 +00003180 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003181 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003182 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003183 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3184 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3185 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003186 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003187 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003188 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003189 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003190 if (CP->isAllOnesValue())
3191 return ReplaceInstUsesWith(I, I.getOperand(0));
3192 }
3193 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003194
Zhou Sheng75b871f2007-01-11 12:24:14 +00003195 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003196 APInt AndRHSMask(AndRHS->getValue());
3197 APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3198 APInt NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003199
Chris Lattnerba1cb382003-09-19 17:17:26 +00003200 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003201 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003202 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003203 Value *Op0LHS = Op0I->getOperand(0);
3204 Value *Op0RHS = Op0I->getOperand(1);
3205 switch (Op0I->getOpcode()) {
3206 case Instruction::Xor:
3207 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003208 // If the mask is only needed on one incoming arm, push it up.
3209 if (Op0I->hasOneUse()) {
3210 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3211 // Not masking anything out for the LHS, move to RHS.
3212 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3213 Op0RHS->getName()+".masked");
3214 InsertNewInstBefore(NewRHS, I);
3215 return BinaryOperator::create(
3216 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003217 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003218 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003219 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3220 // Not masking anything out for the RHS, move to LHS.
3221 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3222 Op0LHS->getName()+".masked");
3223 InsertNewInstBefore(NewLHS, I);
3224 return BinaryOperator::create(
3225 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3226 }
3227 }
3228
Chris Lattner86102b82005-01-01 16:22:27 +00003229 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003230 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003231 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3232 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3233 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3234 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3235 return BinaryOperator::createAnd(V, AndRHS);
3236 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3237 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003238 break;
3239
3240 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003241 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3242 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3243 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3244 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3245 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003246 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003247 }
3248
Chris Lattner16464b32003-07-23 19:25:52 +00003249 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003250 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003251 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003252 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003253 // If this is an integer truncation or change from signed-to-unsigned, and
3254 // if the source is an and/or with immediate, transform it. This
3255 // frequently occurs for bitfield accesses.
3256 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003257 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003258 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003259 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003260 if (CastOp->getOpcode() == Instruction::And) {
3261 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003262 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3263 // This will fold the two constants together, which may allow
3264 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003265 Instruction *NewCast = CastInst::createTruncOrBitCast(
3266 CastOp->getOperand(0), I.getType(),
3267 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003268 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003269 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003270 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003271 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003272 return BinaryOperator::createAnd(NewCast, C3);
3273 } else if (CastOp->getOpcode() == Instruction::Or) {
3274 // Change: and (cast (or X, C1) to T), C2
3275 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003276 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003277 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3278 return ReplaceInstUsesWith(I, AndRHS);
3279 }
3280 }
Chris Lattner33217db2003-07-23 19:36:21 +00003281 }
Chris Lattner183b3362004-04-09 19:05:30 +00003282
3283 // Try to fold constant and into select arguments.
3284 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003285 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003286 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003287 if (isa<PHINode>(Op0))
3288 if (Instruction *NV = FoldOpIntoPhi(I))
3289 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003290 }
3291
Chris Lattnerbb74e222003-03-10 23:06:50 +00003292 Value *Op0NotVal = dyn_castNotVal(Op0);
3293 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003294
Chris Lattner023a4832004-06-18 06:07:51 +00003295 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3297
Misha Brukman9c003d82004-07-30 12:50:08 +00003298 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003299 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003300 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3301 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003302 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003303 return BinaryOperator::createNot(Or);
3304 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003305
3306 {
3307 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003308 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3309 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3310 return ReplaceInstUsesWith(I, Op1);
3311 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3312 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3313 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003314
3315 if (Op0->hasOneUse() &&
3316 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3317 if (A == Op1) { // (A^B)&A -> A&(A^B)
3318 I.swapOperands(); // Simplify below
3319 std::swap(Op0, Op1);
3320 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3321 cast<BinaryOperator>(Op0)->swapOperands();
3322 I.swapOperands(); // Simplify below
3323 std::swap(Op0, Op1);
3324 }
3325 }
3326 if (Op1->hasOneUse() &&
3327 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3328 if (B == Op0) { // B&(A^B) -> B&(B^A)
3329 cast<BinaryOperator>(Op1)->swapOperands();
3330 std::swap(A, B);
3331 }
3332 if (A == Op0) { // A&(A^B) -> A & ~B
3333 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3334 InsertNewInstBefore(NotB, I);
3335 return BinaryOperator::createAnd(A, NotB);
3336 }
3337 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003338 }
3339
Reid Spencer266e42b2006-12-23 06:05:41 +00003340 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3341 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3342 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003343 return R;
3344
Chris Lattner623826c2004-09-28 21:48:02 +00003345 Value *LHSVal, *RHSVal;
3346 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003347 ICmpInst::Predicate LHSCC, RHSCC;
3348 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3349 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3350 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3351 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3352 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3353 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3354 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3355 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003356 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003357 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3358 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3359 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3360 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003361 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003362 std::swap(LHS, RHS);
3363 std::swap(LHSCst, RHSCst);
3364 std::swap(LHSCC, RHSCC);
3365 }
3366
Reid Spencer266e42b2006-12-23 06:05:41 +00003367 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003368 // comparing a value against two constants and and'ing the result
3369 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003370 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3371 // (from the FoldICmpLogical check above), that the two constants
3372 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003373 assert(LHSCst != RHSCst && "Compares not folded above?");
3374
3375 switch (LHSCC) {
3376 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003377 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003378 switch (RHSCC) {
3379 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003380 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3381 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3382 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003383 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003384 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3385 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3386 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003387 return ReplaceInstUsesWith(I, LHS);
3388 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003389 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003390 switch (RHSCC) {
3391 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003392 case ICmpInst::ICMP_ULT:
3393 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3394 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3395 break; // (X != 13 & X u< 15) -> no change
3396 case ICmpInst::ICMP_SLT:
3397 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3398 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3399 break; // (X != 13 & X s< 15) -> no change
3400 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3401 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3402 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003403 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003404 case ICmpInst::ICMP_NE:
3405 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003406 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3407 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3408 LHSVal->getName()+".off");
3409 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003410 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3411 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003412 }
3413 break; // (X != 13 & X != 15) -> no change
3414 }
3415 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003416 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003417 switch (RHSCC) {
3418 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003419 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3420 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003421 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003422 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3423 break;
3424 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3425 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003426 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003427 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3428 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003429 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003430 break;
3431 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003432 switch (RHSCC) {
3433 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003434 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3435 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003436 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003437 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3438 break;
3439 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3440 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003441 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003442 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3443 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003444 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003445 break;
3446 case ICmpInst::ICMP_UGT:
3447 switch (RHSCC) {
3448 default: assert(0 && "Unknown integer condition code!");
3449 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3450 return ReplaceInstUsesWith(I, LHS);
3451 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3452 return ReplaceInstUsesWith(I, RHS);
3453 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3454 break;
3455 case ICmpInst::ICMP_NE:
3456 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3457 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3458 break; // (X u> 13 & X != 15) -> no change
3459 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3460 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3461 true, I);
3462 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3463 break;
3464 }
3465 break;
3466 case ICmpInst::ICMP_SGT:
3467 switch (RHSCC) {
3468 default: assert(0 && "Unknown integer condition code!");
3469 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3470 return ReplaceInstUsesWith(I, LHS);
3471 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3472 return ReplaceInstUsesWith(I, RHS);
3473 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3474 break;
3475 case ICmpInst::ICMP_NE:
3476 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3477 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3478 break; // (X s> 13 & X != 15) -> no change
3479 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3480 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3481 true, I);
3482 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3483 break;
3484 }
3485 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003486 }
3487 }
3488 }
3489
Chris Lattner3af10532006-05-05 06:39:07 +00003490 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003491 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3492 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3493 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3494 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003495 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003496 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003497 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3498 I.getType(), TD) &&
3499 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3500 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003501 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3502 Op1C->getOperand(0),
3503 I.getName());
3504 InsertNewInstBefore(NewOp, I);
3505 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3506 }
Chris Lattner3af10532006-05-05 06:39:07 +00003507 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003508
3509 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003510 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3511 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3512 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003513 SI0->getOperand(1) == SI1->getOperand(1) &&
3514 (SI0->hasOneUse() || SI1->hasOneUse())) {
3515 Instruction *NewOp =
3516 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3517 SI1->getOperand(0),
3518 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003519 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3520 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003521 }
Chris Lattner3af10532006-05-05 06:39:07 +00003522 }
3523
Chris Lattner113f4f42002-06-25 16:13:24 +00003524 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003525}
3526
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003527/// CollectBSwapParts - Look to see if the specified value defines a single byte
3528/// in the result. If it does, and if the specified byte hasn't been filled in
3529/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003530static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003531 Instruction *I = dyn_cast<Instruction>(V);
3532 if (I == 0) return true;
3533
3534 // If this is an or instruction, it is an inner node of the bswap.
3535 if (I->getOpcode() == Instruction::Or)
3536 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3537 CollectBSwapParts(I->getOperand(1), ByteValues);
3538
3539 // If this is a shift by a constant int, and it is "24", then its operand
3540 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003541 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003542 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003543 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003544 8*(ByteValues.size()-1))
3545 return true;
3546
3547 unsigned DestNo;
3548 if (I->getOpcode() == Instruction::Shl) {
3549 // X << 24 defines the top byte with the lowest of the input bytes.
3550 DestNo = ByteValues.size()-1;
3551 } else {
3552 // X >>u 24 defines the low byte with the highest of the input bytes.
3553 DestNo = 0;
3554 }
3555
3556 // If the destination byte value is already defined, the values are or'd
3557 // together, which isn't a bswap (unless it's an or of the same bits).
3558 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3559 return true;
3560 ByteValues[DestNo] = I->getOperand(0);
3561 return false;
3562 }
3563
3564 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3565 // don't have this.
3566 Value *Shift = 0, *ShiftLHS = 0;
3567 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3568 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3569 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3570 return true;
3571 Instruction *SI = cast<Instruction>(Shift);
3572
3573 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003574 if (ShiftAmt->getZExtValue() & 7 ||
3575 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003576 return true;
3577
3578 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3579 unsigned DestByte;
3580 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003581 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003582 break;
3583 // Unknown mask for bswap.
3584 if (DestByte == ByteValues.size()) return true;
3585
Reid Spencere0fc4df2006-10-20 07:07:24 +00003586 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003587 unsigned SrcByte;
3588 if (SI->getOpcode() == Instruction::Shl)
3589 SrcByte = DestByte - ShiftBytes;
3590 else
3591 SrcByte = DestByte + ShiftBytes;
3592
3593 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3594 if (SrcByte != ByteValues.size()-DestByte-1)
3595 return true;
3596
3597 // If the destination byte value is already defined, the values are or'd
3598 // together, which isn't a bswap (unless it's an or of the same bits).
3599 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3600 return true;
3601 ByteValues[DestByte] = SI->getOperand(0);
3602 return false;
3603}
3604
3605/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3606/// If so, insert the new bswap intrinsic and return it.
3607Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003608 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003609 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003610 return 0;
3611
3612 /// ByteValues - For each byte of the result, we keep track of which value
3613 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003614 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003615 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003616
3617 // Try to find all the pieces corresponding to the bswap.
3618 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3619 CollectBSwapParts(I.getOperand(1), ByteValues))
3620 return 0;
3621
3622 // Check to see if all of the bytes come from the same value.
3623 Value *V = ByteValues[0];
3624 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3625
3626 // Check to make sure that all of the bytes come from the same value.
3627 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3628 if (ByteValues[i] != V)
3629 return 0;
3630
3631 // If they do then *success* we can turn this into a bswap. Figure out what
3632 // bswap to make it into.
3633 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003634 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003635 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003636 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003637 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003638 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003639 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003640 FnName = "llvm.bswap.i64";
3641 else
3642 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003643 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003644 return new CallInst(F, V);
3645}
3646
3647
Chris Lattner113f4f42002-06-25 16:13:24 +00003648Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003649 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003650 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003651
Chris Lattner3a8248f2007-03-24 23:56:43 +00003652 if (isa<UndefValue>(Op1)) // X | undef -> -1
3653 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003654
Chris Lattner5b2edb12006-02-12 08:02:11 +00003655 // or X, X = X
3656 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003657 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003658
Chris Lattner5b2edb12006-02-12 08:02:11 +00003659 // See if we can simplify any instructions used by the instruction whose sole
3660 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003661 if (!isa<VectorType>(I.getType())) {
3662 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3663 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3664 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3665 KnownZero, KnownOne))
3666 return &I;
3667 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003668
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003669 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003670 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003671 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003672 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3673 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003674 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003675 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003676 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003677 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3678 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003679
Chris Lattnerd4252a72004-07-30 07:50:03 +00003680 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3681 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003682 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003683 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003684 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003685 return BinaryOperator::createXor(Or,
3686 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003687 }
Chris Lattner183b3362004-04-09 19:05:30 +00003688
3689 // Try to fold constant and into select arguments.
3690 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003691 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003692 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003693 if (isa<PHINode>(Op0))
3694 if (Instruction *NV = FoldOpIntoPhi(I))
3695 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003696 }
3697
Chris Lattner330628a2006-01-06 17:59:59 +00003698 Value *A = 0, *B = 0;
3699 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003700
3701 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3702 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3703 return ReplaceInstUsesWith(I, Op1);
3704 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3705 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3706 return ReplaceInstUsesWith(I, Op0);
3707
Chris Lattnerb7845d62006-07-10 20:25:24 +00003708 // (A | B) | C and A | (B | C) -> bswap if possible.
3709 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003710 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003711 match(Op1, m_Or(m_Value(), m_Value())) ||
3712 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3713 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003714 if (Instruction *BSwap = MatchBSwap(I))
3715 return BSwap;
3716 }
3717
Chris Lattnerb62f5082005-05-09 04:58:36 +00003718 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3719 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003720 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003721 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3722 InsertNewInstBefore(NOr, I);
3723 NOr->takeName(Op0);
3724 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003725 }
3726
3727 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3728 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003729 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003730 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3731 InsertNewInstBefore(NOr, I);
3732 NOr->takeName(Op0);
3733 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003734 }
3735
Chris Lattner15212982005-09-18 03:42:07 +00003736 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003737 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003738 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3739
3740 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3741 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3742
3743
Chris Lattner01f56c62005-09-18 06:02:59 +00003744 // If we have: ((V + N) & C1) | (V & C2)
3745 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3746 // replace with V+N.
3747 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003748 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003749 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003750 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3751 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003752 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003753 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003754 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003755 return ReplaceInstUsesWith(I, A);
3756 }
3757 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003758 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003759 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3760 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003761 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003762 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003763 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003764 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003765 }
3766 }
3767 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003768
3769 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003770 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3771 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3772 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003773 SI0->getOperand(1) == SI1->getOperand(1) &&
3774 (SI0->hasOneUse() || SI1->hasOneUse())) {
3775 Instruction *NewOp =
3776 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3777 SI1->getOperand(0),
3778 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003779 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3780 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003781 }
3782 }
Chris Lattner812aab72003-08-12 19:11:07 +00003783
Chris Lattnerd4252a72004-07-30 07:50:03 +00003784 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3785 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003786 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003787 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003788 } else {
3789 A = 0;
3790 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003791 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003792 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3793 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003794 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003795 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003796
Misha Brukman9c003d82004-07-30 12:50:08 +00003797 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003798 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3799 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3800 I.getName()+".demorgan"), I);
3801 return BinaryOperator::createNot(And);
3802 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003803 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003804
Reid Spencer266e42b2006-12-23 06:05:41 +00003805 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3806 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3807 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003808 return R;
3809
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003810 Value *LHSVal, *RHSVal;
3811 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003812 ICmpInst::Predicate LHSCC, RHSCC;
3813 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3814 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3815 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3816 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3817 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3818 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3819 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3820 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003821 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003822 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3823 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3824 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3825 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003826 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003827 std::swap(LHS, RHS);
3828 std::swap(LHSCst, RHSCst);
3829 std::swap(LHSCC, RHSCC);
3830 }
3831
Reid Spencer266e42b2006-12-23 06:05:41 +00003832 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003833 // comparing a value against two constants and or'ing the result
3834 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003835 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3836 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003837 // equal.
3838 assert(LHSCst != RHSCst && "Compares not folded above?");
3839
3840 switch (LHSCC) {
3841 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003842 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003843 switch (RHSCC) {
3844 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003845 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003846 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3847 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3848 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3849 LHSVal->getName()+".off");
3850 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003851 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003852 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003853 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003854 break; // (X == 13 | X == 15) -> no change
3855 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3856 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003857 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003858 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3859 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3860 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003861 return ReplaceInstUsesWith(I, RHS);
3862 }
3863 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003864 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003865 switch (RHSCC) {
3866 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003867 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3868 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3869 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003870 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003871 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3872 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3873 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003874 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003875 }
3876 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003877 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003878 switch (RHSCC) {
3879 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003880 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003881 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003882 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3883 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3884 false, I);
3885 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3886 break;
3887 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3888 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003889 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003890 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3891 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003892 }
3893 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003894 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003895 switch (RHSCC) {
3896 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003897 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3898 break;
3899 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3900 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3901 false, I);
3902 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3903 break;
3904 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3905 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3906 return ReplaceInstUsesWith(I, RHS);
3907 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3908 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003909 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003910 break;
3911 case ICmpInst::ICMP_UGT:
3912 switch (RHSCC) {
3913 default: assert(0 && "Unknown integer condition code!");
3914 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3915 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3916 return ReplaceInstUsesWith(I, LHS);
3917 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3920 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003921 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003922 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3923 break;
3924 }
3925 break;
3926 case ICmpInst::ICMP_SGT:
3927 switch (RHSCC) {
3928 default: assert(0 && "Unknown integer condition code!");
3929 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3930 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3931 return ReplaceInstUsesWith(I, LHS);
3932 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3933 break;
3934 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3935 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003936 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003937 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3938 break;
3939 }
3940 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003941 }
3942 }
3943 }
Chris Lattner3af10532006-05-05 06:39:07 +00003944
3945 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003946 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003947 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003948 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3949 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003950 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003951 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003952 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3953 I.getType(), TD) &&
3954 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3955 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003956 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3957 Op1C->getOperand(0),
3958 I.getName());
3959 InsertNewInstBefore(NewOp, I);
3960 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3961 }
Chris Lattner3af10532006-05-05 06:39:07 +00003962 }
Chris Lattner3af10532006-05-05 06:39:07 +00003963
Chris Lattner15212982005-09-18 03:42:07 +00003964
Chris Lattner113f4f42002-06-25 16:13:24 +00003965 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003966}
3967
Chris Lattnerc2076352004-02-16 01:20:27 +00003968// XorSelf - Implements: X ^ X --> 0
3969struct XorSelf {
3970 Value *RHS;
3971 XorSelf(Value *rhs) : RHS(rhs) {}
3972 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3973 Instruction *apply(BinaryOperator &Xor) const {
3974 return &Xor;
3975 }
3976};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003977
3978
Chris Lattner113f4f42002-06-25 16:13:24 +00003979Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003980 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003982
Chris Lattner81a7a232004-10-16 18:11:37 +00003983 if (isa<UndefValue>(Op1))
3984 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3985
Chris Lattnerc2076352004-02-16 01:20:27 +00003986 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3987 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3988 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003990 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003991
3992 // See if we can simplify any instructions used by the instruction whose sole
3993 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003994 if (!isa<VectorType>(I.getType())) {
3995 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3996 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3997 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3998 KnownZero, KnownOne))
3999 return &I;
4000 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004001
Zhou Sheng75b871f2007-01-11 12:24:14 +00004002 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004003 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4004 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004005 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004006 return new ICmpInst(ICI->getInversePredicate(),
4007 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004008
Reid Spencer266e42b2006-12-23 06:05:41 +00004009 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004010 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004011 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4012 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004013 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4014 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004015 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004016 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004017 }
Chris Lattner023a4832004-06-18 06:07:51 +00004018
4019 // ~(~X & Y) --> (X | ~Y)
4020 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4021 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4022 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4023 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004024 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004025 Op0I->getOperand(1)->getName()+".not");
4026 InsertNewInstBefore(NotY, I);
4027 return BinaryOperator::createOr(Op0NotVal, NotY);
4028 }
4029 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004030
Chris Lattner97638592003-07-23 21:37:07 +00004031 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004032 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004033 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004034 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004035 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4036 return BinaryOperator::createSub(
4037 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004038 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004039 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004040 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004041 } else if (Op0I->getOpcode() == Instruction::Or) {
4042 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004043 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004044 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4045 // Anything in both C1 and C2 is known to be zero, remove it from
4046 // NewRHS.
4047 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4048 NewRHS = ConstantExpr::getAnd(NewRHS,
4049 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004050 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004051 I.setOperand(0, Op0I->getOperand(0));
4052 I.setOperand(1, NewRHS);
4053 return &I;
4054 }
Chris Lattner97638592003-07-23 21:37:07 +00004055 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004056 }
Chris Lattner183b3362004-04-09 19:05:30 +00004057
4058 // Try to fold constant and into select arguments.
4059 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004060 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004061 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004062 if (isa<PHINode>(Op0))
4063 if (Instruction *NV = FoldOpIntoPhi(I))
4064 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004065 }
4066
Chris Lattnerbb74e222003-03-10 23:06:50 +00004067 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004068 if (X == Op1)
4069 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004070 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004071
Chris Lattnerbb74e222003-03-10 23:06:50 +00004072 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004073 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004074 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004075
Chris Lattner07418422007-03-18 22:51:34 +00004076
4077 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4078 if (Op1I) {
4079 Value *A, *B;
4080 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4081 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004082 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004083 I.swapOperands();
4084 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004085 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004086 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004087 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004088 }
Chris Lattner07418422007-03-18 22:51:34 +00004089 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4090 if (Op0 == A) // A^(A^B) == B
4091 return ReplaceInstUsesWith(I, B);
4092 else if (Op0 == B) // A^(B^A) == B
4093 return ReplaceInstUsesWith(I, A);
4094 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4095 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004096 Op1I->swapOperands();
Chris Lattner07418422007-03-18 22:51:34 +00004097 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004098 I.swapOperands(); // Simplified below.
4099 std::swap(Op0, Op1);
4100 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004101 }
Chris Lattner07418422007-03-18 22:51:34 +00004102 }
4103
4104 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4105 if (Op0I) {
4106 Value *A, *B;
4107 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4108 if (A == Op1) // (B|A)^B == (A|B)^B
4109 std::swap(A, B);
4110 if (B == Op1) { // (A|B)^B == A & ~B
4111 Instruction *NotB =
4112 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4113 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004114 }
Chris Lattner07418422007-03-18 22:51:34 +00004115 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4116 if (Op1 == A) // (A^B)^A == B
4117 return ReplaceInstUsesWith(I, B);
4118 else if (Op1 == B) // (B^A)^A == B
4119 return ReplaceInstUsesWith(I, A);
4120 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4121 if (A == Op1) // (A&B)^A -> (B&A)^A
4122 std::swap(A, B);
4123 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004124 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004125 Instruction *N =
4126 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004127 return BinaryOperator::createAnd(N, Op1);
4128 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004129 }
Chris Lattner07418422007-03-18 22:51:34 +00004130 }
4131
4132 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4133 if (Op0I && Op1I && Op0I->isShift() &&
4134 Op0I->getOpcode() == Op1I->getOpcode() &&
4135 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4136 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4137 Instruction *NewOp =
4138 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4139 Op1I->getOperand(0),
4140 Op0I->getName()), I);
4141 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4142 Op1I->getOperand(1));
4143 }
4144
4145 if (Op0I && Op1I) {
4146 Value *A, *B, *C, *D;
4147 // (A & B)^(A | B) -> A ^ B
4148 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4149 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4150 if ((A == C && B == D) || (A == D && B == C))
4151 return BinaryOperator::createXor(A, B);
4152 }
4153 // (A | B)^(A & B) -> A ^ B
4154 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4155 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4156 if ((A == C && B == D) || (A == D && B == C))
4157 return BinaryOperator::createXor(A, B);
4158 }
4159
4160 // (A & B)^(C & D)
4161 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4162 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4163 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4164 // (X & Y)^(X & Y) -> (Y^Z) & X
4165 Value *X = 0, *Y = 0, *Z = 0;
4166 if (A == C)
4167 X = A, Y = B, Z = D;
4168 else if (A == D)
4169 X = A, Y = B, Z = C;
4170 else if (B == C)
4171 X = B, Y = A, Z = D;
4172 else if (B == D)
4173 X = B, Y = A, Z = C;
4174
4175 if (X) {
4176 Instruction *NewOp =
4177 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4178 return BinaryOperator::createAnd(NewOp, X);
4179 }
4180 }
4181 }
4182
Reid Spencer266e42b2006-12-23 06:05:41 +00004183 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4184 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4185 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004186 return R;
4187
Chris Lattner3af10532006-05-05 06:39:07 +00004188 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004189 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004190 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004191 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4192 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004193 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004194 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004195 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4196 I.getType(), TD) &&
4197 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4198 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004199 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4200 Op1C->getOperand(0),
4201 I.getName());
4202 InsertNewInstBefore(NewOp, I);
4203 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4204 }
Chris Lattner3af10532006-05-05 06:39:07 +00004205 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004206
Chris Lattner113f4f42002-06-25 16:13:24 +00004207 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004208}
4209
Chris Lattner6862fbd2004-09-29 17:40:11 +00004210/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4211/// overflowed for this type.
4212static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004213 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004214 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4215
Reid Spencerf4071162007-03-21 23:19:50 +00004216 if (IsSigned)
4217 if (In2->getValue().isNegative())
4218 return Result->getValue().sgt(In1->getValue());
4219 else
4220 return Result->getValue().slt(In1->getValue());
4221 else
4222 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004223}
4224
Chris Lattner0798af32005-01-13 20:14:25 +00004225/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4226/// code necessary to compute the offset from the base pointer (without adding
4227/// in the base pointer). Return the result as a signed integer of intptr size.
4228static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4229 TargetData &TD = IC.getTargetData();
4230 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004231 const Type *IntPtrTy = TD.getIntPtrType();
4232 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004233
4234 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004235 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004236
Chris Lattner0798af32005-01-13 20:14:25 +00004237 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4238 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004239 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004240 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004241 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4242 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004243 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004244 Scale = ConstantExpr::getMul(OpC, Scale);
4245 if (Constant *RC = dyn_cast<Constant>(Result))
4246 Result = ConstantExpr::getAdd(RC, Scale);
4247 else {
4248 // Emit an add instruction.
4249 Result = IC.InsertNewInstBefore(
4250 BinaryOperator::createAdd(Result, Scale,
4251 GEP->getName()+".offs"), I);
4252 }
4253 }
4254 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004255 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004256 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004257 Op->getName()+".c"), I);
4258 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004259 // We'll let instcombine(mul) convert this to a shl if possible.
4260 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4261 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004262
4263 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004264 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004265 GEP->getName()+".offs"), I);
4266 }
4267 }
4268 return Result;
4269}
4270
Reid Spencer266e42b2006-12-23 06:05:41 +00004271/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004272/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004273Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4274 ICmpInst::Predicate Cond,
4275 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004276 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004277
4278 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4279 if (isa<PointerType>(CI->getOperand(0)->getType()))
4280 RHS = CI->getOperand(0);
4281
Chris Lattner0798af32005-01-13 20:14:25 +00004282 Value *PtrBase = GEPLHS->getOperand(0);
4283 if (PtrBase == RHS) {
4284 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004285 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4286 // each index is zero or not.
4287 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004288 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004289 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4290 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004291 bool EmitIt = true;
4292 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4293 if (isa<UndefValue>(C)) // undef index -> undef.
4294 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4295 if (C->isNullValue())
4296 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004297 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4298 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004299 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004300 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004301 ConstantInt::get(Type::Int1Ty,
4302 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004303 }
4304
4305 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004306 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004307 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004308 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4309 if (InVal == 0)
4310 InVal = Comp;
4311 else {
4312 InVal = InsertNewInstBefore(InVal, I);
4313 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004314 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004315 InVal = BinaryOperator::createOr(InVal, Comp);
4316 else // True if all are equal
4317 InVal = BinaryOperator::createAnd(InVal, Comp);
4318 }
4319 }
4320 }
4321
4322 if (InVal)
4323 return InVal;
4324 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004325 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004326 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4327 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004328 }
Chris Lattner0798af32005-01-13 20:14:25 +00004329
Reid Spencer266e42b2006-12-23 06:05:41 +00004330 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004331 // the result to fold to a constant!
4332 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4333 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4334 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004335 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4336 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004337 }
4338 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004339 // If the base pointers are different, but the indices are the same, just
4340 // compare the base pointer.
4341 if (PtrBase != GEPRHS->getOperand(0)) {
4342 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004343 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004344 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004345 if (IndicesTheSame)
4346 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4347 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4348 IndicesTheSame = false;
4349 break;
4350 }
4351
4352 // If all indices are the same, just compare the base pointers.
4353 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004354 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4355 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004356
4357 // Otherwise, the base pointers are different and the indices are
4358 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004359 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004360 }
Chris Lattner0798af32005-01-13 20:14:25 +00004361
Chris Lattner81e84172005-01-13 22:25:21 +00004362 // If one of the GEPs has all zero indices, recurse.
4363 bool AllZeros = true;
4364 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4365 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4366 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4367 AllZeros = false;
4368 break;
4369 }
4370 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004371 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4372 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004373
4374 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004375 AllZeros = true;
4376 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4377 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4378 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4379 AllZeros = false;
4380 break;
4381 }
4382 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004383 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004384
Chris Lattner4fa89822005-01-14 00:20:05 +00004385 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4386 // If the GEPs only differ by one index, compare it.
4387 unsigned NumDifferences = 0; // Keep track of # differences.
4388 unsigned DiffOperand = 0; // The operand that differs.
4389 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4390 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004391 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4392 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004393 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004394 NumDifferences = 2;
4395 break;
4396 } else {
4397 if (NumDifferences++) break;
4398 DiffOperand = i;
4399 }
4400 }
4401
4402 if (NumDifferences == 0) // SAME GEP?
4403 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004404 ConstantInt::get(Type::Int1Ty,
4405 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004406 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004407 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4408 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004409 // Make sure we do a signed comparison here.
4410 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004411 }
4412 }
4413
Reid Spencer266e42b2006-12-23 06:05:41 +00004414 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004415 // the result to fold to a constant!
4416 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4417 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4418 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4419 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4420 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004421 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004422 }
4423 }
4424 return 0;
4425}
4426
Reid Spencer266e42b2006-12-23 06:05:41 +00004427Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4428 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004429 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004430
Chris Lattner6ee923f2007-01-14 19:42:17 +00004431 // Fold trivial predicates.
4432 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4433 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4434 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4435 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4436
4437 // Simplify 'fcmp pred X, X'
4438 if (Op0 == Op1) {
4439 switch (I.getPredicate()) {
4440 default: assert(0 && "Unknown predicate!");
4441 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4442 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4443 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4444 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4445 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4446 case FCmpInst::FCMP_OLT: // True if ordered and less than
4447 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4448 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4449
4450 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4451 case FCmpInst::FCMP_ULT: // True if unordered or less than
4452 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4453 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4454 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4455 I.setPredicate(FCmpInst::FCMP_UNO);
4456 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4457 return &I;
4458
4459 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4460 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4461 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4462 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4463 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4464 I.setPredicate(FCmpInst::FCMP_ORD);
4465 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4466 return &I;
4467 }
4468 }
4469
Reid Spencer266e42b2006-12-23 06:05:41 +00004470 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004471 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004472
Reid Spencer266e42b2006-12-23 06:05:41 +00004473 // Handle fcmp with constant RHS
4474 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4475 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4476 switch (LHSI->getOpcode()) {
4477 case Instruction::PHI:
4478 if (Instruction *NV = FoldOpIntoPhi(I))
4479 return NV;
4480 break;
4481 case Instruction::Select:
4482 // If either operand of the select is a constant, we can fold the
4483 // comparison into the select arms, which will cause one to be
4484 // constant folded and the select turned into a bitwise or.
4485 Value *Op1 = 0, *Op2 = 0;
4486 if (LHSI->hasOneUse()) {
4487 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4488 // Fold the known value into the constant operand.
4489 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4490 // Insert a new FCmp of the other select operand.
4491 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4492 LHSI->getOperand(2), RHSC,
4493 I.getName()), I);
4494 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4495 // Fold the known value into the constant operand.
4496 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4497 // Insert a new FCmp of the other select operand.
4498 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4499 LHSI->getOperand(1), RHSC,
4500 I.getName()), I);
4501 }
4502 }
4503
4504 if (Op1)
4505 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4506 break;
4507 }
4508 }
4509
4510 return Changed ? &I : 0;
4511}
4512
4513Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4514 bool Changed = SimplifyCompare(I);
4515 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4516 const Type *Ty = Op0->getType();
4517
4518 // icmp X, X
4519 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004520 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4521 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004522
4523 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004524 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004525
4526 // icmp of GlobalValues can never equal each other as long as they aren't
4527 // external weak linkage type.
4528 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4529 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4530 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004531 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4532 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004533
4534 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004535 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004536 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4537 isa<ConstantPointerNull>(Op0)) &&
4538 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004539 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004540 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4541 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004542
Reid Spencer266e42b2006-12-23 06:05:41 +00004543 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004544 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004545 switch (I.getPredicate()) {
4546 default: assert(0 && "Invalid icmp instruction!");
4547 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004548 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004549 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004550 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004551 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004553 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004554
Reid Spencer266e42b2006-12-23 06:05:41 +00004555 case ICmpInst::ICMP_UGT:
4556 case ICmpInst::ICMP_SGT:
4557 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004558 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004559 case ICmpInst::ICMP_ULT:
4560 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004561 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4562 InsertNewInstBefore(Not, I);
4563 return BinaryOperator::createAnd(Not, Op1);
4564 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004565 case ICmpInst::ICMP_UGE:
4566 case ICmpInst::ICMP_SGE:
4567 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004568 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004569 case ICmpInst::ICMP_ULE:
4570 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004571 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4572 InsertNewInstBefore(Not, I);
4573 return BinaryOperator::createOr(Not, Op1);
4574 }
4575 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004576 }
4577
Chris Lattner2dd01742004-06-09 04:24:29 +00004578 // See if we are doing a comparison between a constant and an instruction that
4579 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004580 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004581 switch (I.getPredicate()) {
4582 default: break;
4583 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4584 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004585 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004586 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4587 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4588 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4589 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4590 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004591
Reid Spencer266e42b2006-12-23 06:05:41 +00004592 case ICmpInst::ICMP_SLT:
4593 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004594 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004595 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4596 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4597 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4598 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4599 break;
4600
4601 case ICmpInst::ICMP_UGT:
4602 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004603 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004604 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4605 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4606 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4607 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4608 break;
4609
4610 case ICmpInst::ICMP_SGT:
4611 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004612 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004613 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4614 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4615 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4616 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4617 break;
4618
4619 case ICmpInst::ICMP_ULE:
4620 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004621 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004622 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4623 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4624 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4625 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4626 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004627
Reid Spencer266e42b2006-12-23 06:05:41 +00004628 case ICmpInst::ICMP_SLE:
4629 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004630 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004631 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4632 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4633 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4634 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4635 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004636
Reid Spencer266e42b2006-12-23 06:05:41 +00004637 case ICmpInst::ICMP_UGE:
4638 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004639 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004640 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4641 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4642 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4643 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4644 break;
4645
4646 case ICmpInst::ICMP_SGE:
4647 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004649 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4650 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4651 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4652 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4653 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004654 }
4655
Reid Spencer266e42b2006-12-23 06:05:41 +00004656 // If we still have a icmp le or icmp ge instruction, turn it into the
4657 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004658 // already been handled above, this requires little checking.
4659 //
Reid Spencer624766f2007-03-25 19:55:33 +00004660 switch (I.getPredicate()) {
4661 default: break;
4662 case ICmpInst::ICMP_ULE:
4663 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4664 case ICmpInst::ICMP_SLE:
4665 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4666 case ICmpInst::ICMP_UGE:
4667 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4668 case ICmpInst::ICMP_SGE:
4669 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4670 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004671
4672 // See if we can fold the comparison based on bits known to be zero or one
4673 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004674 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4675 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4676 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004677 KnownZero, KnownOne, 0))
4678 return &I;
4679
4680 // Given the known and unknown bits, compute a range that the LHS could be
4681 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004682 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004683 // Compute the Min, Max and RHS values based on the known bits. For the
4684 // EQ and NE we use unsigned values.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004685 APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004686 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004687 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4688 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004689 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004690 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4691 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004692 }
4693 switch (I.getPredicate()) { // LE/GE have been folded already.
4694 default: assert(0 && "Unknown icmp opcode!");
4695 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004696 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004697 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004698 break;
4699 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004700 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004701 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004702 break;
4703 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004704 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004705 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004706 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004708 break;
4709 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004710 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004711 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004712 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004714 break;
4715 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004716 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004717 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004718 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004719 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004720 break;
4721 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004722 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004723 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004724 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004725 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004726 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004727 }
4728 }
4729
Reid Spencer266e42b2006-12-23 06:05:41 +00004730 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004731 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004732 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004733 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004734 switch (LHSI->getOpcode()) {
4735 case Instruction::And:
4736 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4737 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004738 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4739
Reid Spencer266e42b2006-12-23 06:05:41 +00004740 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004741 // and/compare to be the input width without changing the value
4742 // produced, eliminating a cast.
4743 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4744 // We can do this transformation if either the AND constant does not
4745 // have its sign bit set or if it is an equality comparison.
4746 // Extending a relational comparison when we're checking the sign
4747 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004748 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004749 (I.isEquality() || AndCST->getValue().isPositive() &&
4750 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004751 ConstantInt *NewCST;
4752 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004753 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4754 uint32_t BitWidth = cast<IntegerType>(
4755 Cast->getOperand(0)->getType())->getBitWidth();
4756 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4757 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00004758 Instruction *NewAnd =
4759 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4760 LHSI->getName());
4761 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004762 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004763 }
4764 }
4765
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004766 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4767 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4768 // happens a LOT in code produced by the C front-end, for bitfield
4769 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004770 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4771 if (Shift && !Shift->isShift())
4772 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004773
Reid Spencere0fc4df2006-10-20 07:07:24 +00004774 ConstantInt *ShAmt;
4775 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004776 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4777 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004778
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004779 // We can fold this as long as we can't shift unknown bits
4780 // into the mask. This can only happen with signed shift
4781 // rights, as they sign-extend.
4782 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004783 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004784 if (!CanFold) {
4785 // To test for the bad case of the signed shr, see if any
4786 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004787 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004788 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4789
Reid Spencer2341c222007-02-02 02:16:23 +00004790 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004791 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004792 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4793 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004794 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4795 CanFold = true;
4796 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004797
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004798 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004799 Constant *NewCst;
4800 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004801 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004802 else
4803 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004804
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004805 // Check to see if we are shifting out any of the bits being
4806 // compared.
4807 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4808 // If we shifted bits out, the fold is not going to work out.
4809 // As a special case, check to see if this means that the
4810 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004811 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004812 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004813 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004814 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004815 } else {
4816 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004817 Constant *NewAndCST;
4818 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004819 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004820 else
4821 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4822 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004823 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004824 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004825 AddUsesToWorkList(I);
4826 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004827 }
4828 }
Chris Lattner35167c32004-06-09 07:59:58 +00004829 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004830
4831 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4832 // preferable because it allows the C<<Y expression to be hoisted out
4833 // of a loop if Y is invariant and X is not.
4834 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004835 I.isEquality() && !Shift->isArithmeticShift() &&
4836 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004837 // Compute C << Y.
4838 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004839 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004840 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004841 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004842 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004843 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004844 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004845 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004846 }
4847 InsertNewInstBefore(cast<Instruction>(NS), I);
4848
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004849 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004850 Instruction *NewAnd = BinaryOperator::createAnd(
4851 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004852 InsertNewInstBefore(NewAnd, I);
4853
4854 I.setOperand(0, NewAnd);
4855 return &I;
4856 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004857 }
4858 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004859
Reid Spencer266e42b2006-12-23 06:05:41 +00004860 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004861 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004862 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004863 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4864
4865 // Check that the shift amount is in range. If not, don't perform
4866 // undefined shifts. When the shift is visited it will be
4867 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004868 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004869 break;
4870
Chris Lattner272d5ca2004-09-28 18:22:15 +00004871 // If we are comparing against bits always shifted out, the
4872 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004873 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004874 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004875 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004876 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004877 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004878 return ReplaceInstUsesWith(I, Cst);
4879 }
4880
4881 if (LHSI->hasOneUse()) {
4882 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004883 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Reid Spencer52830322007-03-25 21:11:44 +00004884 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4885 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004886
Chris Lattner272d5ca2004-09-28 18:22:15 +00004887 Instruction *AndI =
4888 BinaryOperator::createAnd(LHSI->getOperand(0),
4889 Mask, LHSI->getName()+".mask");
4890 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004891 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004892 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004893 }
4894 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004895 }
4896 break;
4897
Reid Spencer266e42b2006-12-23 06:05:41 +00004898 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004899 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004900 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004901 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004902 // Check that the shift amount is in range. If not, don't perform
4903 // undefined shifts. When the shift is visited it will be
4904 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004905 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004906 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004907 break;
4908
Chris Lattner1023b872004-09-27 16:18:50 +00004909 // If we are comparing against bits always shifted out, the
4910 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004911 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004912 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004913 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4914 ShAmt);
4915 else
4916 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4917 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004918
Chris Lattner1023b872004-09-27 16:18:50 +00004919 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004920 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004921 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004922 return ReplaceInstUsesWith(I, Cst);
4923 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004924
Chris Lattner1023b872004-09-27 16:18:50 +00004925 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004926 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004927
Chris Lattner1023b872004-09-27 16:18:50 +00004928 // Otherwise strength reduce the shift into an and.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004929 APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
4930 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004931
Chris Lattner1023b872004-09-27 16:18:50 +00004932 Instruction *AndI =
4933 BinaryOperator::createAnd(LHSI->getOperand(0),
4934 Mask, LHSI->getName()+".mask");
4935 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004936 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004937 ConstantExpr::getShl(CI, ShAmt));
4938 }
Chris Lattner1023b872004-09-27 16:18:50 +00004939 }
4940 }
4941 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004942
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004943 case Instruction::SDiv:
4944 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004946 // Fold this div into the comparison, producing a range check.
4947 // Determine, based on the divide type, what the range is being
4948 // checked. If there is an overflow on the low or high side, remember
4949 // it, otherwise compute the range [low, hi) bounding the new value.
4950 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004951 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004952 // FIXME: If the operand types don't match the type of the divide
4953 // then don't attempt this transform. The code below doesn't have the
4954 // logic to deal with a signed divide and an unsigned compare (and
4955 // vice versa). This is because (x /s C1) <s C2 produces different
4956 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4957 // (x /u C1) <u C2. Simply casting the operands and result won't
4958 // work. :( The if statement below tests that condition and bails
4959 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004960 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4961 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004962 break;
Reid Spencerf4071162007-03-21 23:19:50 +00004963 if (DivRHS->isZero())
4964 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004965
4966 // Initialize the variables that will indicate the nature of the
4967 // range check.
4968 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004969 ConstantInt *LoBound = 0, *HiBound = 0;
4970
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004971 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4972 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4973 // C2 (CI). By solving for X we can turn this into a range check
4974 // instead of computing a divide.
4975 ConstantInt *Prod =
4976 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004977
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004978 // Determine if the product overflows by seeing if the product is
4979 // not equal to the divide. Make sure we do the same kind of divide
4980 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00004981 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4982 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004983
Reid Spencer266e42b2006-12-23 06:05:41 +00004984 // Get the ICmp opcode
4985 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004986
Reid Spencerf4071162007-03-21 23:19:50 +00004987 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004988 LoBound = Prod;
4989 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004990 HiOverflow = ProdOV ||
4991 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00004992 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004993 if (CI->isNullValue()) { // (X / pos) op 0
4994 // Can't overflow.
4995 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4996 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00004997 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004998 LoBound = Prod;
4999 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00005000 HiOverflow = ProdOV ||
5001 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005002 } else { // (X / pos) op neg
5003 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5004 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00005005 cast<ConstantInt>(DivRHSH), true);
5006 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005007 HiOverflow = ProdOV;
5008 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005009 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005010 if (CI->isNullValue()) { // (X / neg) op 0
5011 LoBound = AddOne(DivRHS);
5012 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005013 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005014 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00005015 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005016 HiOverflow = LoOverflow = ProdOV;
5017 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00005018 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5019 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005020 HiBound = AddOne(Prod);
5021 } else { // (X / neg) op neg
5022 LoBound = Prod;
5023 LoOverflow = HiOverflow = ProdOV;
5024 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5025 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005026
Chris Lattnera92af962004-10-11 19:40:04 +00005027 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005028 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005029 }
5030
5031 if (LoBound) {
5032 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005033 switch (predicate) {
5034 default: assert(0 && "Unhandled icmp opcode!");
5035 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005036 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005037 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005038 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5040 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005041 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005042 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5043 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005044 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005045 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5046 true, I);
5047 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005048 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005049 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005050 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005051 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5052 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005053 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005054 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5055 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005056 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5058 false, I);
5059 case ICmpInst::ICMP_ULT:
5060 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005061 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005062 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005063 return new ICmpInst(predicate, X, LoBound);
5064 case ICmpInst::ICMP_UGT:
5065 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005066 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005067 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005068 if (predicate == ICmpInst::ICMP_UGT)
5069 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5070 else
5071 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005072 }
5073 }
5074 }
5075 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005076 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005077
Reid Spencer266e42b2006-12-23 06:05:41 +00005078 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005079 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005080 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005081
Reid Spencere0fc4df2006-10-20 07:07:24 +00005082 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5083 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005084 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5085 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005086 case Instruction::SRem:
5087 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005088 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005089 BO->hasOneUse()) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005090 APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5091 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005092 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5093 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005094 return new ICmpInst(I.getPredicate(), NewRem,
5095 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005096 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005097 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005098 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005099 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005100 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5101 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005102 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005103 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5104 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005105 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005106 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5107 // efficiently invertible, or if the add has just this one use.
5108 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005109
Chris Lattnerc992add2003-08-13 05:33:12 +00005110 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005111 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005112 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005113 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005114 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005115 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005116 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005117 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005118 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005119 }
5120 }
5121 break;
5122 case Instruction::Xor:
5123 // For the xor case, we can xor two constants together, eliminating
5124 // the explicit xor.
5125 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005126 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5127 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005128
5129 // FALLTHROUGH
5130 case Instruction::Sub:
5131 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005132 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005133 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5134 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005135 break;
5136
5137 case Instruction::Or:
5138 // If bits are being or'd in that are not present in the constant we
5139 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005140 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005141 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005142 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005143 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5144 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005145 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005146 break;
5147
5148 case Instruction::And:
5149 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005150 // If bits are being compared against that are and'd out, then the
5151 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005152 if (!ConstantExpr::getAnd(CI,
5153 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005154 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5155 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005156
Chris Lattner35167c32004-06-09 07:59:58 +00005157 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005158 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005159 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5160 ICmpInst::ICMP_NE, Op0,
5161 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005162
Reid Spencer266e42b2006-12-23 06:05:41 +00005163 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005164 if (isSignBit(BOC)) {
5165 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005166 Constant *Zero = Constant::getNullValue(X->getType());
5167 ICmpInst::Predicate pred = isICMP_NE ?
5168 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5169 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005170 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005171
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005172 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005173 if (CI->isNullValue() && isHighOnes(BOC)) {
5174 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005175 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005176 ICmpInst::Predicate pred = isICMP_NE ?
5177 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5178 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005179 }
5180
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005181 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005182 default: break;
5183 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005184 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5185 // Handle set{eq|ne} <intrinsic>, intcst.
5186 switch (II->getIntrinsicID()) {
5187 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005188 case Intrinsic::bswap_i16:
5189 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005190 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005191 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005192 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005193 ByteSwap_16(CI->getZExtValue())));
5194 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005195 case Intrinsic::bswap_i32:
5196 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005197 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005198 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005199 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005200 ByteSwap_32(CI->getZExtValue())));
5201 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005202 case Intrinsic::bswap_i64:
5203 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005204 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005205 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005206 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005207 ByteSwap_64(CI->getZExtValue())));
5208 return &I;
5209 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005210 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005211 } else { // Not a ICMP_EQ/ICMP_NE
5212 // If the LHS is a cast from an integral value of the same size, then
5213 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005214 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5215 Value *CastOp = Cast->getOperand(0);
5216 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005217 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005218 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005219 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005220 // If this is an unsigned comparison, try to make the comparison use
5221 // smaller constant values.
5222 switch (I.getPredicate()) {
5223 default: break;
5224 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5225 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005226 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005227 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005228 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005229 break;
5230 }
5231 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5232 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005233 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005234 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5235 Constant::getNullValue(SrcTy));
5236 break;
5237 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005238 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005239
Chris Lattner2b55ea32004-02-23 07:16:20 +00005240 }
5241 }
Chris Lattnere967b342003-06-04 05:10:11 +00005242 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005243 }
5244
Reid Spencer266e42b2006-12-23 06:05:41 +00005245 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005246 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5247 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5248 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005249 case Instruction::GetElementPtr:
5250 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005251 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005252 bool isAllZeros = true;
5253 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5254 if (!isa<Constant>(LHSI->getOperand(i)) ||
5255 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5256 isAllZeros = false;
5257 break;
5258 }
5259 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005260 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005261 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5262 }
5263 break;
5264
Chris Lattner77c32c32005-04-23 15:31:55 +00005265 case Instruction::PHI:
5266 if (Instruction *NV = FoldOpIntoPhi(I))
5267 return NV;
5268 break;
5269 case Instruction::Select:
5270 // If either operand of the select is a constant, we can fold the
5271 // comparison into the select arms, which will cause one to be
5272 // constant folded and the select turned into a bitwise or.
5273 Value *Op1 = 0, *Op2 = 0;
5274 if (LHSI->hasOneUse()) {
5275 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5276 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005277 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5278 // Insert a new ICmp of the other select operand.
5279 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5280 LHSI->getOperand(2), RHSC,
5281 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005282 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5283 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005284 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5285 // Insert a new ICmp of the other select operand.
5286 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5287 LHSI->getOperand(1), RHSC,
5288 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005289 }
5290 }
Jeff Cohen82639852005-04-23 21:38:35 +00005291
Chris Lattner77c32c32005-04-23 15:31:55 +00005292 if (Op1)
5293 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5294 break;
5295 }
5296 }
5297
Reid Spencer266e42b2006-12-23 06:05:41 +00005298 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005299 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005300 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005301 return NI;
5302 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005303 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5304 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005305 return NI;
5306
Reid Spencer266e42b2006-12-23 06:05:41 +00005307 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005308 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5309 // now.
5310 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5311 if (isa<PointerType>(Op0->getType()) &&
5312 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005313 // We keep moving the cast from the left operand over to the right
5314 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005315 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005316
Chris Lattner64d87b02007-01-06 01:45:59 +00005317 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5318 // so eliminate it as well.
5319 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5320 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005321
Chris Lattner16930792003-11-03 04:25:02 +00005322 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005323 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005324 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005325 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005326 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005327 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005328 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005329 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005330 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005331 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005332 }
5333
5334 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005335 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005336 // This comes up when you have code like
5337 // int X = A < B;
5338 // if (X) ...
5339 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005340 // with a constant or another cast from the same type.
5341 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005342 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005343 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005344 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005345
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005346 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005347 Value *A, *B, *C, *D;
5348 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5349 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5350 Value *OtherVal = A == Op1 ? B : A;
5351 return new ICmpInst(I.getPredicate(), OtherVal,
5352 Constant::getNullValue(A->getType()));
5353 }
5354
5355 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5356 // A^c1 == C^c2 --> A == C^(c1^c2)
5357 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5358 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5359 if (Op1->hasOneUse()) {
5360 Constant *NC = ConstantExpr::getXor(C1, C2);
5361 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5362 return new ICmpInst(I.getPredicate(), A,
5363 InsertNewInstBefore(Xor, I));
5364 }
5365
5366 // A^B == A^D -> B == D
5367 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5368 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5369 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5370 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5371 }
5372 }
5373
5374 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5375 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005376 // A == (A^B) -> B == 0
5377 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005378 return new ICmpInst(I.getPredicate(), OtherVal,
5379 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005380 }
5381 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005382 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005383 return new ICmpInst(I.getPredicate(), B,
5384 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005385 }
5386 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005387 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005388 return new ICmpInst(I.getPredicate(), B,
5389 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005390 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005391
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005392 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5393 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5394 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5395 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5396 Value *X = 0, *Y = 0, *Z = 0;
5397
5398 if (A == C) {
5399 X = B; Y = D; Z = A;
5400 } else if (A == D) {
5401 X = B; Y = C; Z = A;
5402 } else if (B == C) {
5403 X = A; Y = D; Z = B;
5404 } else if (B == D) {
5405 X = A; Y = C; Z = B;
5406 }
5407
5408 if (X) { // Build (X^Y) & Z
5409 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5410 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5411 I.setOperand(0, Op1);
5412 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5413 return &I;
5414 }
5415 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005416 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005417 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005418}
5419
Reid Spencer266e42b2006-12-23 06:05:41 +00005420// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005421// We only handle extending casts so far.
5422//
Reid Spencer266e42b2006-12-23 06:05:41 +00005423Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5424 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005425 Value *LHSCIOp = LHSCI->getOperand(0);
5426 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005427 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005428 Value *RHSCIOp;
5429
Reid Spencer266e42b2006-12-23 06:05:41 +00005430 // We only handle extension cast instructions, so far. Enforce this.
5431 if (LHSCI->getOpcode() != Instruction::ZExt &&
5432 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005433 return 0;
5434
Reid Spencer266e42b2006-12-23 06:05:41 +00005435 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5436 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005437
Reid Spencer266e42b2006-12-23 06:05:41 +00005438 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005439 // Not an extension from the same type?
5440 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005441 if (RHSCIOp->getType() != LHSCIOp->getType())
5442 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005443
5444 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5445 // and the other is a zext), then we can't handle this.
5446 if (CI->getOpcode() != LHSCI->getOpcode())
5447 return 0;
5448
5449 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5450 // then we can't handle this.
5451 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5452 return 0;
5453
5454 // Okay, just insert a compare of the reduced operands now!
5455 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005456 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005457
Reid Spencer266e42b2006-12-23 06:05:41 +00005458 // If we aren't dealing with a constant on the RHS, exit early
5459 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5460 if (!CI)
5461 return 0;
5462
5463 // Compute the constant that would happen if we truncated to SrcTy then
5464 // reextended to DestTy.
5465 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5466 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5467
5468 // If the re-extended constant didn't change...
5469 if (Res2 == CI) {
5470 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5471 // For example, we might have:
5472 // %A = sext short %X to uint
5473 // %B = icmp ugt uint %A, 1330
5474 // It is incorrect to transform this into
5475 // %B = icmp ugt short %X, 1330
5476 // because %A may have negative value.
5477 //
5478 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5479 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005480 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005481 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5482 else
5483 return 0;
5484 }
5485
5486 // The re-extended constant changed so the constant cannot be represented
5487 // in the shorter type. Consequently, we cannot emit a simple comparison.
5488
5489 // First, handle some easy cases. We know the result cannot be equal at this
5490 // point so handle the ICI.isEquality() cases
5491 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005492 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005493 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005494 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005495
5496 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5497 // should have been folded away previously and not enter in here.
5498 Value *Result;
5499 if (isSignedCmp) {
5500 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005501 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005502 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005503 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005504 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005505 } else {
5506 // We're performing an unsigned comparison.
5507 if (isSignedExt) {
5508 // We're performing an unsigned comp with a sign extended value.
5509 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005510 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005511 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5512 NegOne, ICI.getName()), ICI);
5513 } else {
5514 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005515 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005516 }
5517 }
5518
5519 // Finally, return the value computed.
5520 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5521 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5522 return ReplaceInstUsesWith(ICI, Result);
5523 } else {
5524 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5525 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5526 "ICmp should be folded!");
5527 if (Constant *CI = dyn_cast<Constant>(Result))
5528 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5529 else
5530 return BinaryOperator::createNot(Result);
5531 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005532}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005533
Reid Spencer2341c222007-02-02 02:16:23 +00005534Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5535 return commonShiftTransforms(I);
5536}
5537
5538Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5539 return commonShiftTransforms(I);
5540}
5541
5542Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5543 return commonShiftTransforms(I);
5544}
5545
5546Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5547 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005548 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005549
5550 // shl X, 0 == X and shr X, 0 == X
5551 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005552 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005553 Op0 == Constant::getNullValue(Op0->getType()))
5554 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005555
Reid Spencer266e42b2006-12-23 06:05:41 +00005556 if (isa<UndefValue>(Op0)) {
5557 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005558 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005559 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5561 }
5562 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005563 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5564 return ReplaceInstUsesWith(I, Op0);
5565 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005566 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005567 }
5568
Chris Lattnerd4dee402006-11-10 23:38:52 +00005569 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5570 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005571 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005572 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005573 return ReplaceInstUsesWith(I, CSI);
5574
Chris Lattner183b3362004-04-09 19:05:30 +00005575 // Try to fold constant and into select arguments.
5576 if (isa<Constant>(Op0))
5577 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005579 return R;
5580
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005581 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005582 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005583 if (MaskedValueIsZero(Op0,
5584 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005585 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005586 }
5587 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005588
Reid Spencere0fc4df2006-10-20 07:07:24 +00005589 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005590 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5591 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005592 return 0;
5593}
5594
Reid Spencere0fc4df2006-10-20 07:07:24 +00005595Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005596 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005597 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005598
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005599 // See if we can simplify any instructions used by the instruction whose sole
5600 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005601 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5602 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5603 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005604 KnownZero, KnownOne))
5605 return &I;
5606
Chris Lattner14553932006-01-06 07:12:35 +00005607 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5608 // of a signed value.
5609 //
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005610 if (Op1->getValue().getActiveBits() > 64 || Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005611 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005612 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5613 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005614 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005615 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005616 }
Chris Lattner14553932006-01-06 07:12:35 +00005617 }
5618
5619 // ((X*C1) << C2) == (X * (C1 << C2))
5620 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5621 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5622 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5623 return BinaryOperator::createMul(BO->getOperand(0),
5624 ConstantExpr::getShl(BOOp, Op1));
5625
5626 // Try to fold constant and into select arguments.
5627 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5628 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5629 return R;
5630 if (isa<PHINode>(Op0))
5631 if (Instruction *NV = FoldOpIntoPhi(I))
5632 return NV;
5633
5634 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005635 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5636 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5637 Value *V1, *V2;
5638 ConstantInt *CC;
5639 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005640 default: break;
5641 case Instruction::Add:
5642 case Instruction::And:
5643 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005644 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005645 // These operators commute.
5646 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005647 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5648 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005649 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005650 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005651 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005652 Op0BO->getName());
5653 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005654 Instruction *X =
5655 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5656 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005657 InsertNewInstBefore(X, I); // (X + (Y << C))
5658 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005659 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005660 return BinaryOperator::createAnd(X, C2);
5661 }
Chris Lattner14553932006-01-06 07:12:35 +00005662
Chris Lattner797dee72005-09-18 06:30:59 +00005663 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005664 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005665 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005666 match(Op0BOOp1,
5667 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005668 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5669 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005670 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005671 Op0BO->getOperand(0), Op1,
5672 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005673 InsertNewInstBefore(YS, I); // (Y << C)
5674 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005675 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005676 V1->getName()+".mask");
5677 InsertNewInstBefore(XM, I); // X & (CC << C)
5678
5679 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5680 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005681 }
Chris Lattner14553932006-01-06 07:12:35 +00005682
Reid Spencer2f34b982007-02-02 14:41:37 +00005683 // FALL THROUGH.
5684 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005685 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005686 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5687 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005688 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005689 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005690 Op0BO->getOperand(1), Op1,
5691 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005692 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005693 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005694 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005695 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005696 InsertNewInstBefore(X, I); // (X + (Y << C))
5697 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005698 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005699 return BinaryOperator::createAnd(X, C2);
5700 }
Chris Lattner14553932006-01-06 07:12:35 +00005701
Chris Lattner1df0e982006-05-31 21:14:00 +00005702 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005703 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5704 match(Op0BO->getOperand(0),
5705 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005706 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005707 cast<BinaryOperator>(Op0BO->getOperand(0))
5708 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005709 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005710 Op0BO->getOperand(1), Op1,
5711 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005712 InsertNewInstBefore(YS, I); // (Y << C)
5713 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005714 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005715 V1->getName()+".mask");
5716 InsertNewInstBefore(XM, I); // X & (CC << C)
5717
Chris Lattner1df0e982006-05-31 21:14:00 +00005718 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005719 }
Chris Lattner14553932006-01-06 07:12:35 +00005720
Chris Lattner27cb9db2005-09-18 05:12:10 +00005721 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005722 }
Chris Lattner14553932006-01-06 07:12:35 +00005723 }
5724
5725
5726 // If the operand is an bitwise operator with a constant RHS, and the
5727 // shift is the only use, we can pull it out of the shift.
5728 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5729 bool isValid = true; // Valid only for And, Or, Xor
5730 bool highBitSet = false; // Transform if high bit of constant set?
5731
5732 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005733 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005734 case Instruction::Add:
5735 isValid = isLeftShift;
5736 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005737 case Instruction::Or:
5738 case Instruction::Xor:
5739 highBitSet = false;
5740 break;
5741 case Instruction::And:
5742 highBitSet = true;
5743 break;
Chris Lattner14553932006-01-06 07:12:35 +00005744 }
5745
5746 // If this is a signed shift right, and the high bit is modified
5747 // by the logical operation, do not perform the transformation.
5748 // The highBitSet boolean indicates the value of the high bit of
5749 // the constant which would cause it to be modified for this
5750 // operation.
5751 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005752 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005753 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005754 }
5755
5756 if (isValid) {
5757 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5758
5759 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005760 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005761 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005762 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005763
5764 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5765 NewRHS);
5766 }
5767 }
5768 }
5769 }
5770
Chris Lattnereb372a02006-01-06 07:52:12 +00005771 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005772 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5773 if (ShiftOp && !ShiftOp->isShift())
5774 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005775
Reid Spencere0fc4df2006-10-20 07:07:24 +00005776 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005777 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005778 uint32_t ShiftAmt1 = ShiftAmt1C->getValue().getActiveBits() > 64 ?
5779 TypeBits : (uint32_t)ShiftAmt1C->getZExtValue();
5780 uint32_t ShiftAmt2 = Op1->getValue().getActiveBits() > 64 ?
5781 TypeBits : (uint32_t)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005782 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5783 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5784 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005785
Chris Lattner3e009e82007-02-05 00:57:54 +00005786 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005787 if (AmtSum > TypeBits)
5788 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005789
5790 const IntegerType *Ty = cast<IntegerType>(I.getType());
5791
5792 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005793 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005794 return BinaryOperator::create(I.getOpcode(), X,
5795 ConstantInt::get(Ty, AmtSum));
5796 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5797 I.getOpcode() == Instruction::AShr) {
5798 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5799 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5800 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5801 I.getOpcode() == Instruction::LShr) {
5802 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5803 Instruction *Shift =
5804 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5805 InsertNewInstBefore(Shift, I);
5806
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005807 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005808 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005809 }
5810
Chris Lattner3e009e82007-02-05 00:57:54 +00005811 // Okay, if we get here, one shift must be left, and the other shift must be
5812 // right. See if the amounts are equal.
5813 if (ShiftAmt1 == ShiftAmt2) {
5814 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5815 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005816 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005817 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005818 }
5819 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5820 if (I.getOpcode() == Instruction::LShr) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005821 APInt Mask(Ty->getMask().lshr(ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005822 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005823 }
5824 // We can simplify ((X << C) >>s C) into a trunc + sext.
5825 // NOTE: we could do this for any C, but that would make 'unusual' integer
5826 // types. For now, just stick to ones well-supported by the code
5827 // generators.
5828 const Type *SExtType = 0;
5829 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005830 case 1 :
5831 case 8 :
5832 case 16 :
5833 case 32 :
5834 case 64 :
5835 case 128:
5836 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5837 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005838 default: break;
5839 }
5840 if (SExtType) {
5841 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5842 InsertNewInstBefore(NewTrunc, I);
5843 return new SExtInst(NewTrunc, Ty);
5844 }
5845 // Otherwise, we can't handle it yet.
5846 } else if (ShiftAmt1 < ShiftAmt2) {
5847 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005848
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005849 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005850 if (I.getOpcode() == Instruction::Shl) {
5851 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5852 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005853 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005854 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005855 InsertNewInstBefore(Shift, I);
5856
Reid Spencer52830322007-03-25 21:11:44 +00005857 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5858 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005859 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005860
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005861 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005862 if (I.getOpcode() == Instruction::LShr) {
5863 assert(ShiftOp->getOpcode() == Instruction::Shl);
5864 Instruction *Shift =
5865 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5866 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005867
Reid Spencer769a5a82007-03-26 17:18:58 +00005868 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005869 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005870 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005871
5872 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5873 } else {
5874 assert(ShiftAmt2 < ShiftAmt1);
5875 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5876
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005877 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005878 if (I.getOpcode() == Instruction::Shl) {
5879 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5880 ShiftOp->getOpcode() == Instruction::AShr);
5881 Instruction *Shift =
5882 BinaryOperator::create(ShiftOp->getOpcode(), X,
5883 ConstantInt::get(Ty, ShiftDiff));
5884 InsertNewInstBefore(Shift, I);
5885
Reid Spencer52830322007-03-25 21:11:44 +00005886 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005887 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005888 }
5889
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005890 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005891 if (I.getOpcode() == Instruction::LShr) {
5892 assert(ShiftOp->getOpcode() == Instruction::Shl);
5893 Instruction *Shift =
5894 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5895 InsertNewInstBefore(Shift, I);
5896
Reid Spencer441486c2007-03-26 23:45:51 +00005897 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005898 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005899 }
5900
5901 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005902 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005903 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005904 return 0;
5905}
5906
Chris Lattner48a44f72002-05-02 17:06:02 +00005907
Chris Lattner8f663e82005-10-29 04:36:15 +00005908/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5909/// expression. If so, decompose it, returning some value X, such that Val is
5910/// X*Scale+Offset.
5911///
5912static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5913 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005914 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005915 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005916 Offset = CI->getZExtValue();
5917 Scale = 1;
5918 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005919 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5920 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005921 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005922 if (I->getOpcode() == Instruction::Shl) {
5923 // This is a value scaled by '1 << the shift amt'.
5924 Scale = 1U << CUI->getZExtValue();
5925 Offset = 0;
5926 return I->getOperand(0);
5927 } else if (I->getOpcode() == Instruction::Mul) {
5928 // This value is scaled by 'CUI'.
5929 Scale = CUI->getZExtValue();
5930 Offset = 0;
5931 return I->getOperand(0);
5932 } else if (I->getOpcode() == Instruction::Add) {
5933 // We have X+C. Check to see if we really have (X*C2)+C1,
5934 // where C1 is divisible by C2.
5935 unsigned SubScale;
5936 Value *SubVal =
5937 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5938 Offset += CUI->getZExtValue();
5939 if (SubScale > 1 && (Offset % SubScale == 0)) {
5940 Scale = SubScale;
5941 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005942 }
5943 }
5944 }
5945 }
5946 }
5947
5948 // Otherwise, we can't look past this.
5949 Scale = 1;
5950 Offset = 0;
5951 return Val;
5952}
5953
5954
Chris Lattner216be912005-10-24 06:03:58 +00005955/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5956/// try to eliminate the cast by moving the type information into the alloc.
5957Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5958 AllocationInst &AI) {
5959 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005960 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005961
Chris Lattnerac87beb2005-10-24 06:22:12 +00005962 // Remove any uses of AI that are dead.
5963 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005964
Chris Lattnerac87beb2005-10-24 06:22:12 +00005965 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5966 Instruction *User = cast<Instruction>(*UI++);
5967 if (isInstructionTriviallyDead(User)) {
5968 while (UI != E && *UI == User)
5969 ++UI; // If this instruction uses AI more than once, don't break UI.
5970
Chris Lattnerac87beb2005-10-24 06:22:12 +00005971 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005972 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005973 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005974 }
5975 }
5976
Chris Lattner216be912005-10-24 06:03:58 +00005977 // Get the type really allocated and the type casted to.
5978 const Type *AllocElTy = AI.getAllocatedType();
5979 const Type *CastElTy = PTy->getElementType();
5980 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005981
Chris Lattner945e4372007-02-14 05:52:17 +00005982 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5983 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005984 if (CastElTyAlign < AllocElTyAlign) return 0;
5985
Chris Lattner46705b22005-10-24 06:35:18 +00005986 // If the allocation has multiple uses, only promote it if we are strictly
5987 // increasing the alignment of the resultant allocation. If we keep it the
5988 // same, we open the door to infinite loops of various kinds.
5989 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5990
Chris Lattner216be912005-10-24 06:03:58 +00005991 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5992 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005993 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005994
Chris Lattner8270c332005-10-29 03:19:53 +00005995 // See if we can satisfy the modulus by pulling a scale out of the array
5996 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005997 unsigned ArraySizeScale, ArrayOffset;
5998 Value *NumElements = // See if the array size is a decomposable linear expr.
5999 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6000
Chris Lattner8270c332005-10-29 03:19:53 +00006001 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6002 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006003 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6004 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006005
Chris Lattner8270c332005-10-29 03:19:53 +00006006 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6007 Value *Amt = 0;
6008 if (Scale == 1) {
6009 Amt = NumElements;
6010 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006011 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006012 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6013 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006014 Amt = ConstantExpr::getMul(
6015 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6016 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006017 else if (Scale != 1) {
6018 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6019 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006020 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006021 }
6022
Chris Lattner8f663e82005-10-29 04:36:15 +00006023 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006024 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006025 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6026 Amt = InsertNewInstBefore(Tmp, AI);
6027 }
6028
Chris Lattner216be912005-10-24 06:03:58 +00006029 AllocationInst *New;
6030 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006031 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006032 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006033 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006034 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006035 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006036
6037 // If the allocation has multiple uses, insert a cast and change all things
6038 // that used it to use the new cast. This will also hack on CI, but it will
6039 // die soon.
6040 if (!AI.hasOneUse()) {
6041 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006042 // New is the allocation instruction, pointer typed. AI is the original
6043 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6044 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006045 InsertNewInstBefore(NewCast, AI);
6046 AI.replaceAllUsesWith(NewCast);
6047 }
Chris Lattner216be912005-10-24 06:03:58 +00006048 return ReplaceInstUsesWith(CI, New);
6049}
6050
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006051/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006052/// and return it as type Ty without inserting any new casts and without
6053/// changing the computed value. This is used by code that tries to decide
6054/// whether promoting or shrinking integer operations to wider or smaller types
6055/// will allow us to eliminate a truncate or extend.
6056///
6057/// This is a truncation operation if Ty is smaller than V->getType(), or an
6058/// extension operation if Ty is larger.
6059static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006060 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006061 // We can always evaluate constants in another type.
6062 if (isa<ConstantInt>(V))
6063 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006064
6065 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006066 if (!I) return false;
6067
6068 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006069
6070 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006071 case Instruction::Add:
6072 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006073 case Instruction::And:
6074 case Instruction::Or:
6075 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006076 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006077 // These operators can all arbitrarily be extended or truncated.
6078 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6079 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006080
Chris Lattner960acb02006-11-29 07:18:39 +00006081 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006082 if (!I->hasOneUse()) return false;
6083 // If we are truncating the result of this SHL, and if it's a shift of a
6084 // constant amount, we can always perform a SHL in a smaller type.
6085 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6086 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6087 CI->getZExtValue() < Ty->getBitWidth())
6088 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6089 }
6090 break;
6091 case Instruction::LShr:
6092 if (!I->hasOneUse()) return false;
6093 // If this is a truncate of a logical shr, we can truncate it to a smaller
6094 // lshr iff we know that the bits we would otherwise be shifting in are
6095 // already zeros.
6096 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006097 uint32_t BitWidth = OrigTy->getBitWidth();
Zhou Sheng755f04b2007-03-23 02:39:25 +00006098 if (Ty->getBitWidth() < BitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006099 MaskedValueIsZero(I->getOperand(0),
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006100 APInt::getAllOnesValue(BitWidth) &
6101 APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6102 && CI->getZExtValue() < Ty->getBitWidth()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006103 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6104 }
6105 }
Chris Lattner960acb02006-11-29 07:18:39 +00006106 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006107 case Instruction::Trunc:
6108 case Instruction::ZExt:
6109 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006110 // If this is a cast from the destination type, we can trivially eliminate
6111 // it, and this will remove a cast overall.
6112 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006113 // If the first operand is itself a cast, and is eliminable, do not count
6114 // this as an eliminable cast. We would prefer to eliminate those two
6115 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006116 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006117 return true;
6118
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006119 ++NumCastsRemoved;
6120 return true;
6121 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006122 break;
6123 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006124 // TODO: Can handle more cases here.
6125 break;
6126 }
6127
6128 return false;
6129}
6130
6131/// EvaluateInDifferentType - Given an expression that
6132/// CanEvaluateInDifferentType returns true for, actually insert the code to
6133/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006134Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006135 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006136 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006137 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006138
6139 // Otherwise, it must be an instruction.
6140 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006141 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006142 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006143 case Instruction::Add:
6144 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006145 case Instruction::And:
6146 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006147 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006148 case Instruction::AShr:
6149 case Instruction::LShr:
6150 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006151 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006152 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6153 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6154 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006155 break;
6156 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006157 case Instruction::Trunc:
6158 case Instruction::ZExt:
6159 case Instruction::SExt:
6160 case Instruction::BitCast:
6161 // If the source type of the cast is the type we're trying for then we can
6162 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006163 if (I->getOperand(0)->getType() == Ty)
6164 return I->getOperand(0);
6165
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006166 // Some other kind of cast, which shouldn't happen, so just ..
6167 // FALL THROUGH
6168 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006169 // TODO: Can handle more cases here.
6170 assert(0 && "Unreachable!");
6171 break;
6172 }
6173
6174 return InsertNewInstBefore(Res, *I);
6175}
6176
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006177/// @brief Implement the transforms common to all CastInst visitors.
6178Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006179 Value *Src = CI.getOperand(0);
6180
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006181 // Casting undef to anything results in undef so might as just replace it and
6182 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006183 if (isa<UndefValue>(Src)) // cast undef -> undef
6184 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6185
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006186 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6187 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006188 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006189 if (Instruction::CastOps opc =
6190 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6191 // The first cast (CSrc) is eliminable so we need to fix up or replace
6192 // the second cast (CI). CSrc will then have a good chance of being dead.
6193 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006194 }
6195 }
Chris Lattner03841652004-05-25 04:29:21 +00006196
Chris Lattnerd0d51602003-06-21 23:12:02 +00006197 // If casting the result of a getelementptr instruction with no offset, turn
6198 // this into a cast of the original pointer!
6199 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006200 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006201 bool AllZeroOperands = true;
6202 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6203 if (!isa<Constant>(GEP->getOperand(i)) ||
6204 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6205 AllZeroOperands = false;
6206 break;
6207 }
6208 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006209 // Changing the cast operand is usually not a good idea but it is safe
6210 // here because the pointer operand is being replaced with another
6211 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006212 CI.setOperand(0, GEP->getOperand(0));
6213 return &CI;
6214 }
6215 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006216
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006217 // If we are casting a malloc or alloca to a pointer to a type of the same
6218 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006219 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006220 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6221 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006222
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006223 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006224 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6225 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6226 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006227
6228 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006229 if (isa<PHINode>(Src))
6230 if (Instruction *NV = FoldOpIntoPhi(CI))
6231 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006232
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006233 return 0;
6234}
6235
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006236/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6237/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006238/// cases.
6239/// @brief Implement the transforms common to CastInst with integer operands
6240Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6241 if (Instruction *Result = commonCastTransforms(CI))
6242 return Result;
6243
6244 Value *Src = CI.getOperand(0);
6245 const Type *SrcTy = Src->getType();
6246 const Type *DestTy = CI.getType();
6247 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6248 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6249
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006250 // See if we can simplify any instructions used by the LHS whose sole
6251 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006252 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6253 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006254 KnownZero, KnownOne))
6255 return &CI;
6256
6257 // If the source isn't an instruction or has more than one use then we
6258 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006259 Instruction *SrcI = dyn_cast<Instruction>(Src);
6260 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006261 return 0;
6262
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006263 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006264 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006265 if (!isa<BitCastInst>(CI) &&
6266 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6267 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006268 // If this cast is a truncate, evaluting in a different type always
6269 // eliminates the cast, so it is always a win. If this is a noop-cast
6270 // this just removes a noop cast which isn't pointful, but simplifies
6271 // the code. If this is a zero-extension, we need to do an AND to
6272 // maintain the clear top-part of the computation, so we require that
6273 // the input have eliminated at least one cast. If this is a sign
6274 // extension, we insert two new casts (to do the extension) so we
6275 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006276 bool DoXForm;
6277 switch (CI.getOpcode()) {
6278 default:
6279 // All the others use floating point so we shouldn't actually
6280 // get here because of the check above.
6281 assert(0 && "Unknown cast type");
6282 case Instruction::Trunc:
6283 DoXForm = true;
6284 break;
6285 case Instruction::ZExt:
6286 DoXForm = NumCastsRemoved >= 1;
6287 break;
6288 case Instruction::SExt:
6289 DoXForm = NumCastsRemoved >= 2;
6290 break;
6291 case Instruction::BitCast:
6292 DoXForm = false;
6293 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006294 }
6295
6296 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006297 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6298 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006299 assert(Res->getType() == DestTy);
6300 switch (CI.getOpcode()) {
6301 default: assert(0 && "Unknown cast type!");
6302 case Instruction::Trunc:
6303 case Instruction::BitCast:
6304 // Just replace this cast with the result.
6305 return ReplaceInstUsesWith(CI, Res);
6306 case Instruction::ZExt: {
6307 // We need to emit an AND to clear the high bits.
6308 assert(SrcBitSize < DestBitSize && "Not a zext?");
Zhou Sheng2777a312007-03-28 09:19:01 +00006309 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006310 return BinaryOperator::createAnd(Res, C);
6311 }
6312 case Instruction::SExt:
6313 // We need to emit a cast to truncate, then a cast to sext.
6314 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006315 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6316 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006317 }
6318 }
6319 }
6320
6321 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6322 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6323
6324 switch (SrcI->getOpcode()) {
6325 case Instruction::Add:
6326 case Instruction::Mul:
6327 case Instruction::And:
6328 case Instruction::Or:
6329 case Instruction::Xor:
6330 // If we are discarding information, or just changing the sign,
6331 // rewrite.
6332 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6333 // Don't insert two casts if they cannot be eliminated. We allow
6334 // two casts to be inserted if the sizes are the same. This could
6335 // only be converting signedness, which is a noop.
6336 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006337 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6338 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006339 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006340 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6341 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6342 return BinaryOperator::create(
6343 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006344 }
6345 }
6346
6347 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6348 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6349 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006350 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006351 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006352 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006353 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6354 }
6355 break;
6356 case Instruction::SDiv:
6357 case Instruction::UDiv:
6358 case Instruction::SRem:
6359 case Instruction::URem:
6360 // If we are just changing the sign, rewrite.
6361 if (DestBitSize == SrcBitSize) {
6362 // Don't insert two casts if they cannot be eliminated. We allow
6363 // two casts to be inserted if the sizes are the same. This could
6364 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006365 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6366 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006367 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6368 Op0, DestTy, SrcI);
6369 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6370 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006371 return BinaryOperator::create(
6372 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6373 }
6374 }
6375 break;
6376
6377 case Instruction::Shl:
6378 // Allow changing the sign of the source operand. Do not allow
6379 // changing the size of the shift, UNLESS the shift amount is a
6380 // constant. We must not change variable sized shifts to a smaller
6381 // size, because it is undefined to shift more bits out than exist
6382 // in the value.
6383 if (DestBitSize == SrcBitSize ||
6384 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006385 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6386 Instruction::BitCast : Instruction::Trunc);
6387 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006388 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006389 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006390 }
6391 break;
6392 case Instruction::AShr:
6393 // If this is a signed shr, and if all bits shifted in are about to be
6394 // truncated off, turn it into an unsigned shr to allow greater
6395 // simplifications.
6396 if (DestBitSize < SrcBitSize &&
6397 isa<ConstantInt>(Op1)) {
6398 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6399 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6400 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006401 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006402 }
6403 }
6404 break;
6405
Reid Spencer266e42b2006-12-23 06:05:41 +00006406 case Instruction::ICmp:
6407 // If we are just checking for a icmp eq of a single bit and casting it
6408 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006409 // cast to integer to avoid the comparison.
6410 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer4154e732007-03-22 20:56:53 +00006411 APInt Op1CV(Op1C->getValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006412 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6413 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6414 // cast (X == 1) to int --> X iff X has only the low bit set.
6415 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6416 // cast (X != 0) to int --> X iff X has only the low bit set.
6417 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6418 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6419 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006420 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006421 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006422 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6423 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6424 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006425 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006426
6427 // This only works for EQ and NE
6428 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6429 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6430 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006431
Zhou Sheng0900993e2007-03-23 03:13:21 +00006432 APInt KnownZeroMask(KnownZero ^ TypeMask);
6433 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006434 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006435 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006436 // (X&4) == 2 --> false
6437 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006438 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006439 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006440 return ReplaceInstUsesWith(CI, Res);
6441 }
6442
Zhou Sheng0900993e2007-03-23 03:13:21 +00006443 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006444 Value *In = Op0;
6445 if (ShiftAmt) {
6446 // Perform a logical shr by shiftamt.
6447 // Insert the shift to put the result in the low bit.
6448 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006449 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006450 ConstantInt::get(In->getType(), ShiftAmt),
6451 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006452 }
6453
Reid Spencer266e42b2006-12-23 06:05:41 +00006454 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006455 Constant *One = ConstantInt::get(In->getType(), 1);
6456 In = BinaryOperator::createXor(In, One, "tmp");
6457 InsertNewInstBefore(cast<Instruction>(In), CI);
6458 }
6459
6460 if (CI.getType() == In->getType())
6461 return ReplaceInstUsesWith(CI, In);
6462 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006463 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006464 }
6465 }
6466 }
6467 break;
6468 }
6469 return 0;
6470}
6471
6472Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006473 if (Instruction *Result = commonIntCastTransforms(CI))
6474 return Result;
6475
6476 Value *Src = CI.getOperand(0);
6477 const Type *Ty = CI.getType();
6478 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00006479 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006480
6481 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6482 switch (SrcI->getOpcode()) {
6483 default: break;
6484 case Instruction::LShr:
6485 // We can shrink lshr to something smaller if we know the bits shifted in
6486 // are already zeros.
6487 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6488 unsigned ShAmt = ShAmtV->getZExtValue();
6489
6490 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006491 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006492 Value* SrcIOp0 = SrcI->getOperand(0);
6493 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006494 if (ShAmt >= DestBitWidth) // All zeros.
6495 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6496
6497 // Okay, we can shrink this. Truncate the input, then return a new
6498 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006499 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6500 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6501 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006502 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006503 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006504 } else { // This is a variable shr.
6505
6506 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6507 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6508 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006509 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006510 Value *One = ConstantInt::get(SrcI->getType(), 1);
6511
Reid Spencer2341c222007-02-02 02:16:23 +00006512 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006513 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006514 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006515 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6516 SrcI->getOperand(0),
6517 "tmp"), CI);
6518 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006519 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006520 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006521 }
6522 break;
6523 }
6524 }
6525
6526 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006527}
6528
6529Instruction *InstCombiner::visitZExt(CastInst &CI) {
6530 // If one of the common conversion will work ..
6531 if (Instruction *Result = commonIntCastTransforms(CI))
6532 return Result;
6533
6534 Value *Src = CI.getOperand(0);
6535
6536 // If this is a cast of a cast
6537 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006538 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6539 // types and if the sizes are just right we can convert this into a logical
6540 // 'and' which will be much cheaper than the pair of casts.
6541 if (isa<TruncInst>(CSrc)) {
6542 // Get the sizes of the types involved
6543 Value *A = CSrc->getOperand(0);
6544 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6545 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6546 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6547 // If we're actually extending zero bits and the trunc is a no-op
6548 if (MidSize < DstSize && SrcSize == DstSize) {
6549 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006550 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006551 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006552 Instruction *And =
6553 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6554 // Unfortunately, if the type changed, we need to cast it back.
6555 if (And->getType() != CI.getType()) {
6556 And->setName(CSrc->getName()+".mask");
6557 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006558 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006559 }
6560 return And;
6561 }
6562 }
6563 }
6564
6565 return 0;
6566}
6567
6568Instruction *InstCombiner::visitSExt(CastInst &CI) {
6569 return commonIntCastTransforms(CI);
6570}
6571
6572Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6573 return commonCastTransforms(CI);
6574}
6575
6576Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6577 return commonCastTransforms(CI);
6578}
6579
6580Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006581 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006582}
6583
6584Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006585 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006586}
6587
6588Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6589 return commonCastTransforms(CI);
6590}
6591
6592Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6593 return commonCastTransforms(CI);
6594}
6595
6596Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006597 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006598}
6599
6600Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6601 return commonCastTransforms(CI);
6602}
6603
6604Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6605
6606 // If the operands are integer typed then apply the integer transforms,
6607 // otherwise just apply the common ones.
6608 Value *Src = CI.getOperand(0);
6609 const Type *SrcTy = Src->getType();
6610 const Type *DestTy = CI.getType();
6611
Chris Lattner03c49532007-01-15 02:27:26 +00006612 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006613 if (Instruction *Result = commonIntCastTransforms(CI))
6614 return Result;
6615 } else {
6616 if (Instruction *Result = commonCastTransforms(CI))
6617 return Result;
6618 }
6619
6620
6621 // Get rid of casts from one type to the same type. These are useless and can
6622 // be replaced by the operand.
6623 if (DestTy == Src->getType())
6624 return ReplaceInstUsesWith(CI, Src);
6625
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006626 // If the source and destination are pointers, and this cast is equivalent to
6627 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6628 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006629 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6630 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6631 const Type *DstElTy = DstPTy->getElementType();
6632 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006633
Reid Spencerc635f472006-12-31 05:48:39 +00006634 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006635 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006636 while (SrcElTy != DstElTy &&
6637 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6638 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6639 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006640 ++NumZeros;
6641 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006642
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006643 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006644 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006645 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6646 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006647 }
6648 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006649 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006650
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006651 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6652 if (SVI->hasOneUse()) {
6653 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6654 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006655 if (isa<VectorType>(DestTy) &&
6656 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006657 SVI->getType()->getNumElements()) {
6658 CastInst *Tmp;
6659 // If either of the operands is a cast from CI.getType(), then
6660 // evaluating the shuffle in the casted destination's type will allow
6661 // us to eliminate at least one cast.
6662 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6663 Tmp->getOperand(0)->getType() == DestTy) ||
6664 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6665 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006666 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6667 SVI->getOperand(0), DestTy, &CI);
6668 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6669 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006670 // Return a new shuffle vector. Use the same element ID's, as we
6671 // know the vector types match #elts.
6672 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006673 }
6674 }
6675 }
6676 }
Chris Lattner260ab202002-04-18 17:39:14 +00006677 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006678}
6679
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006680/// GetSelectFoldableOperands - We want to turn code that looks like this:
6681/// %C = or %A, %B
6682/// %D = select %cond, %C, %A
6683/// into:
6684/// %C = select %cond, %B, 0
6685/// %D = or %A, %C
6686///
6687/// Assuming that the specified instruction is an operand to the select, return
6688/// a bitmask indicating which operands of this instruction are foldable if they
6689/// equal the other incoming value of the select.
6690///
6691static unsigned GetSelectFoldableOperands(Instruction *I) {
6692 switch (I->getOpcode()) {
6693 case Instruction::Add:
6694 case Instruction::Mul:
6695 case Instruction::And:
6696 case Instruction::Or:
6697 case Instruction::Xor:
6698 return 3; // Can fold through either operand.
6699 case Instruction::Sub: // Can only fold on the amount subtracted.
6700 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006701 case Instruction::LShr:
6702 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006703 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006704 default:
6705 return 0; // Cannot fold
6706 }
6707}
6708
6709/// GetSelectFoldableConstant - For the same transformation as the previous
6710/// function, return the identity constant that goes into the select.
6711static Constant *GetSelectFoldableConstant(Instruction *I) {
6712 switch (I->getOpcode()) {
6713 default: assert(0 && "This cannot happen!"); abort();
6714 case Instruction::Add:
6715 case Instruction::Sub:
6716 case Instruction::Or:
6717 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006718 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006719 case Instruction::LShr:
6720 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006721 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006722 case Instruction::And:
6723 return ConstantInt::getAllOnesValue(I->getType());
6724 case Instruction::Mul:
6725 return ConstantInt::get(I->getType(), 1);
6726 }
6727}
6728
Chris Lattner411336f2005-01-19 21:50:18 +00006729/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6730/// have the same opcode and only one use each. Try to simplify this.
6731Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6732 Instruction *FI) {
6733 if (TI->getNumOperands() == 1) {
6734 // If this is a non-volatile load or a cast from the same type,
6735 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006736 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006737 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6738 return 0;
6739 } else {
6740 return 0; // unknown unary op.
6741 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006742
Chris Lattner411336f2005-01-19 21:50:18 +00006743 // Fold this by inserting a select from the input values.
6744 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6745 FI->getOperand(0), SI.getName()+".v");
6746 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006747 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6748 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006749 }
6750
Reid Spencer2341c222007-02-02 02:16:23 +00006751 // Only handle binary operators here.
6752 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006753 return 0;
6754
6755 // Figure out if the operations have any operands in common.
6756 Value *MatchOp, *OtherOpT, *OtherOpF;
6757 bool MatchIsOpZero;
6758 if (TI->getOperand(0) == FI->getOperand(0)) {
6759 MatchOp = TI->getOperand(0);
6760 OtherOpT = TI->getOperand(1);
6761 OtherOpF = FI->getOperand(1);
6762 MatchIsOpZero = true;
6763 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6764 MatchOp = TI->getOperand(1);
6765 OtherOpT = TI->getOperand(0);
6766 OtherOpF = FI->getOperand(0);
6767 MatchIsOpZero = false;
6768 } else if (!TI->isCommutative()) {
6769 return 0;
6770 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6771 MatchOp = TI->getOperand(0);
6772 OtherOpT = TI->getOperand(1);
6773 OtherOpF = FI->getOperand(0);
6774 MatchIsOpZero = true;
6775 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6776 MatchOp = TI->getOperand(1);
6777 OtherOpT = TI->getOperand(0);
6778 OtherOpF = FI->getOperand(1);
6779 MatchIsOpZero = true;
6780 } else {
6781 return 0;
6782 }
6783
6784 // If we reach here, they do have operations in common.
6785 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6786 OtherOpF, SI.getName()+".v");
6787 InsertNewInstBefore(NewSI, SI);
6788
6789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6790 if (MatchIsOpZero)
6791 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6792 else
6793 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006794 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006795 assert(0 && "Shouldn't get here");
6796 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006797}
6798
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006799Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006800 Value *CondVal = SI.getCondition();
6801 Value *TrueVal = SI.getTrueValue();
6802 Value *FalseVal = SI.getFalseValue();
6803
6804 // select true, X, Y -> X
6805 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006806 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006807 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006808
6809 // select C, X, X -> X
6810 if (TrueVal == FalseVal)
6811 return ReplaceInstUsesWith(SI, TrueVal);
6812
Chris Lattner81a7a232004-10-16 18:11:37 +00006813 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6814 return ReplaceInstUsesWith(SI, FalseVal);
6815 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6816 return ReplaceInstUsesWith(SI, TrueVal);
6817 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6818 if (isa<Constant>(TrueVal))
6819 return ReplaceInstUsesWith(SI, TrueVal);
6820 else
6821 return ReplaceInstUsesWith(SI, FalseVal);
6822 }
6823
Reid Spencer542964f2007-01-11 18:21:29 +00006824 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006825 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006826 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006827 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006828 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006829 } else {
6830 // Change: A = select B, false, C --> A = and !B, C
6831 Value *NotCond =
6832 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6833 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006834 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006835 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006836 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006837 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006838 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006839 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006840 } else {
6841 // Change: A = select B, C, true --> A = or !B, C
6842 Value *NotCond =
6843 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6844 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006845 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006846 }
6847 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006848 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006849
Chris Lattner183b3362004-04-09 19:05:30 +00006850 // Selecting between two integer constants?
6851 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6852 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6853 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006854 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006855 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006856 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006857 // select C, 0, 1 -> cast !C to int
6858 Value *NotCond =
6859 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006860 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006861 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006862 }
Chris Lattner35167c32004-06-09 07:59:58 +00006863
Reid Spencer266e42b2006-12-23 06:05:41 +00006864 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006865
Reid Spencer266e42b2006-12-23 06:05:41 +00006866 // (x <s 0) ? -1 : 0 -> ashr x, 31
6867 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006868 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006869 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6870 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006871 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006872 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006873 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006874 else {
6875 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006876 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006877 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006878 }
6879
6880 if (CanXForm) {
6881 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006882 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006883 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006884 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006885 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6886 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6887 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006888 InsertNewInstBefore(SRA, SI);
6889
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006890 // Finally, convert to the type of the select RHS. We figure out
6891 // if this requires a SExt, Trunc or BitCast based on the sizes.
6892 Instruction::CastOps opc = Instruction::BitCast;
6893 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6894 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6895 if (SRASize < SISize)
6896 opc = Instruction::SExt;
6897 else if (SRASize > SISize)
6898 opc = Instruction::Trunc;
6899 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006900 }
6901 }
6902
6903
6904 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006905 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006906 // non-constant value, eliminate this whole mess. This corresponds to
6907 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006908 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006909 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006910 cast<Constant>(IC->getOperand(1))->isNullValue())
6911 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6912 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006913 isa<ConstantInt>(ICA->getOperand(1)) &&
6914 (ICA->getOperand(1) == TrueValC ||
6915 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006916 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6917 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006918 // know whether we have a icmp_ne or icmp_eq and whether the
6919 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006920 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006921 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006922 Value *V = ICA;
6923 if (ShouldNotVal)
6924 V = InsertNewInstBefore(BinaryOperator::create(
6925 Instruction::Xor, V, ICA->getOperand(1)), SI);
6926 return ReplaceInstUsesWith(SI, V);
6927 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006928 }
Chris Lattner533bc492004-03-30 19:37:13 +00006929 }
Chris Lattner623fba12004-04-10 22:21:27 +00006930
6931 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006932 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6933 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006934 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006935 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006936 return ReplaceInstUsesWith(SI, FalseVal);
6937 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006938 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006939 return ReplaceInstUsesWith(SI, TrueVal);
6940 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6941
Reid Spencer266e42b2006-12-23 06:05:41 +00006942 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006943 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006944 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006945 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006946 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006947 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6948 return ReplaceInstUsesWith(SI, TrueVal);
6949 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6950 }
6951 }
6952
6953 // See if we are selecting two values based on a comparison of the two values.
6954 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6955 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6956 // Transform (X == Y) ? X : Y -> Y
6957 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6958 return ReplaceInstUsesWith(SI, FalseVal);
6959 // Transform (X != Y) ? X : Y -> X
6960 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6961 return ReplaceInstUsesWith(SI, TrueVal);
6962 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6963
6964 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6965 // Transform (X == Y) ? Y : X -> X
6966 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6967 return ReplaceInstUsesWith(SI, FalseVal);
6968 // Transform (X != Y) ? Y : X -> Y
6969 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006970 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006971 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6972 }
6973 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006974
Chris Lattnera04c9042005-01-13 22:52:24 +00006975 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6976 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6977 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006978 Instruction *AddOp = 0, *SubOp = 0;
6979
Chris Lattner411336f2005-01-19 21:50:18 +00006980 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6981 if (TI->getOpcode() == FI->getOpcode())
6982 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6983 return IV;
6984
6985 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6986 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006987 if (TI->getOpcode() == Instruction::Sub &&
6988 FI->getOpcode() == Instruction::Add) {
6989 AddOp = FI; SubOp = TI;
6990 } else if (FI->getOpcode() == Instruction::Sub &&
6991 TI->getOpcode() == Instruction::Add) {
6992 AddOp = TI; SubOp = FI;
6993 }
6994
6995 if (AddOp) {
6996 Value *OtherAddOp = 0;
6997 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6998 OtherAddOp = AddOp->getOperand(1);
6999 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7000 OtherAddOp = AddOp->getOperand(0);
7001 }
7002
7003 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007004 // So at this point we know we have (Y -> OtherAddOp):
7005 // select C, (add X, Y), (sub X, Z)
7006 Value *NegVal; // Compute -Z
7007 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7008 NegVal = ConstantExpr::getNeg(C);
7009 } else {
7010 NegVal = InsertNewInstBefore(
7011 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007012 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007013
7014 Value *NewTrueOp = OtherAddOp;
7015 Value *NewFalseOp = NegVal;
7016 if (AddOp != TI)
7017 std::swap(NewTrueOp, NewFalseOp);
7018 Instruction *NewSel =
7019 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7020
7021 NewSel = InsertNewInstBefore(NewSel, SI);
7022 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007023 }
7024 }
7025 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007026
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007027 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007028 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007029 // See the comment above GetSelectFoldableOperands for a description of the
7030 // transformation we are doing here.
7031 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7032 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7033 !isa<Constant>(FalseVal))
7034 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7035 unsigned OpToFold = 0;
7036 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7037 OpToFold = 1;
7038 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7039 OpToFold = 2;
7040 }
7041
7042 if (OpToFold) {
7043 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007044 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007045 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007046 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007047 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7049 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007050 else {
7051 assert(0 && "Unknown instruction!!");
7052 }
7053 }
7054 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007055
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007056 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7057 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7058 !isa<Constant>(TrueVal))
7059 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7060 unsigned OpToFold = 0;
7061 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7062 OpToFold = 1;
7063 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7064 OpToFold = 2;
7065 }
7066
7067 if (OpToFold) {
7068 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007069 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007070 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007071 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007072 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007073 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7074 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007075 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007076 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007077 }
7078 }
7079 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007080
7081 if (BinaryOperator::isNot(CondVal)) {
7082 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7083 SI.setOperand(1, FalseVal);
7084 SI.setOperand(2, TrueVal);
7085 return &SI;
7086 }
7087
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007088 return 0;
7089}
7090
Chris Lattner82f2ef22006-03-06 20:18:44 +00007091/// GetKnownAlignment - If the specified pointer has an alignment that we can
7092/// determine, return it, otherwise return 0.
7093static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7094 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7095 unsigned Align = GV->getAlignment();
7096 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007097 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007098 return Align;
7099 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7100 unsigned Align = AI->getAlignment();
7101 if (Align == 0 && TD) {
7102 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007103 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007104 else if (isa<MallocInst>(AI)) {
7105 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007106 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007107 Align =
7108 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007109 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007110 Align =
7111 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007112 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007113 }
7114 }
7115 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007116 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007117 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007118 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007119 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007120 if (isa<PointerType>(CI->getOperand(0)->getType()))
7121 return GetKnownAlignment(CI->getOperand(0), TD);
7122 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007123 } else if (isa<GetElementPtrInst>(V) ||
7124 (isa<ConstantExpr>(V) &&
7125 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7126 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007127 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7128 if (BaseAlignment == 0) return 0;
7129
7130 // If all indexes are zero, it is just the alignment of the base pointer.
7131 bool AllZeroOperands = true;
7132 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7133 if (!isa<Constant>(GEPI->getOperand(i)) ||
7134 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7135 AllZeroOperands = false;
7136 break;
7137 }
7138 if (AllZeroOperands)
7139 return BaseAlignment;
7140
7141 // Otherwise, if the base alignment is >= the alignment we expect for the
7142 // base pointer type, then we know that the resultant pointer is aligned at
7143 // least as much as its type requires.
7144 if (!TD) return 0;
7145
7146 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007147 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007148 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007149 <= BaseAlignment) {
7150 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007151 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007152 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007153 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007154 return 0;
7155 }
7156 return 0;
7157}
7158
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007159
Chris Lattnerc66b2232006-01-13 20:11:04 +00007160/// visitCallInst - CallInst simplification. This mostly only handles folding
7161/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7162/// the heavy lifting.
7163///
Chris Lattner970c33a2003-06-19 17:00:31 +00007164Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007165 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7166 if (!II) return visitCallSite(&CI);
7167
Chris Lattner51ea1272004-02-28 05:22:00 +00007168 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7169 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007170 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007171 bool Changed = false;
7172
7173 // memmove/cpy/set of zero bytes is a noop.
7174 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7175 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7176
Chris Lattner00648e12004-10-12 04:52:52 +00007177 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007178 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007179 // Replace the instruction with just byte operations. We would
7180 // transform other cases to loads/stores, but we don't know if
7181 // alignment is sufficient.
7182 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007183 }
7184
Chris Lattner00648e12004-10-12 04:52:52 +00007185 // If we have a memmove and the source operation is a constant global,
7186 // then the source and dest pointers can't alias, so we can change this
7187 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007188 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007189 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7190 if (GVSrc->isConstant()) {
7191 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007192 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007193 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007194 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007195 Name = "llvm.memcpy.i32";
7196 else
7197 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007198 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007199 CI.getCalledFunction()->getFunctionType());
7200 CI.setOperand(0, MemCpy);
7201 Changed = true;
7202 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007203 }
Chris Lattner00648e12004-10-12 04:52:52 +00007204
Chris Lattner82f2ef22006-03-06 20:18:44 +00007205 // If we can determine a pointer alignment that is bigger than currently
7206 // set, update the alignment.
7207 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7208 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7209 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7210 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007211 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007212 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007213 Changed = true;
7214 }
7215 } else if (isa<MemSetInst>(MI)) {
7216 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007217 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007218 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007219 Changed = true;
7220 }
7221 }
7222
Chris Lattnerc66b2232006-01-13 20:11:04 +00007223 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007224 } else {
7225 switch (II->getIntrinsicID()) {
7226 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007227 case Intrinsic::ppc_altivec_lvx:
7228 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007229 case Intrinsic::x86_sse_loadu_ps:
7230 case Intrinsic::x86_sse2_loadu_pd:
7231 case Intrinsic::x86_sse2_loadu_dq:
7232 // Turn PPC lvx -> load if the pointer is known aligned.
7233 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007234 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007235 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007236 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007237 return new LoadInst(Ptr);
7238 }
7239 break;
7240 case Intrinsic::ppc_altivec_stvx:
7241 case Intrinsic::ppc_altivec_stvxl:
7242 // Turn stvx -> store if the pointer is known aligned.
7243 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007244 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007245 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7246 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007247 return new StoreInst(II->getOperand(1), Ptr);
7248 }
7249 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007250 case Intrinsic::x86_sse_storeu_ps:
7251 case Intrinsic::x86_sse2_storeu_pd:
7252 case Intrinsic::x86_sse2_storeu_dq:
7253 case Intrinsic::x86_sse2_storel_dq:
7254 // Turn X86 storeu -> store if the pointer is known aligned.
7255 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7256 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007257 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7258 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007259 return new StoreInst(II->getOperand(2), Ptr);
7260 }
7261 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007262
7263 case Intrinsic::x86_sse_cvttss2si: {
7264 // These intrinsics only demands the 0th element of its input vector. If
7265 // we can simplify the input based on that, do so now.
7266 uint64_t UndefElts;
7267 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7268 UndefElts)) {
7269 II->setOperand(1, V);
7270 return II;
7271 }
7272 break;
7273 }
7274
Chris Lattnere79d2492006-04-06 19:19:17 +00007275 case Intrinsic::ppc_altivec_vperm:
7276 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007277 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007278 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7279
7280 // Check that all of the elements are integer constants or undefs.
7281 bool AllEltsOk = true;
7282 for (unsigned i = 0; i != 16; ++i) {
7283 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7284 !isa<UndefValue>(Mask->getOperand(i))) {
7285 AllEltsOk = false;
7286 break;
7287 }
7288 }
7289
7290 if (AllEltsOk) {
7291 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007292 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7293 II->getOperand(1), Mask->getType(), CI);
7294 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7295 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007296 Value *Result = UndefValue::get(Op0->getType());
7297
7298 // Only extract each element once.
7299 Value *ExtractedElts[32];
7300 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7301
7302 for (unsigned i = 0; i != 16; ++i) {
7303 if (isa<UndefValue>(Mask->getOperand(i)))
7304 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007305 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007306 Idx &= 31; // Match the hardware behavior.
7307
7308 if (ExtractedElts[Idx] == 0) {
7309 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007310 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007311 InsertNewInstBefore(Elt, CI);
7312 ExtractedElts[Idx] = Elt;
7313 }
7314
7315 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007316 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007317 InsertNewInstBefore(cast<Instruction>(Result), CI);
7318 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007319 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007320 }
7321 }
7322 break;
7323
Chris Lattner503221f2006-01-13 21:28:09 +00007324 case Intrinsic::stackrestore: {
7325 // If the save is right next to the restore, remove the restore. This can
7326 // happen when variable allocas are DCE'd.
7327 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7328 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7329 BasicBlock::iterator BI = SS;
7330 if (&*++BI == II)
7331 return EraseInstFromFunction(CI);
7332 }
7333 }
7334
7335 // If the stack restore is in a return/unwind block and if there are no
7336 // allocas or calls between the restore and the return, nuke the restore.
7337 TerminatorInst *TI = II->getParent()->getTerminator();
7338 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7339 BasicBlock::iterator BI = II;
7340 bool CannotRemove = false;
7341 for (++BI; &*BI != TI; ++BI) {
7342 if (isa<AllocaInst>(BI) ||
7343 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7344 CannotRemove = true;
7345 break;
7346 }
7347 }
7348 if (!CannotRemove)
7349 return EraseInstFromFunction(CI);
7350 }
7351 break;
7352 }
7353 }
Chris Lattner00648e12004-10-12 04:52:52 +00007354 }
7355
Chris Lattnerc66b2232006-01-13 20:11:04 +00007356 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007357}
7358
7359// InvokeInst simplification
7360//
7361Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007362 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007363}
7364
Chris Lattneraec3d942003-10-07 22:32:43 +00007365// visitCallSite - Improvements for call and invoke instructions.
7366//
7367Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007368 bool Changed = false;
7369
7370 // If the callee is a constexpr cast of a function, attempt to move the cast
7371 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007372 if (transformConstExprCastCall(CS)) return 0;
7373
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007374 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007375
Chris Lattner61d9d812005-05-13 07:09:09 +00007376 if (Function *CalleeF = dyn_cast<Function>(Callee))
7377 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7378 Instruction *OldCall = CS.getInstruction();
7379 // If the call and callee calling conventions don't match, this call must
7380 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007381 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007382 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007383 if (!OldCall->use_empty())
7384 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7385 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7386 return EraseInstFromFunction(*OldCall);
7387 return 0;
7388 }
7389
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007390 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7391 // This instruction is not reachable, just remove it. We insert a store to
7392 // undef so that we know that this code is not reachable, despite the fact
7393 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007394 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007395 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007396 CS.getInstruction());
7397
7398 if (!CS.getInstruction()->use_empty())
7399 CS.getInstruction()->
7400 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7401
7402 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7403 // Don't break the CFG, insert a dummy cond branch.
7404 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007405 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007406 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007407 return EraseInstFromFunction(*CS.getInstruction());
7408 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007409
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007410 const PointerType *PTy = cast<PointerType>(Callee->getType());
7411 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7412 if (FTy->isVarArg()) {
7413 // See if we can optimize any arguments passed through the varargs area of
7414 // the call.
7415 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7416 E = CS.arg_end(); I != E; ++I)
7417 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7418 // If this cast does not effect the value passed through the varargs
7419 // area, we can eliminate the use of the cast.
7420 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007421 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007422 *I = Op;
7423 Changed = true;
7424 }
7425 }
7426 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007427
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007428 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007429}
7430
Chris Lattner970c33a2003-06-19 17:00:31 +00007431// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7432// attempt to move the cast to the arguments of the call/invoke.
7433//
7434bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7435 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7436 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007437 if (CE->getOpcode() != Instruction::BitCast ||
7438 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007439 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007440 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007441 Instruction *Caller = CS.getInstruction();
7442
7443 // Okay, this is a cast from a function to a different type. Unless doing so
7444 // would cause a type conversion of one of our arguments, change this call to
7445 // be a direct call with arguments casted to the appropriate types.
7446 //
7447 const FunctionType *FT = Callee->getFunctionType();
7448 const Type *OldRetTy = Caller->getType();
7449
Chris Lattner1f7942f2004-01-14 06:06:08 +00007450 // Check to see if we are changing the return type...
7451 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007452 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007453 // Conversion is ok if changing from pointer to int of same size.
7454 !(isa<PointerType>(FT->getReturnType()) &&
7455 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007456 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007457
7458 // If the callsite is an invoke instruction, and the return value is used by
7459 // a PHI node in a successor, we cannot change the return type of the call
7460 // because there is no place to put the cast instruction (without breaking
7461 // the critical edge). Bail out in this case.
7462 if (!Caller->use_empty())
7463 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7464 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7465 UI != E; ++UI)
7466 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7467 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007468 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007469 return false;
7470 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007471
7472 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7473 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007474
Chris Lattner970c33a2003-06-19 17:00:31 +00007475 CallSite::arg_iterator AI = CS.arg_begin();
7476 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7477 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007478 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007479 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007480 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007481 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007482 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007483 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007484 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7485 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007486 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007487 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007488 }
7489
7490 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007491 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007492 return false; // Do not delete arguments unless we have a function body...
7493
7494 // Okay, we decided that this is a safe thing to do: go ahead and start
7495 // inserting cast instructions as necessary...
7496 std::vector<Value*> Args;
7497 Args.reserve(NumActualArgs);
7498
7499 AI = CS.arg_begin();
7500 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7501 const Type *ParamTy = FT->getParamType(i);
7502 if ((*AI)->getType() == ParamTy) {
7503 Args.push_back(*AI);
7504 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007505 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007506 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007507 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007508 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007509 }
7510 }
7511
7512 // If the function takes more arguments than the call was taking, add them
7513 // now...
7514 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7515 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7516
7517 // If we are removing arguments to the function, emit an obnoxious warning...
7518 if (FT->getNumParams() < NumActualArgs)
7519 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007520 cerr << "WARNING: While resolving call to function '"
7521 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007522 } else {
7523 // Add all of the arguments in their promoted form to the arg list...
7524 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7525 const Type *PTy = getPromotedType((*AI)->getType());
7526 if (PTy != (*AI)->getType()) {
7527 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007528 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7529 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007530 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007531 InsertNewInstBefore(Cast, *Caller);
7532 Args.push_back(Cast);
7533 } else {
7534 Args.push_back(*AI);
7535 }
7536 }
7537 }
7538
7539 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007540 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007541
7542 Instruction *NC;
7543 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007544 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007545 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007546 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007547 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007548 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007549 if (cast<CallInst>(Caller)->isTailCall())
7550 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007551 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007552 }
7553
Chris Lattner6e0123b2007-02-11 01:23:03 +00007554 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007555 Value *NV = NC;
7556 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7557 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007558 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007559 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7560 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007561 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007562
7563 // If this is an invoke instruction, we should insert it after the first
7564 // non-phi, instruction in the normal successor block.
7565 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7566 BasicBlock::iterator I = II->getNormalDest()->begin();
7567 while (isa<PHINode>(I)) ++I;
7568 InsertNewInstBefore(NC, *I);
7569 } else {
7570 // Otherwise, it's a call, just insert cast right after the call instr
7571 InsertNewInstBefore(NC, *Caller);
7572 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007573 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007574 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007575 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007576 }
7577 }
7578
7579 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7580 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007581 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007582 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007583 return true;
7584}
7585
Chris Lattnercadac0c2006-11-01 04:51:18 +00007586/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7587/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7588/// and a single binop.
7589Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7590 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007591 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7592 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007593 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007594 Value *LHSVal = FirstInst->getOperand(0);
7595 Value *RHSVal = FirstInst->getOperand(1);
7596
7597 const Type *LHSType = LHSVal->getType();
7598 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007599
7600 // Scan to see if all operands are the same opcode, all have one use, and all
7601 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007602 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007603 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007604 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007605 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007606 // types or GEP's with different index types.
7607 I->getOperand(0)->getType() != LHSType ||
7608 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007609 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007610
7611 // If they are CmpInst instructions, check their predicates
7612 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7613 if (cast<CmpInst>(I)->getPredicate() !=
7614 cast<CmpInst>(FirstInst)->getPredicate())
7615 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007616
7617 // Keep track of which operand needs a phi node.
7618 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7619 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007620 }
7621
Chris Lattner4f218d52006-11-08 19:42:28 +00007622 // Otherwise, this is safe to transform, determine if it is profitable.
7623
7624 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7625 // Indexes are often folded into load/store instructions, so we don't want to
7626 // hide them behind a phi.
7627 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7628 return 0;
7629
Chris Lattnercadac0c2006-11-01 04:51:18 +00007630 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007631 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007632 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007633 if (LHSVal == 0) {
7634 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7635 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7636 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007637 InsertNewInstBefore(NewLHS, PN);
7638 LHSVal = NewLHS;
7639 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007640
7641 if (RHSVal == 0) {
7642 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7643 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7644 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007645 InsertNewInstBefore(NewRHS, PN);
7646 RHSVal = NewRHS;
7647 }
7648
Chris Lattnercd62f112006-11-08 19:29:23 +00007649 // Add all operands to the new PHIs.
7650 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7651 if (NewLHS) {
7652 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7653 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7654 }
7655 if (NewRHS) {
7656 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7657 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7658 }
7659 }
7660
Chris Lattnercadac0c2006-11-01 04:51:18 +00007661 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007662 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007663 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7664 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7665 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007666 else {
7667 assert(isa<GetElementPtrInst>(FirstInst));
7668 return new GetElementPtrInst(LHSVal, RHSVal);
7669 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007670}
7671
Chris Lattner14f82c72006-11-01 07:13:54 +00007672/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7673/// of the block that defines it. This means that it must be obvious the value
7674/// of the load is not changed from the point of the load to the end of the
7675/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007676///
7677/// Finally, it is safe, but not profitable, to sink a load targetting a
7678/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7679/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007680static bool isSafeToSinkLoad(LoadInst *L) {
7681 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7682
7683 for (++BBI; BBI != E; ++BBI)
7684 if (BBI->mayWriteToMemory())
7685 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007686
7687 // Check for non-address taken alloca. If not address-taken already, it isn't
7688 // profitable to do this xform.
7689 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7690 bool isAddressTaken = false;
7691 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7692 UI != E; ++UI) {
7693 if (isa<LoadInst>(UI)) continue;
7694 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7695 // If storing TO the alloca, then the address isn't taken.
7696 if (SI->getOperand(1) == AI) continue;
7697 }
7698 isAddressTaken = true;
7699 break;
7700 }
7701
7702 if (!isAddressTaken)
7703 return false;
7704 }
7705
Chris Lattner14f82c72006-11-01 07:13:54 +00007706 return true;
7707}
7708
Chris Lattner970c33a2003-06-19 17:00:31 +00007709
Chris Lattner7515cab2004-11-14 19:13:23 +00007710// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7711// operator and they all are only used by the PHI, PHI together their
7712// inputs, and do the operation once, to the result of the PHI.
7713Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7714 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7715
7716 // Scan the instruction, looking for input operations that can be folded away.
7717 // If all input operands to the phi are the same instruction (e.g. a cast from
7718 // the same type or "+42") we can pull the operation through the PHI, reducing
7719 // code size and simplifying code.
7720 Constant *ConstantOp = 0;
7721 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007722 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007723 if (isa<CastInst>(FirstInst)) {
7724 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007725 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007726 // Can fold binop, compare or shift here if the RHS is a constant,
7727 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007728 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007729 if (ConstantOp == 0)
7730 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007731 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7732 isVolatile = LI->isVolatile();
7733 // We can't sink the load if the loaded value could be modified between the
7734 // load and the PHI.
7735 if (LI->getParent() != PN.getIncomingBlock(0) ||
7736 !isSafeToSinkLoad(LI))
7737 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007738 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007739 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007740 return FoldPHIArgBinOpIntoPHI(PN);
7741 // Can't handle general GEPs yet.
7742 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007743 } else {
7744 return 0; // Cannot fold this operation.
7745 }
7746
7747 // Check to see if all arguments are the same operation.
7748 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7749 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7750 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007751 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007752 return 0;
7753 if (CastSrcTy) {
7754 if (I->getOperand(0)->getType() != CastSrcTy)
7755 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007756 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007757 // We can't sink the load if the loaded value could be modified between
7758 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007759 if (LI->isVolatile() != isVolatile ||
7760 LI->getParent() != PN.getIncomingBlock(i) ||
7761 !isSafeToSinkLoad(LI))
7762 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007763 } else if (I->getOperand(1) != ConstantOp) {
7764 return 0;
7765 }
7766 }
7767
7768 // Okay, they are all the same operation. Create a new PHI node of the
7769 // correct type, and PHI together all of the LHS's of the instructions.
7770 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7771 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007772 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007773
7774 Value *InVal = FirstInst->getOperand(0);
7775 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007776
7777 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007778 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7779 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7780 if (NewInVal != InVal)
7781 InVal = 0;
7782 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7783 }
7784
7785 Value *PhiVal;
7786 if (InVal) {
7787 // The new PHI unions all of the same values together. This is really
7788 // common, so we handle it intelligently here for compile-time speed.
7789 PhiVal = InVal;
7790 delete NewPN;
7791 } else {
7792 InsertNewInstBefore(NewPN, PN);
7793 PhiVal = NewPN;
7794 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007795
Chris Lattner7515cab2004-11-14 19:13:23 +00007796 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007797 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7798 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007799 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007800 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007801 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007802 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007803 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7804 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7805 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007806 else
Reid Spencer2341c222007-02-02 02:16:23 +00007807 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007808 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007809}
Chris Lattner48a44f72002-05-02 17:06:02 +00007810
Chris Lattner71536432005-01-17 05:10:15 +00007811/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7812/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007813static bool DeadPHICycle(PHINode *PN,
7814 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00007815 if (PN->use_empty()) return true;
7816 if (!PN->hasOneUse()) return false;
7817
7818 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007819 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00007820 return true;
7821
7822 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7823 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007824
Chris Lattner71536432005-01-17 05:10:15 +00007825 return false;
7826}
7827
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007828// PHINode simplification
7829//
Chris Lattner113f4f42002-06-25 16:13:24 +00007830Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007831 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007832 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007833
Owen Andersonae8aa642006-07-10 22:03:18 +00007834 if (Value *V = PN.hasConstantValue())
7835 return ReplaceInstUsesWith(PN, V);
7836
Owen Andersonae8aa642006-07-10 22:03:18 +00007837 // If all PHI operands are the same operation, pull them through the PHI,
7838 // reducing code size.
7839 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7840 PN.getIncomingValue(0)->hasOneUse())
7841 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7842 return Result;
7843
7844 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7845 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7846 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007847 if (PN.hasOneUse()) {
7848 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7849 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00007850 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00007851 PotentiallyDeadPHIs.insert(&PN);
7852 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7853 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7854 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007855
7856 // If this phi has a single use, and if that use just computes a value for
7857 // the next iteration of a loop, delete the phi. This occurs with unused
7858 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7859 // common case here is good because the only other things that catch this
7860 // are induction variable analysis (sometimes) and ADCE, which is only run
7861 // late.
7862 if (PHIUser->hasOneUse() &&
7863 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7864 PHIUser->use_back() == &PN) {
7865 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7866 }
7867 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007868
Chris Lattner91daeb52003-12-19 05:58:40 +00007869 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007870}
7871
Reid Spencer13bc5d72006-12-12 09:18:51 +00007872static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7873 Instruction *InsertPoint,
7874 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007875 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7876 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007877 // We must cast correctly to the pointer type. Ensure that we
7878 // sign extend the integer value if it is smaller as this is
7879 // used for address computation.
7880 Instruction::CastOps opcode =
7881 (VTySize < PtrSize ? Instruction::SExt :
7882 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7883 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007884}
7885
Chris Lattner48a44f72002-05-02 17:06:02 +00007886
Chris Lattner113f4f42002-06-25 16:13:24 +00007887Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007888 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007889 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007890 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007891 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007892 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007893
Chris Lattner81a7a232004-10-16 18:11:37 +00007894 if (isa<UndefValue>(GEP.getOperand(0)))
7895 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7896
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007897 bool HasZeroPointerIndex = false;
7898 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7899 HasZeroPointerIndex = C->isNullValue();
7900
7901 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007902 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007903
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007904 // Keep track of whether all indices are zero constants integers.
7905 bool AllZeroIndices = true;
7906
Chris Lattner69193f92004-04-05 01:30:19 +00007907 // Eliminate unneeded casts for indices.
7908 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007909
Chris Lattner2b2412d2004-04-07 18:38:20 +00007910 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007911 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
7912 // Track whether this GEP has all zero indices, if so, it doesn't move the
7913 // input pointer, it just changes its type.
7914 if (AllZeroIndices) {
7915 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
7916 AllZeroIndices = CI->isNullValue();
7917 else
7918 AllZeroIndices = false;
7919 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007920 if (isa<SequentialType>(*GTI)) {
7921 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007922 if (CI->getOpcode() == Instruction::ZExt ||
7923 CI->getOpcode() == Instruction::SExt) {
7924 const Type *SrcTy = CI->getOperand(0)->getType();
7925 // We can eliminate a cast from i32 to i64 iff the target
7926 // is a 32-bit pointer target.
7927 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7928 MadeChange = true;
7929 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007930 }
7931 }
7932 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007933 // If we are using a wider index than needed for this platform, shrink it
7934 // to what we need. If the incoming value needs a cast instruction,
7935 // insert it. This explicit cast can make subsequent optimizations more
7936 // obvious.
7937 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007938 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007939 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007940 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007941 MadeChange = true;
7942 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007943 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7944 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007945 GEP.setOperand(i, Op);
7946 MadeChange = true;
7947 }
Chris Lattner69193f92004-04-05 01:30:19 +00007948 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007949 }
Chris Lattner69193f92004-04-05 01:30:19 +00007950 if (MadeChange) return &GEP;
7951
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007952 // If this GEP instruction doesn't move the pointer, and if the input operand
7953 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
7954 // real input to the dest type.
7955 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
7956 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
7957 GEP.getType());
7958
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007959 // Combine Indices - If the source pointer to this getelementptr instruction
7960 // is a getelementptr instruction, combine the indices of the two
7961 // getelementptr instructions into a single instruction.
7962 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007963 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007964 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007965 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007966
7967 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007968 // Note that if our source is a gep chain itself that we wait for that
7969 // chain to be resolved before we perform this transformation. This
7970 // avoids us creating a TON of code in some cases.
7971 //
7972 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7973 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7974 return 0; // Wait until our source is folded to completion.
7975
Chris Lattneraf6094f2007-02-15 22:48:32 +00007976 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007977
7978 // Find out whether the last index in the source GEP is a sequential idx.
7979 bool EndsWithSequential = false;
7980 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7981 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007982 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007983
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007984 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007985 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007986 // Replace: gep (gep %P, long B), long A, ...
7987 // With: T = long A+B; gep %P, T, ...
7988 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007989 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007990 if (SO1 == Constant::getNullValue(SO1->getType())) {
7991 Sum = GO1;
7992 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7993 Sum = SO1;
7994 } else {
7995 // If they aren't the same type, convert both to an integer of the
7996 // target's pointer size.
7997 if (SO1->getType() != GO1->getType()) {
7998 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007999 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008000 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008001 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008002 } else {
8003 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008004 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008005 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008006 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008007
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008008 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008009 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008010 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008011 } else {
8012 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008013 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8014 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008015 }
8016 }
8017 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008018 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8019 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8020 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008021 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8022 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008023 }
Chris Lattner69193f92004-04-05 01:30:19 +00008024 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008025
8026 // Recycle the GEP we already have if possible.
8027 if (SrcGEPOperands.size() == 2) {
8028 GEP.setOperand(0, SrcGEPOperands[0]);
8029 GEP.setOperand(1, Sum);
8030 return &GEP;
8031 } else {
8032 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8033 SrcGEPOperands.end()-1);
8034 Indices.push_back(Sum);
8035 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8036 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008037 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008038 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008039 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008040 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008041 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8042 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008043 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8044 }
8045
8046 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008047 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8048 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008049
Chris Lattner5f667a62004-05-07 22:09:22 +00008050 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008051 // GEP of global variable. If all of the indices for this GEP are
8052 // constants, we can promote this to a constexpr instead of an instruction.
8053
8054 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008055 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008056 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8057 for (; I != E && isa<Constant>(*I); ++I)
8058 Indices.push_back(cast<Constant>(*I));
8059
8060 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008061 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8062 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008063
8064 // Replace all uses of the GEP with the new constexpr...
8065 return ReplaceInstUsesWith(GEP, CE);
8066 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008067 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008068 if (!isa<PointerType>(X->getType())) {
8069 // Not interesting. Source pointer must be a cast from pointer.
8070 } else if (HasZeroPointerIndex) {
8071 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8072 // into : GEP [10 x ubyte]* X, long 0, ...
8073 //
8074 // This occurs when the program declares an array extern like "int X[];"
8075 //
8076 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8077 const PointerType *XTy = cast<PointerType>(X->getType());
8078 if (const ArrayType *XATy =
8079 dyn_cast<ArrayType>(XTy->getElementType()))
8080 if (const ArrayType *CATy =
8081 dyn_cast<ArrayType>(CPTy->getElementType()))
8082 if (CATy->getElementType() == XATy->getElementType()) {
8083 // At this point, we know that the cast source type is a pointer
8084 // to an array of the same type as the destination pointer
8085 // array. Because the array type is never stepped over (there
8086 // is a leading zero) we can fold the cast into this GEP.
8087 GEP.setOperand(0, X);
8088 return &GEP;
8089 }
8090 } else if (GEP.getNumOperands() == 2) {
8091 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008092 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8093 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008094 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8095 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8096 if (isa<ArrayType>(SrcElTy) &&
8097 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8098 TD->getTypeSize(ResElTy)) {
8099 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008100 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008101 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008102 // V and GEP are both pointer types --> BitCast
8103 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008104 }
Chris Lattner2a893292005-09-13 18:36:04 +00008105
8106 // Transform things like:
8107 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8108 // (where tmp = 8*tmp2) into:
8109 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8110
8111 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008112 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008113 uint64_t ArrayEltSize =
8114 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8115
8116 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8117 // allow either a mul, shift, or constant here.
8118 Value *NewIdx = 0;
8119 ConstantInt *Scale = 0;
8120 if (ArrayEltSize == 1) {
8121 NewIdx = GEP.getOperand(1);
8122 Scale = ConstantInt::get(NewIdx->getType(), 1);
8123 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008124 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008125 Scale = CI;
8126 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8127 if (Inst->getOpcode() == Instruction::Shl &&
8128 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008129 unsigned ShAmt =
8130 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008131 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008132 NewIdx = Inst->getOperand(0);
8133 } else if (Inst->getOpcode() == Instruction::Mul &&
8134 isa<ConstantInt>(Inst->getOperand(1))) {
8135 Scale = cast<ConstantInt>(Inst->getOperand(1));
8136 NewIdx = Inst->getOperand(0);
8137 }
8138 }
8139
8140 // If the index will be to exactly the right offset with the scale taken
8141 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008142 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008143 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008144 Scale = ConstantInt::get(Scale->getType(),
8145 Scale->getZExtValue() / ArrayEltSize);
8146 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008147 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8148 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008149 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8150 NewIdx = InsertNewInstBefore(Sc, GEP);
8151 }
8152
8153 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008154 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008155 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008156 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008157 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8158 // The NewGEP must be pointer typed, so must the old one -> BitCast
8159 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008160 }
8161 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008162 }
Chris Lattnerca081252001-12-14 16:52:21 +00008163 }
8164
Chris Lattnerca081252001-12-14 16:52:21 +00008165 return 0;
8166}
8167
Chris Lattner1085bdf2002-11-04 16:18:53 +00008168Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8169 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8170 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008171 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8172 const Type *NewTy =
8173 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008174 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008175
8176 // Create and insert the replacement instruction...
8177 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008178 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008179 else {
8180 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008181 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008182 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008183
8184 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008185
Chris Lattner1085bdf2002-11-04 16:18:53 +00008186 // Scan to the end of the allocation instructions, to skip over a block of
8187 // allocas if possible...
8188 //
8189 BasicBlock::iterator It = New;
8190 while (isa<AllocationInst>(*It)) ++It;
8191
8192 // Now that I is pointing to the first non-allocation-inst in the block,
8193 // insert our getelementptr instruction...
8194 //
Reid Spencerc635f472006-12-31 05:48:39 +00008195 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008196 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8197 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008198
8199 // Now make everything use the getelementptr instead of the original
8200 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008201 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008202 } else if (isa<UndefValue>(AI.getArraySize())) {
8203 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008204 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008205
8206 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8207 // Note that we only do this for alloca's, because malloc should allocate and
8208 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008209 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008210 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008211 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8212
Chris Lattner1085bdf2002-11-04 16:18:53 +00008213 return 0;
8214}
8215
Chris Lattner8427bff2003-12-07 01:24:23 +00008216Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8217 Value *Op = FI.getOperand(0);
8218
8219 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8220 if (CastInst *CI = dyn_cast<CastInst>(Op))
8221 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8222 FI.setOperand(0, CI->getOperand(0));
8223 return &FI;
8224 }
8225
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008226 // free undef -> unreachable.
8227 if (isa<UndefValue>(Op)) {
8228 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008229 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008230 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008231 return EraseInstFromFunction(FI);
8232 }
8233
Chris Lattnerf3a36602004-02-28 04:57:37 +00008234 // If we have 'free null' delete the instruction. This can happen in stl code
8235 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008236 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008237 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008238
Chris Lattner8427bff2003-12-07 01:24:23 +00008239 return 0;
8240}
8241
8242
Chris Lattner72684fe2005-01-31 05:51:45 +00008243/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008244static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8245 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008246 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008247
8248 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008249 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008250 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008251
Reid Spencer31a4ef42007-01-22 05:51:25 +00008252 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008253 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008254 // If the source is an array, the code below will not succeed. Check to
8255 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8256 // constants.
8257 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8258 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8259 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008260 Value *Idxs[2];
8261 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8262 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008263 SrcTy = cast<PointerType>(CastOp->getType());
8264 SrcPTy = SrcTy->getElementType();
8265 }
8266
Reid Spencer31a4ef42007-01-22 05:51:25 +00008267 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008268 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008269 // Do not allow turning this into a load of an integer, which is then
8270 // casted to a pointer, this pessimizes pointer analysis a lot.
8271 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008272 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8273 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008274
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008275 // Okay, we are casting from one integer or pointer type to another of
8276 // the same size. Instead of casting the pointer before the load, cast
8277 // the result of the loaded value.
8278 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8279 CI->getName(),
8280 LI.isVolatile()),LI);
8281 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008282 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008283 }
Chris Lattner35e24772004-07-13 01:49:43 +00008284 }
8285 }
8286 return 0;
8287}
8288
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008289/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008290/// from this value cannot trap. If it is not obviously safe to load from the
8291/// specified pointer, we do a quick local scan of the basic block containing
8292/// ScanFrom, to determine if the address is already accessed.
8293static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8294 // If it is an alloca or global variable, it is always safe to load from.
8295 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8296
8297 // Otherwise, be a little bit agressive by scanning the local block where we
8298 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008299 // from/to. If so, the previous load or store would have already trapped,
8300 // so there is no harm doing an extra load (also, CSE will later eliminate
8301 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008302 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8303
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008304 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008305 --BBI;
8306
8307 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8308 if (LI->getOperand(0) == V) return true;
8309 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8310 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008311
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008312 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008313 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008314}
8315
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008316Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8317 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008318
Chris Lattnera9d84e32005-05-01 04:24:53 +00008319 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008320 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008321 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8322 return Res;
8323
8324 // None of the following transforms are legal for volatile loads.
8325 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008326
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008327 if (&LI.getParent()->front() != &LI) {
8328 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008329 // If the instruction immediately before this is a store to the same
8330 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008331 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8332 if (SI->getOperand(1) == LI.getOperand(0))
8333 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008334 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8335 if (LIB->getOperand(0) == LI.getOperand(0))
8336 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008337 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008338
8339 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8340 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8341 isa<UndefValue>(GEPI->getOperand(0))) {
8342 // Insert a new store to null instruction before the load to indicate
8343 // that this code is not reachable. We do this instead of inserting
8344 // an unreachable instruction directly because we cannot modify the
8345 // CFG.
8346 new StoreInst(UndefValue::get(LI.getType()),
8347 Constant::getNullValue(Op->getType()), &LI);
8348 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8349 }
8350
Chris Lattner81a7a232004-10-16 18:11:37 +00008351 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008352 // load null/undef -> undef
8353 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008354 // Insert a new store to null instruction before the load to indicate that
8355 // this code is not reachable. We do this instead of inserting an
8356 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008357 new StoreInst(UndefValue::get(LI.getType()),
8358 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008359 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008360 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008361
Chris Lattner81a7a232004-10-16 18:11:37 +00008362 // Instcombine load (constant global) into the value loaded.
8363 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008364 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008365 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008366
Chris Lattner81a7a232004-10-16 18:11:37 +00008367 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8369 if (CE->getOpcode() == Instruction::GetElementPtr) {
8370 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008371 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008372 if (Constant *V =
8373 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008374 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008375 if (CE->getOperand(0)->isNullValue()) {
8376 // Insert a new store to null instruction before the load to indicate
8377 // that this code is not reachable. We do this instead of inserting
8378 // an unreachable instruction directly because we cannot modify the
8379 // CFG.
8380 new StoreInst(UndefValue::get(LI.getType()),
8381 Constant::getNullValue(Op->getType()), &LI);
8382 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8383 }
8384
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008385 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008386 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8387 return Res;
8388 }
8389 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008390
Chris Lattnera9d84e32005-05-01 04:24:53 +00008391 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008392 // Change select and PHI nodes to select values instead of addresses: this
8393 // helps alias analysis out a lot, allows many others simplifications, and
8394 // exposes redundancy in the code.
8395 //
8396 // Note that we cannot do the transformation unless we know that the
8397 // introduced loads cannot trap! Something like this is valid as long as
8398 // the condition is always false: load (select bool %C, int* null, int* %G),
8399 // but it would not be valid if we transformed it to load from null
8400 // unconditionally.
8401 //
8402 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8403 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008404 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8405 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008406 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008407 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008408 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008409 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008410 return new SelectInst(SI->getCondition(), V1, V2);
8411 }
8412
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008413 // load (select (cond, null, P)) -> load P
8414 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8415 if (C->isNullValue()) {
8416 LI.setOperand(0, SI->getOperand(2));
8417 return &LI;
8418 }
8419
8420 // load (select (cond, P, null)) -> load P
8421 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8422 if (C->isNullValue()) {
8423 LI.setOperand(0, SI->getOperand(1));
8424 return &LI;
8425 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008426 }
8427 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008428 return 0;
8429}
8430
Reid Spencere928a152007-01-19 21:20:31 +00008431/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008432/// when possible.
8433static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8434 User *CI = cast<User>(SI.getOperand(1));
8435 Value *CastOp = CI->getOperand(0);
8436
8437 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8438 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8439 const Type *SrcPTy = SrcTy->getElementType();
8440
Reid Spencer31a4ef42007-01-22 05:51:25 +00008441 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008442 // If the source is an array, the code below will not succeed. Check to
8443 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8444 // constants.
8445 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8446 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8447 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008448 Value* Idxs[2];
8449 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8450 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008451 SrcTy = cast<PointerType>(CastOp->getType());
8452 SrcPTy = SrcTy->getElementType();
8453 }
8454
Reid Spencer9a4bed02007-01-20 23:35:48 +00008455 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8456 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8457 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008458
8459 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008460 // the same size. Instead of casting the pointer before
8461 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008462 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008463 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008464 Instruction::CastOps opcode = Instruction::BitCast;
8465 const Type* CastSrcTy = SIOp0->getType();
8466 const Type* CastDstTy = SrcPTy;
8467 if (isa<PointerType>(CastDstTy)) {
8468 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008469 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008470 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008471 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008472 opcode = Instruction::PtrToInt;
8473 }
8474 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008475 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008476 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008477 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008478 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8479 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008480 return new StoreInst(NewCast, CastOp);
8481 }
8482 }
8483 }
8484 return 0;
8485}
8486
Chris Lattner31f486c2005-01-31 05:36:43 +00008487Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8488 Value *Val = SI.getOperand(0);
8489 Value *Ptr = SI.getOperand(1);
8490
8491 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008492 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008493 ++NumCombined;
8494 return 0;
8495 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008496
8497 // If the RHS is an alloca with a single use, zapify the store, making the
8498 // alloca dead.
8499 if (Ptr->hasOneUse()) {
8500 if (isa<AllocaInst>(Ptr)) {
8501 EraseInstFromFunction(SI);
8502 ++NumCombined;
8503 return 0;
8504 }
8505
8506 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8507 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8508 GEP->getOperand(0)->hasOneUse()) {
8509 EraseInstFromFunction(SI);
8510 ++NumCombined;
8511 return 0;
8512 }
8513 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008514
Chris Lattner5997cf92006-02-08 03:25:32 +00008515 // Do really simple DSE, to catch cases where there are several consequtive
8516 // stores to the same location, separated by a few arithmetic operations. This
8517 // situation often occurs with bitfield accesses.
8518 BasicBlock::iterator BBI = &SI;
8519 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8520 --ScanInsts) {
8521 --BBI;
8522
8523 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8524 // Prev store isn't volatile, and stores to the same location?
8525 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8526 ++NumDeadStore;
8527 ++BBI;
8528 EraseInstFromFunction(*PrevSI);
8529 continue;
8530 }
8531 break;
8532 }
8533
Chris Lattnerdab43b22006-05-26 19:19:20 +00008534 // If this is a load, we have to stop. However, if the loaded value is from
8535 // the pointer we're loading and is producing the pointer we're storing,
8536 // then *this* store is dead (X = load P; store X -> P).
8537 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8538 if (LI == Val && LI->getOperand(0) == Ptr) {
8539 EraseInstFromFunction(SI);
8540 ++NumCombined;
8541 return 0;
8542 }
8543 // Otherwise, this is a load from some other location. Stores before it
8544 // may not be dead.
8545 break;
8546 }
8547
Chris Lattner5997cf92006-02-08 03:25:32 +00008548 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008549 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008550 break;
8551 }
8552
8553
8554 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008555
8556 // store X, null -> turns into 'unreachable' in SimplifyCFG
8557 if (isa<ConstantPointerNull>(Ptr)) {
8558 if (!isa<UndefValue>(Val)) {
8559 SI.setOperand(0, UndefValue::get(Val->getType()));
8560 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008561 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008562 ++NumCombined;
8563 }
8564 return 0; // Do not modify these!
8565 }
8566
8567 // store undef, Ptr -> noop
8568 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008569 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008570 ++NumCombined;
8571 return 0;
8572 }
8573
Chris Lattner72684fe2005-01-31 05:51:45 +00008574 // If the pointer destination is a cast, see if we can fold the cast into the
8575 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008576 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008577 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8578 return Res;
8579 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008580 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008581 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8582 return Res;
8583
Chris Lattner219175c2005-09-12 23:23:25 +00008584
8585 // If this store is the last instruction in the basic block, and if the block
8586 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008587 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008588 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8589 if (BI->isUnconditional()) {
8590 // Check to see if the successor block has exactly two incoming edges. If
8591 // so, see if the other predecessor contains a store to the same location.
8592 // if so, insert a PHI node (if needed) and move the stores down.
8593 BasicBlock *Dest = BI->getSuccessor(0);
8594
8595 pred_iterator PI = pred_begin(Dest);
8596 BasicBlock *Other = 0;
8597 if (*PI != BI->getParent())
8598 Other = *PI;
8599 ++PI;
8600 if (PI != pred_end(Dest)) {
8601 if (*PI != BI->getParent())
8602 if (Other)
8603 Other = 0;
8604 else
8605 Other = *PI;
8606 if (++PI != pred_end(Dest))
8607 Other = 0;
8608 }
8609 if (Other) { // If only one other pred...
8610 BBI = Other->getTerminator();
8611 // Make sure this other block ends in an unconditional branch and that
8612 // there is an instruction before the branch.
8613 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8614 BBI != Other->begin()) {
8615 --BBI;
8616 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8617
8618 // If this instruction is a store to the same location.
8619 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8620 // Okay, we know we can perform this transformation. Insert a PHI
8621 // node now if we need it.
8622 Value *MergedVal = OtherStore->getOperand(0);
8623 if (MergedVal != SI.getOperand(0)) {
8624 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8625 PN->reserveOperandSpace(2);
8626 PN->addIncoming(SI.getOperand(0), SI.getParent());
8627 PN->addIncoming(OtherStore->getOperand(0), Other);
8628 MergedVal = InsertNewInstBefore(PN, Dest->front());
8629 }
8630
8631 // Advance to a place where it is safe to insert the new store and
8632 // insert it.
8633 BBI = Dest->begin();
8634 while (isa<PHINode>(BBI)) ++BBI;
8635 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8636 OtherStore->isVolatile()), *BBI);
8637
8638 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008639 EraseInstFromFunction(SI);
8640 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008641 ++NumCombined;
8642 return 0;
8643 }
8644 }
8645 }
8646 }
8647
Chris Lattner31f486c2005-01-31 05:36:43 +00008648 return 0;
8649}
8650
8651
Chris Lattner9eef8a72003-06-04 04:46:00 +00008652Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8653 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008654 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008655 BasicBlock *TrueDest;
8656 BasicBlock *FalseDest;
8657 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8658 !isa<Constant>(X)) {
8659 // Swap Destinations and condition...
8660 BI.setCondition(X);
8661 BI.setSuccessor(0, FalseDest);
8662 BI.setSuccessor(1, TrueDest);
8663 return &BI;
8664 }
8665
Reid Spencer266e42b2006-12-23 06:05:41 +00008666 // Cannonicalize fcmp_one -> fcmp_oeq
8667 FCmpInst::Predicate FPred; Value *Y;
8668 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8669 TrueDest, FalseDest)))
8670 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8671 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8672 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008673 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008674 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8675 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008676 // Swap Destinations and condition...
8677 BI.setCondition(NewSCC);
8678 BI.setSuccessor(0, FalseDest);
8679 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008680 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008681 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008682 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008683 return &BI;
8684 }
8685
8686 // Cannonicalize icmp_ne -> icmp_eq
8687 ICmpInst::Predicate IPred;
8688 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8689 TrueDest, FalseDest)))
8690 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8691 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8692 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8693 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008694 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008695 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8696 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008697 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008698 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008699 BI.setSuccessor(0, FalseDest);
8700 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008701 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008702 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008703 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008704 return &BI;
8705 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008706
Chris Lattner9eef8a72003-06-04 04:46:00 +00008707 return 0;
8708}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008709
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008710Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8711 Value *Cond = SI.getCondition();
8712 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8713 if (I->getOpcode() == Instruction::Add)
8714 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8715 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8716 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008717 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008718 AddRHS));
8719 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008720 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008721 return &SI;
8722 }
8723 }
8724 return 0;
8725}
8726
Chris Lattner6bc98652006-03-05 00:22:33 +00008727/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8728/// is to leave as a vector operation.
8729static bool CheapToScalarize(Value *V, bool isConstant) {
8730 if (isa<ConstantAggregateZero>(V))
8731 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008732 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008733 if (isConstant) return true;
8734 // If all elts are the same, we can extract.
8735 Constant *Op0 = C->getOperand(0);
8736 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8737 if (C->getOperand(i) != Op0)
8738 return false;
8739 return true;
8740 }
8741 Instruction *I = dyn_cast<Instruction>(V);
8742 if (!I) return false;
8743
8744 // Insert element gets simplified to the inserted element or is deleted if
8745 // this is constant idx extract element and its a constant idx insertelt.
8746 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8747 isa<ConstantInt>(I->getOperand(2)))
8748 return true;
8749 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8750 return true;
8751 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8752 if (BO->hasOneUse() &&
8753 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8754 CheapToScalarize(BO->getOperand(1), isConstant)))
8755 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008756 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8757 if (CI->hasOneUse() &&
8758 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8759 CheapToScalarize(CI->getOperand(1), isConstant)))
8760 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008761
8762 return false;
8763}
8764
Chris Lattner945e4372007-02-14 05:52:17 +00008765/// Read and decode a shufflevector mask.
8766///
8767/// It turns undef elements into values that are larger than the number of
8768/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008769static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8770 unsigned NElts = SVI->getType()->getNumElements();
8771 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8772 return std::vector<unsigned>(NElts, 0);
8773 if (isa<UndefValue>(SVI->getOperand(2)))
8774 return std::vector<unsigned>(NElts, 2*NElts);
8775
8776 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008777 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008778 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8779 if (isa<UndefValue>(CP->getOperand(i)))
8780 Result.push_back(NElts*2); // undef -> 8
8781 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008782 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008783 return Result;
8784}
8785
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008786/// FindScalarElement - Given a vector and an element number, see if the scalar
8787/// value is already around as a register, for example if it were inserted then
8788/// extracted from the vector.
8789static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008790 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8791 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008792 unsigned Width = PTy->getNumElements();
8793 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008794 return UndefValue::get(PTy->getElementType());
8795
8796 if (isa<UndefValue>(V))
8797 return UndefValue::get(PTy->getElementType());
8798 else if (isa<ConstantAggregateZero>(V))
8799 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008800 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008801 return CP->getOperand(EltNo);
8802 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8803 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008804 if (!isa<ConstantInt>(III->getOperand(2)))
8805 return 0;
8806 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008807
8808 // If this is an insert to the element we are looking for, return the
8809 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008810 if (EltNo == IIElt)
8811 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008812
8813 // Otherwise, the insertelement doesn't modify the value, recurse on its
8814 // vector input.
8815 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008816 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008817 unsigned InEl = getShuffleMask(SVI)[EltNo];
8818 if (InEl < Width)
8819 return FindScalarElement(SVI->getOperand(0), InEl);
8820 else if (InEl < Width*2)
8821 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8822 else
8823 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008824 }
8825
8826 // Otherwise, we don't know.
8827 return 0;
8828}
8829
Robert Bocchinoa8352962006-01-13 22:48:06 +00008830Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008831
Chris Lattner92346c32006-03-31 18:25:14 +00008832 // If packed val is undef, replace extract with scalar undef.
8833 if (isa<UndefValue>(EI.getOperand(0)))
8834 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8835
8836 // If packed val is constant 0, replace extract with scalar 0.
8837 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8838 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8839
Reid Spencerd84d35b2007-02-15 02:26:10 +00008840 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008841 // If packed val is constant with uniform operands, replace EI
8842 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008843 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008844 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008845 if (C->getOperand(i) != op0) {
8846 op0 = 0;
8847 break;
8848 }
8849 if (op0)
8850 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008851 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008852
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008853 // If extracting a specified index from the vector, see if we can recursively
8854 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008855 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008856 // This instruction only demands the single element from the input vector.
8857 // If the input vector has a single use, simplify it based on this use
8858 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008859 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008860 if (EI.getOperand(0)->hasOneUse()) {
8861 uint64_t UndefElts;
8862 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008863 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008864 UndefElts)) {
8865 EI.setOperand(0, V);
8866 return &EI;
8867 }
8868 }
8869
Reid Spencere0fc4df2006-10-20 07:07:24 +00008870 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008871 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008872 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008873
Chris Lattner83f65782006-05-25 22:53:38 +00008874 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008875 if (I->hasOneUse()) {
8876 // Push extractelement into predecessor operation if legal and
8877 // profitable to do so
8878 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008879 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8880 if (CheapToScalarize(BO, isConstantElt)) {
8881 ExtractElementInst *newEI0 =
8882 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8883 EI.getName()+".lhs");
8884 ExtractElementInst *newEI1 =
8885 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8886 EI.getName()+".rhs");
8887 InsertNewInstBefore(newEI0, EI);
8888 InsertNewInstBefore(newEI1, EI);
8889 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8890 }
Reid Spencerde46e482006-11-02 20:25:50 +00008891 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008892 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008893 PointerType::get(EI.getType()), EI);
8894 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008895 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008896 InsertNewInstBefore(GEP, EI);
8897 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008898 }
8899 }
8900 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8901 // Extracting the inserted element?
8902 if (IE->getOperand(2) == EI.getOperand(1))
8903 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8904 // If the inserted and extracted elements are constants, they must not
8905 // be the same value, extract from the pre-inserted value instead.
8906 if (isa<Constant>(IE->getOperand(2)) &&
8907 isa<Constant>(EI.getOperand(1))) {
8908 AddUsesToWorkList(EI);
8909 EI.setOperand(0, IE->getOperand(0));
8910 return &EI;
8911 }
8912 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8913 // If this is extracting an element from a shufflevector, figure out where
8914 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008915 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8916 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008917 Value *Src;
8918 if (SrcIdx < SVI->getType()->getNumElements())
8919 Src = SVI->getOperand(0);
8920 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8921 SrcIdx -= SVI->getType()->getNumElements();
8922 Src = SVI->getOperand(1);
8923 } else {
8924 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008925 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008926 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008927 }
8928 }
Chris Lattner83f65782006-05-25 22:53:38 +00008929 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008930 return 0;
8931}
8932
Chris Lattner90951862006-04-16 00:51:47 +00008933/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8934/// elements from either LHS or RHS, return the shuffle mask and true.
8935/// Otherwise, return false.
8936static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8937 std::vector<Constant*> &Mask) {
8938 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8939 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008940 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008941
8942 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008943 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008944 return true;
8945 } else if (V == LHS) {
8946 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008947 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008948 return true;
8949 } else if (V == RHS) {
8950 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008951 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008952 return true;
8953 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8954 // If this is an insert of an extract from some other vector, include it.
8955 Value *VecOp = IEI->getOperand(0);
8956 Value *ScalarOp = IEI->getOperand(1);
8957 Value *IdxOp = IEI->getOperand(2);
8958
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008959 if (!isa<ConstantInt>(IdxOp))
8960 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008961 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008962
8963 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8964 // Okay, we can handle this if the vector we are insertinting into is
8965 // transitively ok.
8966 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8967 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008968 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008969 return true;
8970 }
8971 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8972 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008973 EI->getOperand(0)->getType() == V->getType()) {
8974 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008975 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008976
8977 // This must be extracting from either LHS or RHS.
8978 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8979 // Okay, we can handle this if the vector we are insertinting into is
8980 // transitively ok.
8981 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8982 // If so, update the mask to reflect the inserted value.
8983 if (EI->getOperand(0) == LHS) {
8984 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008985 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008986 } else {
8987 assert(EI->getOperand(0) == RHS);
8988 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008989 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008990
8991 }
8992 return true;
8993 }
8994 }
8995 }
8996 }
8997 }
8998 // TODO: Handle shufflevector here!
8999
9000 return false;
9001}
9002
9003/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9004/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9005/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009006static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009007 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009008 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009009 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009010 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009011 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009012
9013 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009014 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009015 return V;
9016 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009017 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009018 return V;
9019 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9020 // If this is an insert of an extract from some other vector, include it.
9021 Value *VecOp = IEI->getOperand(0);
9022 Value *ScalarOp = IEI->getOperand(1);
9023 Value *IdxOp = IEI->getOperand(2);
9024
9025 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9026 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9027 EI->getOperand(0)->getType() == V->getType()) {
9028 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009029 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9030 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009031
9032 // Either the extracted from or inserted into vector must be RHSVec,
9033 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009034 if (EI->getOperand(0) == RHS || RHS == 0) {
9035 RHS = EI->getOperand(0);
9036 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009037 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009038 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009039 return V;
9040 }
9041
Chris Lattner90951862006-04-16 00:51:47 +00009042 if (VecOp == RHS) {
9043 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009044 // Everything but the extracted element is replaced with the RHS.
9045 for (unsigned i = 0; i != NumElts; ++i) {
9046 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009047 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009048 }
9049 return V;
9050 }
Chris Lattner90951862006-04-16 00:51:47 +00009051
9052 // If this insertelement is a chain that comes from exactly these two
9053 // vectors, return the vector and the effective shuffle.
9054 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9055 return EI->getOperand(0);
9056
Chris Lattner39fac442006-04-15 01:39:45 +00009057 }
9058 }
9059 }
Chris Lattner90951862006-04-16 00:51:47 +00009060 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009061
9062 // Otherwise, can't do anything fancy. Return an identity vector.
9063 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009064 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009065 return V;
9066}
9067
9068Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9069 Value *VecOp = IE.getOperand(0);
9070 Value *ScalarOp = IE.getOperand(1);
9071 Value *IdxOp = IE.getOperand(2);
9072
9073 // If the inserted element was extracted from some other vector, and if the
9074 // indexes are constant, try to turn this into a shufflevector operation.
9075 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9076 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9077 EI->getOperand(0)->getType() == IE.getType()) {
9078 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009079 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9080 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009081
9082 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9083 return ReplaceInstUsesWith(IE, VecOp);
9084
9085 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9086 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9087
9088 // If we are extracting a value from a vector, then inserting it right
9089 // back into the same place, just use the input vector.
9090 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9091 return ReplaceInstUsesWith(IE, VecOp);
9092
9093 // We could theoretically do this for ANY input. However, doing so could
9094 // turn chains of insertelement instructions into a chain of shufflevector
9095 // instructions, and right now we do not merge shufflevectors. As such,
9096 // only do this in a situation where it is clear that there is benefit.
9097 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9098 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9099 // the values of VecOp, except then one read from EIOp0.
9100 // Build a new shuffle mask.
9101 std::vector<Constant*> Mask;
9102 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009103 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009104 else {
9105 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009106 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009107 NumVectorElts));
9108 }
Reid Spencerc635f472006-12-31 05:48:39 +00009109 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009110 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009111 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009112 }
9113
9114 // If this insertelement isn't used by some other insertelement, turn it
9115 // (and any insertelements it points to), into one big shuffle.
9116 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9117 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009118 Value *RHS = 0;
9119 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9120 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9121 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009122 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009123 }
9124 }
9125 }
9126
9127 return 0;
9128}
9129
9130
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009131Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9132 Value *LHS = SVI.getOperand(0);
9133 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009134 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009135
9136 bool MadeChange = false;
9137
Chris Lattner2deeaea2006-10-05 06:55:50 +00009138 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009139 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009140 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9141
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009142 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009143 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009144 if (isa<UndefValue>(SVI.getOperand(1))) {
9145 // Scan to see if there are any references to the RHS. If so, replace them
9146 // with undef element refs and set MadeChange to true.
9147 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9148 if (Mask[i] >= e && Mask[i] != 2*e) {
9149 Mask[i] = 2*e;
9150 MadeChange = true;
9151 }
9152 }
9153
9154 if (MadeChange) {
9155 // Remap any references to RHS to use LHS.
9156 std::vector<Constant*> Elts;
9157 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9158 if (Mask[i] == 2*e)
9159 Elts.push_back(UndefValue::get(Type::Int32Ty));
9160 else
9161 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9162 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009163 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009164 }
9165 }
Chris Lattner39fac442006-04-15 01:39:45 +00009166
Chris Lattner12249be2006-05-25 23:48:38 +00009167 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9168 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9169 if (LHS == RHS || isa<UndefValue>(LHS)) {
9170 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009171 // shuffle(undef,undef,mask) -> undef.
9172 return ReplaceInstUsesWith(SVI, LHS);
9173 }
9174
Chris Lattner12249be2006-05-25 23:48:38 +00009175 // Remap any references to RHS to use LHS.
9176 std::vector<Constant*> Elts;
9177 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009178 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009179 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009180 else {
9181 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9182 (Mask[i] < e && isa<UndefValue>(LHS)))
9183 Mask[i] = 2*e; // Turn into undef.
9184 else
9185 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009186 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009187 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009188 }
Chris Lattner12249be2006-05-25 23:48:38 +00009189 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009190 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009191 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009192 LHS = SVI.getOperand(0);
9193 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009194 MadeChange = true;
9195 }
9196
Chris Lattner0e477162006-05-26 00:29:06 +00009197 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009198 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009199
Chris Lattner12249be2006-05-25 23:48:38 +00009200 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9201 if (Mask[i] >= e*2) continue; // Ignore undef values.
9202 // Is this an identity shuffle of the LHS value?
9203 isLHSID &= (Mask[i] == i);
9204
9205 // Is this an identity shuffle of the RHS value?
9206 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009207 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009208
Chris Lattner12249be2006-05-25 23:48:38 +00009209 // Eliminate identity shuffles.
9210 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9211 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009212
Chris Lattner0e477162006-05-26 00:29:06 +00009213 // If the LHS is a shufflevector itself, see if we can combine it with this
9214 // one without producing an unusual shuffle. Here we are really conservative:
9215 // we are absolutely afraid of producing a shuffle mask not in the input
9216 // program, because the code gen may not be smart enough to turn a merged
9217 // shuffle into two specific shuffles: it may produce worse code. As such,
9218 // we only merge two shuffles if the result is one of the two input shuffle
9219 // masks. In this case, merging the shuffles just removes one instruction,
9220 // which we know is safe. This is good for things like turning:
9221 // (splat(splat)) -> splat.
9222 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9223 if (isa<UndefValue>(RHS)) {
9224 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9225
9226 std::vector<unsigned> NewMask;
9227 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9228 if (Mask[i] >= 2*e)
9229 NewMask.push_back(2*e);
9230 else
9231 NewMask.push_back(LHSMask[Mask[i]]);
9232
9233 // If the result mask is equal to the src shuffle or this shuffle mask, do
9234 // the replacement.
9235 if (NewMask == LHSMask || NewMask == Mask) {
9236 std::vector<Constant*> Elts;
9237 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9238 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009239 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009240 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009241 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009242 }
9243 }
9244 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9245 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009246 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009247 }
9248 }
9249 }
Chris Lattner4284f642007-01-30 22:32:46 +00009250
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009251 return MadeChange ? &SVI : 0;
9252}
9253
9254
Robert Bocchinoa8352962006-01-13 22:48:06 +00009255
Chris Lattner39c98bb2004-12-08 23:43:58 +00009256
9257/// TryToSinkInstruction - Try to move the specified instruction from its
9258/// current block into the beginning of DestBlock, which can only happen if it's
9259/// safe to move the instruction past all of the instructions between it and the
9260/// end of its block.
9261static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9262 assert(I->hasOneUse() && "Invariants didn't hold!");
9263
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009264 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9265 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009266
Chris Lattner39c98bb2004-12-08 23:43:58 +00009267 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009268 if (isa<AllocaInst>(I) && I->getParent() ==
9269 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009270 return false;
9271
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009272 // We can only sink load instructions if there is nothing between the load and
9273 // the end of block that could change the value.
9274 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009275 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9276 Scan != E; ++Scan)
9277 if (Scan->mayWriteToMemory())
9278 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009279 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009280
9281 BasicBlock::iterator InsertPos = DestBlock->begin();
9282 while (isa<PHINode>(InsertPos)) ++InsertPos;
9283
Chris Lattner9f269e42005-08-08 19:11:57 +00009284 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009285 ++NumSunkInst;
9286 return true;
9287}
9288
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009289
9290/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9291/// all reachable code to the worklist.
9292///
9293/// This has a couple of tricks to make the code faster and more powerful. In
9294/// particular, we constant fold and DCE instructions as we go, to avoid adding
9295/// them to the worklist (this significantly speeds up instcombine on code where
9296/// many instructions are dead or constant). Additionally, if we find a branch
9297/// whose condition is a known constant, we only visit the reachable successors.
9298///
9299static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009300 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009301 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009302 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009303 std::vector<BasicBlock*> Worklist;
9304 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009305
Chris Lattner12b89cc2007-03-23 19:17:18 +00009306 while (!Worklist.empty()) {
9307 BB = Worklist.back();
9308 Worklist.pop_back();
9309
9310 // We have now visited this block! If we've already been here, ignore it.
9311 if (!Visited.insert(BB)) continue;
9312
9313 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9314 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009315
Chris Lattner12b89cc2007-03-23 19:17:18 +00009316 // DCE instruction if trivially dead.
9317 if (isInstructionTriviallyDead(Inst)) {
9318 ++NumDeadInst;
9319 DOUT << "IC: DCE: " << *Inst;
9320 Inst->eraseFromParent();
9321 continue;
9322 }
9323
9324 // ConstantProp instruction if trivially constant.
9325 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9326 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9327 Inst->replaceAllUsesWith(C);
9328 ++NumConstProp;
9329 Inst->eraseFromParent();
9330 continue;
9331 }
9332
9333 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009334 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009335
9336 // Recursively visit successors. If this is a branch or switch on a
9337 // constant, only visit the reachable successor.
9338 TerminatorInst *TI = BB->getTerminator();
9339 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9340 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9341 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9342 Worklist.push_back(BI->getSuccessor(!CondVal));
9343 continue;
9344 }
9345 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9346 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9347 // See if this is an explicit destination.
9348 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9349 if (SI->getCaseValue(i) == Cond) {
9350 Worklist.push_back(SI->getSuccessor(i));
9351 continue;
9352 }
9353
9354 // Otherwise it is the default destination.
9355 Worklist.push_back(SI->getSuccessor(0));
9356 continue;
9357 }
9358 }
9359
9360 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9361 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009362 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009363}
9364
Chris Lattner960a5432007-03-03 02:04:50 +00009365bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009366 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009367 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009368
9369 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9370 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009371
Chris Lattner4ed40f72005-07-07 20:40:38 +00009372 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009373 // Do a depth-first traversal of the function, populate the worklist with
9374 // the reachable instructions. Ignore blocks that are not reachable. Keep
9375 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009376 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009377 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009378
Chris Lattner4ed40f72005-07-07 20:40:38 +00009379 // Do a quick scan over the function. If we find any blocks that are
9380 // unreachable, remove any instructions inside of them. This prevents
9381 // the instcombine code from having to deal with some bad special cases.
9382 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9383 if (!Visited.count(BB)) {
9384 Instruction *Term = BB->getTerminator();
9385 while (Term != BB->begin()) { // Remove instrs bottom-up
9386 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009387
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009388 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009389 ++NumDeadInst;
9390
9391 if (!I->use_empty())
9392 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9393 I->eraseFromParent();
9394 }
9395 }
9396 }
Chris Lattnerca081252001-12-14 16:52:21 +00009397
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009398 while (!Worklist.empty()) {
9399 Instruction *I = RemoveOneFromWorkList();
9400 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009401
Chris Lattner1443bc52006-05-11 17:11:52 +00009402 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009403 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009404 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009405 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009406 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009407 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009408
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009409 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009410
9411 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009412 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009413 continue;
9414 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009415
Chris Lattner1443bc52006-05-11 17:11:52 +00009416 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009417 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009418 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009419
Chris Lattner1443bc52006-05-11 17:11:52 +00009420 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009421 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009422 ReplaceInstUsesWith(*I, C);
9423
Chris Lattner99f48c62002-09-02 04:59:56 +00009424 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009425 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009426 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009427 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009428 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009429
Chris Lattner39c98bb2004-12-08 23:43:58 +00009430 // See if we can trivially sink this instruction to a successor basic block.
9431 if (I->hasOneUse()) {
9432 BasicBlock *BB = I->getParent();
9433 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9434 if (UserParent != BB) {
9435 bool UserIsSuccessor = false;
9436 // See if the user is one of our successors.
9437 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9438 if (*SI == UserParent) {
9439 UserIsSuccessor = true;
9440 break;
9441 }
9442
9443 // If the user is one of our immediate successors, and if that successor
9444 // only has us as a predecessors (we'd have to split the critical edge
9445 // otherwise), we can keep going.
9446 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9447 next(pred_begin(UserParent)) == pred_end(UserParent))
9448 // Okay, the CFG is simple enough, try to sink this instruction.
9449 Changed |= TryToSinkInstruction(I, UserParent);
9450 }
9451 }
9452
Chris Lattnerca081252001-12-14 16:52:21 +00009453 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009454#ifndef NDEBUG
9455 std::string OrigI;
9456#endif
9457 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009458 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009459 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009460 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009461 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009462 DOUT << "IC: Old = " << *I
9463 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009464
Chris Lattner396dbfe2004-06-09 05:08:07 +00009465 // Everything uses the new instruction now.
9466 I->replaceAllUsesWith(Result);
9467
9468 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009469 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009470 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009471
Chris Lattner6e0123b2007-02-11 01:23:03 +00009472 // Move the name to the new instruction first.
9473 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009474
9475 // Insert the new instruction into the basic block...
9476 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009477 BasicBlock::iterator InsertPos = I;
9478
9479 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9480 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9481 ++InsertPos;
9482
9483 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009484
Chris Lattner63d75af2004-05-01 23:27:23 +00009485 // Make sure that we reprocess all operands now that we reduced their
9486 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009487 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009488
Chris Lattner396dbfe2004-06-09 05:08:07 +00009489 // Instructions can end up on the worklist more than once. Make sure
9490 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009491 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009492
9493 // Erase the old instruction.
9494 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009495 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009496#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009497 DOUT << "IC: Mod = " << OrigI
9498 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009499#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009500
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009501 // If the instruction was modified, it's possible that it is now dead.
9502 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009503 if (isInstructionTriviallyDead(I)) {
9504 // Make sure we process all operands now that we are reducing their
9505 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009506 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009507
Chris Lattner63d75af2004-05-01 23:27:23 +00009508 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009509 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009510 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009511 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009512 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009513 AddToWorkList(I);
9514 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009515 }
Chris Lattner053c0932002-05-14 15:24:07 +00009516 }
Chris Lattner260ab202002-04-18 17:39:14 +00009517 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009518 }
9519 }
9520
Chris Lattner960a5432007-03-03 02:04:50 +00009521 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009522 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009523}
9524
Chris Lattner960a5432007-03-03 02:04:50 +00009525
9526bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009527 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9528
Chris Lattner960a5432007-03-03 02:04:50 +00009529 bool EverMadeChange = false;
9530
9531 // Iterate while there is work to do.
9532 unsigned Iteration = 0;
9533 while (DoOneIteration(F, Iteration++))
9534 EverMadeChange = true;
9535 return EverMadeChange;
9536}
9537
Brian Gaeke38b79e82004-07-27 17:43:21 +00009538FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009539 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009540}
Brian Gaeke960707c2003-11-11 22:41:34 +00009541