blob: 07ffb19277089dc1c6a31af35005f06c09f328c4 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris 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 Spencer3f4e6e82007-02-04 00:40:42 +000059#include <set>
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
Chris Lattner0157e7f2006-02-11 09:31:47 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000325
Chris Lattner2deeaea2006-10-05 06:55:50 +0000326 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
327 uint64_t &UndefElts, unsigned Depth = 0);
328
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000329 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
330 // PHI node as operand #0, see if we can fold the instruction into the PHI
331 // (which is only possible if all operands to the PHI are constants).
332 Instruction *FoldOpIntoPhi(Instruction &I);
333
Chris Lattner7515cab2004-11-14 19:13:23 +0000334 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
335 // operator and they all are only used by the PHI, PHI together their
336 // inputs, and do the operation once, to the result of the PHI.
337 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000338 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
339
340
Zhou Sheng75b871f2007-01-11 12:24:14 +0000341 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
342 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000343
Zhou Sheng75b871f2007-01-11 12:24:14 +0000344 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000345 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000346 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000347 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000348 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000349 Instruction *MatchBSwap(BinaryOperator &I);
350
Reid Spencer74a528b2006-12-13 18:21:21 +0000351 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000352 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000353
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000354 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000355}
356
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000357// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000358// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359static unsigned getComplexity(Value *V) {
360 if (isa<Instruction>(V)) {
361 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000362 return 3;
363 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000364 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000365 if (isa<Argument>(V)) return 3;
366 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000367}
Chris Lattner260ab202002-04-18 17:39:14 +0000368
Chris Lattner7fb29e12003-03-11 00:12:48 +0000369// isOnlyUse - Return true if this instruction will be deleted if we stop using
370// it.
371static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000372 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373}
374
Chris Lattnere79e8542004-02-23 06:38:22 +0000375// getPromotedType - Return the specified type promoted as it would be to pass
376// though a va_arg area...
377static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000378 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
379 if (ITy->getBitWidth() < 32)
380 return Type::Int32Ty;
381 } else if (Ty == Type::FloatTy)
382 return Type::DoubleTy;
383 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000384}
385
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000386/// getBitCastOperand - If the specified operand is a CastInst or a constant
387/// expression bitcast, return the operand value, otherwise return null.
388static Value *getBitCastOperand(Value *V) {
389 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000390 return I->getOperand(0);
391 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000392 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000393 return CE->getOperand(0);
394 return 0;
395}
396
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000397/// This function is a wrapper around CastInst::isEliminableCastPair. It
398/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399static Instruction::CastOps
400isEliminableCastPair(
401 const CastInst *CI, ///< The first cast instruction
402 unsigned opcode, ///< The opcode of the second cast instruction
403 const Type *DstTy, ///< The target type for the second cast instruction
404 TargetData *TD ///< The target data for pointer size
405) {
406
407 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
408 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000409
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000410 // Get the opcodes of the two Cast instructions
411 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
412 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000413
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000414 return Instruction::CastOps(
415 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
416 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000417}
418
419/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
420/// in any code being generated. It does not require codegen if V is simple
421/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000422static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
423 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000424 if (V->getType() == Ty || isa<Constant>(V)) return false;
425
Chris Lattner99155be2006-05-25 23:24:33 +0000426 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000427 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000428 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 return false;
430 return true;
431}
432
433/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
434/// InsertBefore instruction. This is specialized a bit to avoid inserting
435/// casts that are known to not do anything...
436///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000437Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
438 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000439 Instruction *InsertBefore) {
440 if (V->getType() == DestTy) return V;
441 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000442 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000443
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445}
446
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000447// SimplifyCommutative - This performs a few simplifications for commutative
448// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000449//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000450// 1. Order operands such that they are listed from right (least complex) to
451// left (most complex). This puts constants before unary operators before
452// binary operators.
453//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000454// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
455// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000457bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 bool Changed = false;
459 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
460 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000462 if (!I.isAssociative()) return Changed;
463 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000464 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
465 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
466 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000467 Constant *Folded = ConstantExpr::get(I.getOpcode(),
468 cast<Constant>(I.getOperand(1)),
469 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000470 I.setOperand(0, Op->getOperand(0));
471 I.setOperand(1, Folded);
472 return true;
473 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
474 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
475 isOnlyUse(Op) && isOnlyUse(Op1)) {
476 Constant *C1 = cast<Constant>(Op->getOperand(1));
477 Constant *C2 = cast<Constant>(Op1->getOperand(1));
478
479 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000480 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000481 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
482 Op1->getOperand(0),
483 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000484 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000485 I.setOperand(0, New);
486 I.setOperand(1, Folded);
487 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000488 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000489 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000490 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000491}
Chris Lattnerca081252001-12-14 16:52:21 +0000492
Reid Spencer266e42b2006-12-23 06:05:41 +0000493/// SimplifyCompare - For a CmpInst this function just orders the operands
494/// so that theyare listed from right (least complex) to left (most complex).
495/// This puts constants before unary operators before binary operators.
496bool InstCombiner::SimplifyCompare(CmpInst &I) {
497 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
498 return false;
499 I.swapOperands();
500 // Compare instructions are not associative so there's nothing else we can do.
501 return true;
502}
503
Chris Lattnerbb74e222003-03-10 23:06:50 +0000504// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
505// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000506//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000507static inline Value *dyn_castNegVal(Value *V) {
508 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000509 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000510
Chris Lattner9ad0d552004-12-14 20:08:06 +0000511 // Constants can be considered to be negated values if they can be folded.
512 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
513 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000515}
516
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517static inline Value *dyn_castNotVal(Value *V) {
518 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000519 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000520
521 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000522 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000523 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524 return 0;
525}
526
Chris Lattner7fb29e12003-03-11 00:12:48 +0000527// dyn_castFoldableMul - If this value is a multiply that can be folded into
528// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000529// non-constant operand of the multiply, and set CST to point to the multiplier.
530// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000532static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000533 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000535 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000536 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000539 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 // The multiplier is really 1 << CST.
541 Constant *One = ConstantInt::get(V->getType(), 1);
542 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
543 return I->getOperand(0);
544 }
545 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000547}
Chris Lattner31ae8632002-08-14 17:51:49 +0000548
Chris Lattner0798af32005-01-13 20:14:25 +0000549/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
550/// expression, return it.
551static User *dyn_castGetElementPtr(Value *V) {
552 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
553 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
554 if (CE->getOpcode() == Instruction::GetElementPtr)
555 return cast<User>(V);
556 return false;
557}
558
Chris Lattner623826c2004-09-28 21:48:02 +0000559// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000560static ConstantInt *AddOne(ConstantInt *C) {
561 return cast<ConstantInt>(ConstantExpr::getAdd(C,
562 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000563}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000564static ConstantInt *SubOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getSub(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000567}
568
Chris Lattner4534dd592006-02-09 07:38:58 +0000569/// ComputeMaskedBits - Determine which of the bits specified in Mask are
570/// known to be either zero or one and return them in the KnownZero/KnownOne
571/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
572/// processing.
573static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
574 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000575 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
576 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000577 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000578 // optimized based on the contradictory assumption that it is non-zero.
579 // Because instcombine aggressively folds operations with undef args anyway,
580 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000581 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000582 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000583 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000584 KnownZero = ~KnownOne & Mask;
585 return;
586 }
587
588 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000589 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000590 return; // Limit search depth.
591
592 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000593 Instruction *I = dyn_cast<Instruction>(V);
594 if (!I) return;
595
Reid Spencera94d3942007-01-19 21:13:56 +0000596 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000597
Chris Lattner0157e7f2006-02-11 09:31:47 +0000598 switch (I->getOpcode()) {
599 case Instruction::And:
600 // If either the LHS or the RHS are Zero, the result is zero.
601 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
602 Mask &= ~KnownZero;
603 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
604 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
605 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
606
607 // Output known-1 bits are only known if set in both the LHS & RHS.
608 KnownOne &= KnownOne2;
609 // Output known-0 are known to be clear if zero in either the LHS | RHS.
610 KnownZero |= KnownZero2;
611 return;
612 case Instruction::Or:
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 Mask &= ~KnownOne;
615 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618
619 // Output known-0 bits are only known if clear in both the LHS & RHS.
620 KnownZero &= KnownZero2;
621 // Output known-1 are known to be set if set in either the LHS | RHS.
622 KnownOne |= KnownOne2;
623 return;
624 case Instruction::Xor: {
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
629
630 // Output known-0 bits are known if clear or set in both the LHS & RHS.
631 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
632 // Output known-1 are known to be set if set in only one of the LHS, RHS.
633 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
634 KnownZero = KnownZeroOut;
635 return;
636 }
637 case Instruction::Select:
638 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
639 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
640 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
641 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
642
643 // Only known if known in both the LHS and RHS.
644 KnownOne &= KnownOne2;
645 KnownZero &= KnownZero2;
646 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000647 case Instruction::FPTrunc:
648 case Instruction::FPExt:
649 case Instruction::FPToUI:
650 case Instruction::FPToSI:
651 case Instruction::SIToFP:
652 case Instruction::PtrToInt:
653 case Instruction::UIToFP:
654 case Instruction::IntToPtr:
655 return; // Can't work with floating point or pointers
656 case Instruction::Trunc:
657 // All these have integer operands
658 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
659 return;
660 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000661 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000662 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000663 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000664 return;
665 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000666 break;
667 }
668 case Instruction::ZExt: {
669 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000670 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
671 uint64_t NotIn = ~SrcTy->getBitMask();
672 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000673
Reid Spencera94d3942007-01-19 21:13:56 +0000674 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
676 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
677 // The top bits are known to be zero.
678 KnownZero |= NewBits;
679 return;
680 }
681 case Instruction::SExt: {
682 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000683 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
684 uint64_t NotIn = ~SrcTy->getBitMask();
685 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000686
Reid Spencera94d3942007-01-19 21:13:56 +0000687 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000688 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
689 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000690
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000691 // If the sign bit of the input is known set or clear, then we know the
692 // top bits of the result.
693 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
694 if (KnownZero & InSignBit) { // Input sign bit known zero
695 KnownZero |= NewBits;
696 KnownOne &= ~NewBits;
697 } else if (KnownOne & InSignBit) { // Input sign bit known set
698 KnownOne |= NewBits;
699 KnownZero &= ~NewBits;
700 } else { // Input sign bit unknown
701 KnownZero &= ~NewBits;
702 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000703 }
704 return;
705 }
706 case Instruction::Shl:
707 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000708 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709 uint64_t ShiftAmt = SA->getZExtValue();
710 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000711 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
712 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000713 KnownZero <<= ShiftAmt;
714 KnownOne <<= ShiftAmt;
715 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000716 return;
717 }
718 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000719 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000721 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000722 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000723 uint64_t ShiftAmt = SA->getZExtValue();
724 uint64_t HighBits = (1ULL << ShiftAmt)-1;
725 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000726
Reid Spencerfdff9382006-11-08 06:47:33 +0000727 // Unsigned shift right.
728 Mask <<= ShiftAmt;
729 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
730 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
731 KnownZero >>= ShiftAmt;
732 KnownOne >>= ShiftAmt;
733 KnownZero |= HighBits; // high bits known zero.
734 return;
735 }
736 break;
737 case Instruction::AShr:
738 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
739 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
740 // Compute the new bits that are at the top now.
741 uint64_t ShiftAmt = SA->getZExtValue();
742 uint64_t HighBits = (1ULL << ShiftAmt)-1;
743 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
744
745 // Signed shift right.
746 Mask <<= ShiftAmt;
747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
748 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
749 KnownZero >>= ShiftAmt;
750 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000751
Reid Spencerfdff9382006-11-08 06:47:33 +0000752 // Handle the sign bits.
753 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
754 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755
Reid Spencerfdff9382006-11-08 06:47:33 +0000756 if (KnownZero & SignBit) { // New bits are known zero.
757 KnownZero |= HighBits;
758 } else if (KnownOne & SignBit) { // New bits are known one.
759 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000760 }
761 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000762 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000763 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000764 }
Chris Lattner92a68652006-02-07 08:05:22 +0000765}
766
767/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
768/// this predicate to simplify operations downstream. Mask is known to be zero
769/// for bits that V cannot have.
770static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000771 uint64_t KnownZero, KnownOne;
772 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
774 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000775}
776
Chris Lattner0157e7f2006-02-11 09:31:47 +0000777/// ShrinkDemandedConstant - Check to see if the specified operand of the
778/// specified instruction is a constant integer. If so, check to see if there
779/// are any bits set in the constant that are not demanded. If so, shrink the
780/// constant and return true.
781static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
782 uint64_t Demanded) {
783 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
784 if (!OpC) return false;
785
786 // If there are no bits set that aren't demanded, nothing to do.
787 if ((~Demanded & OpC->getZExtValue()) == 0)
788 return false;
789
790 // This is producing any bits that are not needed, shrink the RHS.
791 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000792 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000793 return true;
794}
795
Chris Lattneree0f2802006-02-12 02:07:56 +0000796// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
797// set of known zero and one bits, compute the maximum and minimum values that
798// could have the specified known zero and known one bits, returning them in
799// min/max.
800static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
801 uint64_t KnownZero,
802 uint64_t KnownOne,
803 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000804 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000805 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806
807 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
808
809 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
810 // bit if it is unknown.
811 Min = KnownOne;
812 Max = KnownOne|UnknownBits;
813
814 if (SignBit & UnknownBits) { // Sign bit is unknown
815 Min |= SignBit;
816 Max &= ~SignBit;
817 }
818
819 // Sign extend the min/max values.
820 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
821 Min = (Min << ShAmt) >> ShAmt;
822 Max = (Max << ShAmt) >> ShAmt;
823}
824
825// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
826// a set of known zero and one bits, compute the maximum and minimum values that
827// could have the specified known zero and known one bits, returning them in
828// min/max.
829static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
830 uint64_t KnownZero,
831 uint64_t KnownOne,
832 uint64_t &Min,
833 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000834 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000835 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
836
837 // The minimum value is when the unknown bits are all zeros.
838 Min = KnownOne;
839 // The maximum value is when the unknown bits are all ones.
840 Max = KnownOne|UnknownBits;
841}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000842
843
844/// SimplifyDemandedBits - Look at V. At this point, we know that only the
845/// DemandedMask bits of the result of V are ever used downstream. If we can
846/// use this information to simplify V, do so and return true. Otherwise,
847/// analyze the expression and return a mask of KnownOne and KnownZero bits for
848/// the expression (used to simplify the caller). The KnownZero/One bits may
849/// only be accurate for those bits in the DemandedMask.
850bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
851 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000852 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000853 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000854 // We know all of the bits for a constant!
855 KnownOne = CI->getZExtValue() & DemandedMask;
856 KnownZero = ~KnownOne & DemandedMask;
857 return false;
858 }
859
860 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000861 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000862 if (Depth != 0) { // Not at the root.
863 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
864 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000865 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000866 }
Chris Lattner2590e512006-02-07 06:56:34 +0000867 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 // just set the DemandedMask to all bits.
Reid Spencera94d3942007-01-19 21:13:56 +0000869 DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000870 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000871 if (V != UndefValue::get(V->getType()))
872 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
873 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000874 } else if (Depth == 6) { // Limit search depth.
875 return false;
876 }
877
878 Instruction *I = dyn_cast<Instruction>(V);
879 if (!I) return false; // Only analyze instructions.
880
Reid Spencera94d3942007-01-19 21:13:56 +0000881 DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000882
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000883 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000884 switch (I->getOpcode()) {
885 default: break;
886 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000887 // If either the LHS or the RHS are Zero, the result is zero.
888 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
889 KnownZero, KnownOne, Depth+1))
890 return true;
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892
893 // If something is known zero on the RHS, the bits aren't demanded on the
894 // LHS.
895 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
896 KnownZero2, KnownOne2, Depth+1))
897 return true;
898 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
899
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000900 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000901 // These bits cannot contribute to the result of the 'and'.
902 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
903 return UpdateValueUsesWith(I, I->getOperand(0));
904 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
905 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000906
907 // If all of the demanded bits in the inputs are known zeros, return zero.
908 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
909 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
910
Chris Lattner0157e7f2006-02-11 09:31:47 +0000911 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000912 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000913 return UpdateValueUsesWith(I, I);
914
915 // Output known-1 bits are only known if set in both the LHS & RHS.
916 KnownOne &= KnownOne2;
917 // Output known-0 are known to be clear if zero in either the LHS | RHS.
918 KnownZero |= KnownZero2;
919 break;
920 case Instruction::Or:
921 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922 KnownZero, KnownOne, Depth+1))
923 return true;
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
926 KnownZero2, KnownOne2, Depth+1))
927 return true;
928 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
929
930 // If all of the demanded bits are known zero on one side, return the other.
931 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000932 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000933 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000934 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000935 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000936
937 // If all of the potentially set bits on one side are known to be set on
938 // the other side, just use the 'other' side.
939 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
940 (DemandedMask & (~KnownZero)))
941 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000942 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
943 (DemandedMask & (~KnownZero2)))
944 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000945
946 // If the RHS is a constant, see if we can simplify it.
947 if (ShrinkDemandedConstant(I, 1, DemandedMask))
948 return UpdateValueUsesWith(I, I);
949
950 // Output known-0 bits are only known if clear in both the LHS & RHS.
951 KnownZero &= KnownZero2;
952 // Output known-1 are known to be set if set in either the LHS | RHS.
953 KnownOne |= KnownOne2;
954 break;
955 case Instruction::Xor: {
956 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
957 KnownZero, KnownOne, Depth+1))
958 return true;
959 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
960 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
961 KnownZero2, KnownOne2, Depth+1))
962 return true;
963 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
964
965 // If all of the demanded bits are known zero on one side, return the other.
966 // These bits cannot contribute to the result of the 'xor'.
967 if ((DemandedMask & KnownZero) == DemandedMask)
968 return UpdateValueUsesWith(I, I->getOperand(0));
969 if ((DemandedMask & KnownZero2) == DemandedMask)
970 return UpdateValueUsesWith(I, I->getOperand(1));
971
972 // Output known-0 bits are known if clear or set in both the LHS & RHS.
973 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
974 // Output known-1 are known to be set if set in only one of the LHS, RHS.
975 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
976
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000977 // If all of the demanded bits are known to be zero on one side or the
978 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000979 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000980 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
981 Instruction *Or =
982 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
983 I->getName());
984 InsertNewInstBefore(Or, *I);
985 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000986 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000987
Chris Lattner5b2edb12006-02-12 08:02:11 +0000988 // If all of the demanded bits on one side are known, and all of the set
989 // bits on that side are also known to be set on the other side, turn this
990 // into an AND, as we know the bits will be cleared.
991 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
992 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
993 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000994 Constant *AndC = ConstantInt::get(I->getType(),
995 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000996 Instruction *And =
997 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
998 InsertNewInstBefore(And, *I);
999 return UpdateValueUsesWith(I, And);
1000 }
1001 }
1002
Chris Lattner0157e7f2006-02-11 09:31:47 +00001003 // If the RHS is a constant, see if we can simplify it.
1004 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1005 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006 return UpdateValueUsesWith(I, I);
1007
1008 KnownZero = KnownZeroOut;
1009 KnownOne = KnownOneOut;
1010 break;
1011 }
1012 case Instruction::Select:
1013 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1014 KnownZero, KnownOne, Depth+1))
1015 return true;
1016 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1017 KnownZero2, KnownOne2, Depth+1))
1018 return true;
1019 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1020 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1021
1022 // If the operands are constants, see if we can simplify them.
1023 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1024 return UpdateValueUsesWith(I, I);
1025 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1026 return UpdateValueUsesWith(I, I);
1027
1028 // Only known if known in both the LHS and RHS.
1029 KnownOne &= KnownOne2;
1030 KnownZero &= KnownZero2;
1031 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001032 case Instruction::Trunc:
1033 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1034 KnownZero, KnownOne, Depth+1))
1035 return true;
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 break;
1038 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001039 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001040 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001041
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001042 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1043 KnownZero, KnownOne, Depth+1))
1044 return true;
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1046 break;
1047 case Instruction::ZExt: {
1048 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001049 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1050 uint64_t NotIn = ~SrcTy->getBitMask();
1051 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001052
Reid Spencera94d3942007-01-19 21:13:56 +00001053 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001054 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1055 KnownZero, KnownOne, Depth+1))
1056 return true;
1057 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1058 // The top bits are known to be zero.
1059 KnownZero |= NewBits;
1060 break;
1061 }
1062 case Instruction::SExt: {
1063 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001064 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1065 uint64_t NotIn = ~SrcTy->getBitMask();
1066 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001067
1068 // Get the sign bit for the source type
1069 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001070 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001071
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001072 // If any of the sign extended bits are demanded, we know that the sign
1073 // bit is demanded.
1074 if (NewBits & DemandedMask)
1075 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001076
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001077 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1078 KnownZero, KnownOne, Depth+1))
1079 return true;
1080 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001081
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001082 // If the sign bit of the input is known set or clear, then we know the
1083 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001084
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001085 // If the input sign bit is known zero, or if the NewBits are not demanded
1086 // convert this into a zero extension.
1087 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1088 // Convert to ZExt cast
1089 CastInst *NewCast = CastInst::create(
1090 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1091 return UpdateValueUsesWith(I, NewCast);
1092 } else if (KnownOne & InSignBit) { // Input sign bit known set
1093 KnownOne |= NewBits;
1094 KnownZero &= ~NewBits;
1095 } else { // Input sign bit unknown
1096 KnownZero &= ~NewBits;
1097 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001098 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001099 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001100 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001101 case Instruction::Add:
1102 // If there is a constant on the RHS, there are a variety of xformations
1103 // we can do.
1104 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1105 // If null, this should be simplified elsewhere. Some of the xforms here
1106 // won't work if the RHS is zero.
1107 if (RHS->isNullValue())
1108 break;
1109
1110 // Figure out what the input bits are. If the top bits of the and result
1111 // are not demanded, then the add doesn't demand them from its input
1112 // either.
1113
1114 // Shift the demanded mask up so that it's at the top of the uint64_t.
1115 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1116 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1117
1118 // If the top bit of the output is demanded, demand everything from the
1119 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001120 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001121
1122 // Find information about known zero/one bits in the input.
1123 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1124 KnownZero2, KnownOne2, Depth+1))
1125 return true;
1126
1127 // If the RHS of the add has bits set that can't affect the input, reduce
1128 // the constant.
1129 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1130 return UpdateValueUsesWith(I, I);
1131
1132 // Avoid excess work.
1133 if (KnownZero2 == 0 && KnownOne2 == 0)
1134 break;
1135
1136 // Turn it into OR if input bits are zero.
1137 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1138 Instruction *Or =
1139 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1140 I->getName());
1141 InsertNewInstBefore(Or, *I);
1142 return UpdateValueUsesWith(I, Or);
1143 }
1144
1145 // We can say something about the output known-zero and known-one bits,
1146 // depending on potential carries from the input constant and the
1147 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1148 // bits set and the RHS constant is 0x01001, then we know we have a known
1149 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1150
1151 // To compute this, we first compute the potential carry bits. These are
1152 // the bits which may be modified. I'm not aware of a better way to do
1153 // this scan.
1154 uint64_t RHSVal = RHS->getZExtValue();
1155
1156 bool CarryIn = false;
1157 uint64_t CarryBits = 0;
1158 uint64_t CurBit = 1;
1159 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1160 // Record the current carry in.
1161 if (CarryIn) CarryBits |= CurBit;
1162
1163 bool CarryOut;
1164
1165 // This bit has a carry out unless it is "zero + zero" or
1166 // "zero + anything" with no carry in.
1167 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1168 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1169 } else if (!CarryIn &&
1170 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1171 CarryOut = false; // 0 + anything has no carry out if no carry in.
1172 } else {
1173 // Otherwise, we have to assume we have a carry out.
1174 CarryOut = true;
1175 }
1176
1177 // This stage's carry out becomes the next stage's carry-in.
1178 CarryIn = CarryOut;
1179 }
1180
1181 // Now that we know which bits have carries, compute the known-1/0 sets.
1182
1183 // Bits are known one if they are known zero in one operand and one in the
1184 // other, and there is no input carry.
1185 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1186
1187 // Bits are known zero if they are known zero in both operands and there
1188 // is no input carry.
1189 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1190 }
1191 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001192 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001193 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1194 uint64_t ShiftAmt = SA->getZExtValue();
1195 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001196 KnownZero, KnownOne, Depth+1))
1197 return true;
1198 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001199 KnownZero <<= ShiftAmt;
1200 KnownOne <<= ShiftAmt;
1201 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001202 }
Chris Lattner2590e512006-02-07 06:56:34 +00001203 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001204 case Instruction::LShr:
1205 // For a logical shift right
1206 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1207 unsigned ShiftAmt = SA->getZExtValue();
1208
1209 // Compute the new bits that are at the top now.
1210 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1211 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001212 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001213 // Unsigned shift right.
1214 if (SimplifyDemandedBits(I->getOperand(0),
1215 (DemandedMask << ShiftAmt) & TypeMask,
1216 KnownZero, KnownOne, Depth+1))
1217 return true;
1218 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1219 KnownZero &= TypeMask;
1220 KnownOne &= TypeMask;
1221 KnownZero >>= ShiftAmt;
1222 KnownOne >>= ShiftAmt;
1223 KnownZero |= HighBits; // high bits known zero.
1224 }
1225 break;
1226 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001227 // If this is an arithmetic shift right and only the low-bit is set, we can
1228 // always convert this into a logical shr, even if the shift amount is
1229 // variable. The low bit of the shift cannot be an input sign bit unless
1230 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001231 if (DemandedMask == 1) {
1232 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001233 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001234 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001235 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001236 return UpdateValueUsesWith(I, NewVal);
1237 }
1238
Reid Spencere0fc4df2006-10-20 07:07:24 +00001239 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1240 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001241
1242 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001243 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1244 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001245 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001246 // Signed shift right.
1247 if (SimplifyDemandedBits(I->getOperand(0),
1248 (DemandedMask << ShiftAmt) & TypeMask,
1249 KnownZero, KnownOne, Depth+1))
1250 return true;
1251 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1252 KnownZero &= TypeMask;
1253 KnownOne &= TypeMask;
1254 KnownZero >>= ShiftAmt;
1255 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001256
Reid Spencerfdff9382006-11-08 06:47:33 +00001257 // Handle the sign bits.
1258 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1259 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001260
Reid Spencerfdff9382006-11-08 06:47:33 +00001261 // If the input sign bit is known to be zero, or if none of the top bits
1262 // are demanded, turn this into an unsigned shift right.
1263 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1264 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001265 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001266 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001267 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1268 return UpdateValueUsesWith(I, NewVal);
1269 } else if (KnownOne & SignBit) { // New bits are known one.
1270 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001271 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001272 }
Chris Lattner2590e512006-02-07 06:56:34 +00001273 break;
1274 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001275
1276 // If the client is only demanding bits that we know, return the known
1277 // constant.
1278 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001279 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001280 return false;
1281}
1282
Chris Lattner2deeaea2006-10-05 06:55:50 +00001283
1284/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1285/// 64 or fewer elements. DemandedElts contains the set of elements that are
1286/// actually used by the caller. This method analyzes which elements of the
1287/// operand are undef and returns that information in UndefElts.
1288///
1289/// If the information about demanded elements can be used to simplify the
1290/// operation, the operation is simplified, then the resultant value is
1291/// returned. This returns null if no change was made.
1292Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1293 uint64_t &UndefElts,
1294 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001295 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001296 assert(VWidth <= 64 && "Vector too wide to analyze!");
1297 uint64_t EltMask = ~0ULL >> (64-VWidth);
1298 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1299 "Invalid DemandedElts!");
1300
1301 if (isa<UndefValue>(V)) {
1302 // If the entire vector is undefined, just return this info.
1303 UndefElts = EltMask;
1304 return 0;
1305 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1306 UndefElts = EltMask;
1307 return UndefValue::get(V->getType());
1308 }
1309
1310 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001311 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1312 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001313 Constant *Undef = UndefValue::get(EltTy);
1314
1315 std::vector<Constant*> Elts;
1316 for (unsigned i = 0; i != VWidth; ++i)
1317 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1318 Elts.push_back(Undef);
1319 UndefElts |= (1ULL << i);
1320 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1321 Elts.push_back(Undef);
1322 UndefElts |= (1ULL << i);
1323 } else { // Otherwise, defined.
1324 Elts.push_back(CP->getOperand(i));
1325 }
1326
1327 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001328 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001329 return NewCP != CP ? NewCP : 0;
1330 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001331 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001332 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001333 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001334 Constant *Zero = Constant::getNullValue(EltTy);
1335 Constant *Undef = UndefValue::get(EltTy);
1336 std::vector<Constant*> Elts;
1337 for (unsigned i = 0; i != VWidth; ++i)
1338 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1339 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001340 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001341 }
1342
1343 if (!V->hasOneUse()) { // Other users may use these bits.
1344 if (Depth != 0) { // Not at the root.
1345 // TODO: Just compute the UndefElts information recursively.
1346 return false;
1347 }
1348 return false;
1349 } else if (Depth == 10) { // Limit search depth.
1350 return false;
1351 }
1352
1353 Instruction *I = dyn_cast<Instruction>(V);
1354 if (!I) return false; // Only analyze instructions.
1355
1356 bool MadeChange = false;
1357 uint64_t UndefElts2;
1358 Value *TmpV;
1359 switch (I->getOpcode()) {
1360 default: break;
1361
1362 case Instruction::InsertElement: {
1363 // If this is a variable index, we don't know which element it overwrites.
1364 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001365 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001366 if (Idx == 0) {
1367 // Note that we can't propagate undef elt info, because we don't know
1368 // which elt is getting updated.
1369 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1370 UndefElts2, Depth+1);
1371 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372 break;
1373 }
1374
1375 // If this is inserting an element that isn't demanded, remove this
1376 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001377 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001378 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1379 return AddSoonDeadInstToWorklist(*I, 0);
1380
1381 // Otherwise, the element inserted overwrites whatever was there, so the
1382 // input demanded set is simpler than the output set.
1383 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1384 DemandedElts & ~(1ULL << IdxNo),
1385 UndefElts, Depth+1);
1386 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1387
1388 // The inserted element is defined.
1389 UndefElts |= 1ULL << IdxNo;
1390 break;
1391 }
1392
1393 case Instruction::And:
1394 case Instruction::Or:
1395 case Instruction::Xor:
1396 case Instruction::Add:
1397 case Instruction::Sub:
1398 case Instruction::Mul:
1399 // div/rem demand all inputs, because they don't want divide by zero.
1400 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1401 UndefElts, Depth+1);
1402 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1403 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1404 UndefElts2, Depth+1);
1405 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1406
1407 // Output elements are undefined if both are undefined. Consider things
1408 // like undef&0. The result is known zero, not undef.
1409 UndefElts &= UndefElts2;
1410 break;
1411
1412 case Instruction::Call: {
1413 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1414 if (!II) break;
1415 switch (II->getIntrinsicID()) {
1416 default: break;
1417
1418 // Binary vector operations that work column-wise. A dest element is a
1419 // function of the corresponding input elements from the two inputs.
1420 case Intrinsic::x86_sse_sub_ss:
1421 case Intrinsic::x86_sse_mul_ss:
1422 case Intrinsic::x86_sse_min_ss:
1423 case Intrinsic::x86_sse_max_ss:
1424 case Intrinsic::x86_sse2_sub_sd:
1425 case Intrinsic::x86_sse2_mul_sd:
1426 case Intrinsic::x86_sse2_min_sd:
1427 case Intrinsic::x86_sse2_max_sd:
1428 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1429 UndefElts, Depth+1);
1430 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1431 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1432 UndefElts2, Depth+1);
1433 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1434
1435 // If only the low elt is demanded and this is a scalarizable intrinsic,
1436 // scalarize it now.
1437 if (DemandedElts == 1) {
1438 switch (II->getIntrinsicID()) {
1439 default: break;
1440 case Intrinsic::x86_sse_sub_ss:
1441 case Intrinsic::x86_sse_mul_ss:
1442 case Intrinsic::x86_sse2_sub_sd:
1443 case Intrinsic::x86_sse2_mul_sd:
1444 // TODO: Lower MIN/MAX/ABS/etc
1445 Value *LHS = II->getOperand(1);
1446 Value *RHS = II->getOperand(2);
1447 // Extract the element as scalars.
1448 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1449 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1450
1451 switch (II->getIntrinsicID()) {
1452 default: assert(0 && "Case stmts out of sync!");
1453 case Intrinsic::x86_sse_sub_ss:
1454 case Intrinsic::x86_sse2_sub_sd:
1455 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1456 II->getName()), *II);
1457 break;
1458 case Intrinsic::x86_sse_mul_ss:
1459 case Intrinsic::x86_sse2_mul_sd:
1460 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1461 II->getName()), *II);
1462 break;
1463 }
1464
1465 Instruction *New =
1466 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1467 II->getName());
1468 InsertNewInstBefore(New, *II);
1469 AddSoonDeadInstToWorklist(*II, 0);
1470 return New;
1471 }
1472 }
1473
1474 // Output elements are undefined if both are undefined. Consider things
1475 // like undef&0. The result is known zero, not undef.
1476 UndefElts &= UndefElts2;
1477 break;
1478 }
1479 break;
1480 }
1481 }
1482 return MadeChange ? I : 0;
1483}
1484
Reid Spencer266e42b2006-12-23 06:05:41 +00001485/// @returns true if the specified compare instruction is
1486/// true when both operands are equal...
1487/// @brief Determine if the ICmpInst returns true if both operands are equal
1488static bool isTrueWhenEqual(ICmpInst &ICI) {
1489 ICmpInst::Predicate pred = ICI.getPredicate();
1490 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1491 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1492 pred == ICmpInst::ICMP_SLE;
1493}
1494
Chris Lattnerb8b97502003-08-13 19:01:45 +00001495/// AssociativeOpt - Perform an optimization on an associative operator. This
1496/// function is designed to check a chain of associative operators for a
1497/// potential to apply a certain optimization. Since the optimization may be
1498/// applicable if the expression was reassociated, this checks the chain, then
1499/// reassociates the expression as necessary to expose the optimization
1500/// opportunity. This makes use of a special Functor, which must define
1501/// 'shouldApply' and 'apply' methods.
1502///
1503template<typename Functor>
1504Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1505 unsigned Opcode = Root.getOpcode();
1506 Value *LHS = Root.getOperand(0);
1507
1508 // Quick check, see if the immediate LHS matches...
1509 if (F.shouldApply(LHS))
1510 return F.apply(Root);
1511
1512 // Otherwise, if the LHS is not of the same opcode as the root, return.
1513 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001514 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001515 // Should we apply this transform to the RHS?
1516 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1517
1518 // If not to the RHS, check to see if we should apply to the LHS...
1519 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1520 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1521 ShouldApply = true;
1522 }
1523
1524 // If the functor wants to apply the optimization to the RHS of LHSI,
1525 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1526 if (ShouldApply) {
1527 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001528
Chris Lattnerb8b97502003-08-13 19:01:45 +00001529 // Now all of the instructions are in the current basic block, go ahead
1530 // and perform the reassociation.
1531 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1532
1533 // First move the selected RHS to the LHS of the root...
1534 Root.setOperand(0, LHSI->getOperand(1));
1535
1536 // Make what used to be the LHS of the root be the user of the root...
1537 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001538 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001539 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1540 return 0;
1541 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001542 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001543 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001544 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1545 BasicBlock::iterator ARI = &Root; ++ARI;
1546 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1547 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001548
1549 // Now propagate the ExtraOperand down the chain of instructions until we
1550 // get to LHSI.
1551 while (TmpLHSI != LHSI) {
1552 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001553 // Move the instruction to immediately before the chain we are
1554 // constructing to avoid breaking dominance properties.
1555 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1556 BB->getInstList().insert(ARI, NextLHSI);
1557 ARI = NextLHSI;
1558
Chris Lattnerb8b97502003-08-13 19:01:45 +00001559 Value *NextOp = NextLHSI->getOperand(1);
1560 NextLHSI->setOperand(1, ExtraOperand);
1561 TmpLHSI = NextLHSI;
1562 ExtraOperand = NextOp;
1563 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001564
Chris Lattnerb8b97502003-08-13 19:01:45 +00001565 // Now that the instructions are reassociated, have the functor perform
1566 // the transformation...
1567 return F.apply(Root);
1568 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001569
Chris Lattnerb8b97502003-08-13 19:01:45 +00001570 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1571 }
1572 return 0;
1573}
1574
1575
1576// AddRHS - Implements: X + X --> X << 1
1577struct AddRHS {
1578 Value *RHS;
1579 AddRHS(Value *rhs) : RHS(rhs) {}
1580 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1581 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001582 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001583 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001584 }
1585};
1586
1587// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1588// iff C1&C2 == 0
1589struct AddMaskingAnd {
1590 Constant *C2;
1591 AddMaskingAnd(Constant *c) : C2(c) {}
1592 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001593 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001594 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001595 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001596 }
1597 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001598 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001599 }
1600};
1601
Chris Lattner86102b82005-01-01 16:22:27 +00001602static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001603 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001604 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001605 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001606 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001607
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001608 return IC->InsertNewInstBefore(CastInst::create(
1609 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001610 }
1611
Chris Lattner183b3362004-04-09 19:05:30 +00001612 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001613 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1614 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001615
Chris Lattner183b3362004-04-09 19:05:30 +00001616 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1617 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001618 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1619 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001620 }
1621
1622 Value *Op0 = SO, *Op1 = ConstOperand;
1623 if (!ConstIsRHS)
1624 std::swap(Op0, Op1);
1625 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1627 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001628 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1629 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1630 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001631 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001632 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001633 abort();
1634 }
Chris Lattner86102b82005-01-01 16:22:27 +00001635 return IC->InsertNewInstBefore(New, I);
1636}
1637
1638// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1639// constant as the other operand, try to fold the binary operator into the
1640// select arguments. This also works for Cast instructions, which obviously do
1641// not have a second operand.
1642static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1643 InstCombiner *IC) {
1644 // Don't modify shared select instructions
1645 if (!SI->hasOneUse()) return 0;
1646 Value *TV = SI->getOperand(1);
1647 Value *FV = SI->getOperand(2);
1648
1649 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001650 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001651 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001652
Chris Lattner86102b82005-01-01 16:22:27 +00001653 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1654 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1655
1656 return new SelectInst(SI->getCondition(), SelectTrueVal,
1657 SelectFalseVal);
1658 }
1659 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001660}
1661
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001662
1663/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1664/// node as operand #0, see if we can fold the instruction into the PHI (which
1665/// is only possible if all operands to the PHI are constants).
1666Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1667 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001668 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001669 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001670
Chris Lattner04689872006-09-09 22:02:56 +00001671 // Check to see if all of the operands of the PHI are constants. If there is
1672 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001673 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001674 BasicBlock *NonConstBB = 0;
1675 for (unsigned i = 0; i != NumPHIValues; ++i)
1676 if (!isa<Constant>(PN->getIncomingValue(i))) {
1677 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001678 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001679 NonConstBB = PN->getIncomingBlock(i);
1680
1681 // If the incoming non-constant value is in I's block, we have an infinite
1682 // loop.
1683 if (NonConstBB == I.getParent())
1684 return 0;
1685 }
1686
1687 // If there is exactly one non-constant value, we can insert a copy of the
1688 // operation in that block. However, if this is a critical edge, we would be
1689 // inserting the computation one some other paths (e.g. inside a loop). Only
1690 // do this if the pred block is unconditionally branching into the phi block.
1691 if (NonConstBB) {
1692 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1693 if (!BI || !BI->isUnconditional()) return 0;
1694 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001695
1696 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001697 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001698 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001699 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001700 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001701
1702 // Next, add all of the operands to the PHI.
1703 if (I.getNumOperands() == 2) {
1704 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001705 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001706 Value *InV;
1707 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001708 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1709 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1710 else
1711 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001712 } else {
1713 assert(PN->getIncomingBlock(i) == NonConstBB);
1714 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1715 InV = BinaryOperator::create(BO->getOpcode(),
1716 PN->getIncomingValue(i), C, "phitmp",
1717 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001718 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1719 InV = CmpInst::create(CI->getOpcode(),
1720 CI->getPredicate(),
1721 PN->getIncomingValue(i), C, "phitmp",
1722 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001723 else
1724 assert(0 && "Unknown binop!");
1725
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001726 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001727 }
1728 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001729 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001730 } else {
1731 CastInst *CI = cast<CastInst>(&I);
1732 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001733 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001734 Value *InV;
1735 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001736 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001737 } else {
1738 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001739 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1740 I.getType(), "phitmp",
1741 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001742 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001743 }
1744 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001745 }
1746 }
1747 return ReplaceInstUsesWith(I, NewPN);
1748}
1749
Chris Lattner113f4f42002-06-25 16:13:24 +00001750Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001751 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001752 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001753
Chris Lattnercf4a9962004-04-10 22:01:55 +00001754 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001755 // X + undef -> undef
1756 if (isa<UndefValue>(RHS))
1757 return ReplaceInstUsesWith(I, RHS);
1758
Chris Lattnercf4a9962004-04-10 22:01:55 +00001759 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001760 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001761 if (RHSC->isNullValue())
1762 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001763 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1764 if (CFP->isExactlyValue(-0.0))
1765 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001766 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001767
Chris Lattnercf4a9962004-04-10 22:01:55 +00001768 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001769 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001770 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001771 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001772 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001773
1774 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1775 // (X & 254)+1 -> (X&254)|1
1776 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001777 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00001778 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001779 KnownZero, KnownOne))
1780 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001781 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001782
1783 if (isa<PHINode>(LHS))
1784 if (Instruction *NV = FoldOpIntoPhi(I))
1785 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001786
Chris Lattner330628a2006-01-06 17:59:59 +00001787 ConstantInt *XorRHS = 0;
1788 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001789 if (isa<ConstantInt>(RHSC) &&
1790 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001791 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1792 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1793 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1794
1795 uint64_t C0080Val = 1ULL << 31;
1796 int64_t CFF80Val = -C0080Val;
1797 unsigned Size = 32;
1798 do {
1799 if (TySizeBits > Size) {
1800 bool Found = false;
1801 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1802 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1803 if (RHSSExt == CFF80Val) {
1804 if (XorRHS->getZExtValue() == C0080Val)
1805 Found = true;
1806 } else if (RHSZExt == C0080Val) {
1807 if (XorRHS->getSExtValue() == CFF80Val)
1808 Found = true;
1809 }
1810 if (Found) {
1811 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001812 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001813 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00001814 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001815 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001816 Size = 0; // Not a sign ext, but can't be any others either.
1817 goto FoundSExt;
1818 }
1819 }
1820 Size >>= 1;
1821 C0080Val >>= Size;
1822 CFF80Val >>= Size;
1823 } while (Size >= 8);
1824
1825FoundSExt:
1826 const Type *MiddleType = 0;
1827 switch (Size) {
1828 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001829 case 32: MiddleType = Type::Int32Ty; break;
1830 case 16: MiddleType = Type::Int16Ty; break;
1831 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001832 }
1833 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001834 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001835 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001836 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001837 }
1838 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001839 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001840
Chris Lattnerb8b97502003-08-13 19:01:45 +00001841 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001842 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001843 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001844
1845 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1846 if (RHSI->getOpcode() == Instruction::Sub)
1847 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1848 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1849 }
1850 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1851 if (LHSI->getOpcode() == Instruction::Sub)
1852 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1853 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1854 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001855 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001856
Chris Lattner147e9752002-05-08 22:46:53 +00001857 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001858 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001859 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001860
1861 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001862 if (!isa<Constant>(RHS))
1863 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001864 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001865
Misha Brukmanb1c93172005-04-21 23:48:37 +00001866
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001867 ConstantInt *C2;
1868 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1869 if (X == RHS) // X*C + X --> X * (C+1)
1870 return BinaryOperator::createMul(RHS, AddOne(C2));
1871
1872 // X*C1 + X*C2 --> X * (C1+C2)
1873 ConstantInt *C1;
1874 if (X == dyn_castFoldableMul(RHS, C1))
1875 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001876 }
1877
1878 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001879 if (dyn_castFoldableMul(RHS, C2) == LHS)
1880 return BinaryOperator::createMul(LHS, AddOne(C2));
1881
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001882 // X + ~X --> -1 since ~X = -X-1
1883 if (dyn_castNotVal(LHS) == RHS ||
1884 dyn_castNotVal(RHS) == LHS)
1885 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1886
Chris Lattner57c8d992003-02-18 19:57:07 +00001887
Chris Lattnerb8b97502003-08-13 19:01:45 +00001888 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001889 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001890 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1891 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001892
Chris Lattnerb9cde762003-10-02 15:11:26 +00001893 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001894 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001895 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1896 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1897 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001898 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001899
Chris Lattnerbff91d92004-10-08 05:07:56 +00001900 // (X & FF00) + xx00 -> (X+xx00) & FF00
1901 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1902 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1903 if (Anded == CRHS) {
1904 // See if all bits from the first bit set in the Add RHS up are included
1905 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001906 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001907
1908 // Form a mask of all bits from the lowest bit added through the top.
1909 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001910 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001911
1912 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001913 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001914
Chris Lattnerbff91d92004-10-08 05:07:56 +00001915 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1916 // Okay, the xform is safe. Insert the new add pronto.
1917 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1918 LHS->getName()), I);
1919 return BinaryOperator::createAnd(NewAdd, C2);
1920 }
1921 }
1922 }
1923
Chris Lattnerd4252a72004-07-30 07:50:03 +00001924 // Try to fold constant add into select arguments.
1925 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001926 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001927 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001928 }
1929
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001930 // add (cast *A to intptrtype) B ->
1931 // cast (GEP (cast *A to sbyte*) B) ->
1932 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001933 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001934 CastInst *CI = dyn_cast<CastInst>(LHS);
1935 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001936 if (!CI) {
1937 CI = dyn_cast<CastInst>(RHS);
1938 Other = LHS;
1939 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001940 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001941 (CI->getType()->getPrimitiveSizeInBits() ==
1942 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001943 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001944 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001945 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001946 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001947 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001948 }
1949 }
1950
Chris Lattner113f4f42002-06-25 16:13:24 +00001951 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001952}
1953
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001954// isSignBit - Return true if the value represented by the constant only has the
1955// highest order bit set.
1956static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001957 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001958 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001959}
1960
Chris Lattner113f4f42002-06-25 16:13:24 +00001961Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001963
Chris Lattnere6794492002-08-12 21:17:25 +00001964 if (Op0 == Op1) // sub X, X -> 0
1965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001966
Chris Lattnere6794492002-08-12 21:17:25 +00001967 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001968 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001969 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001970
Chris Lattner81a7a232004-10-16 18:11:37 +00001971 if (isa<UndefValue>(Op0))
1972 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1973 if (isa<UndefValue>(Op1))
1974 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1975
Chris Lattner8f2f5982003-11-05 01:06:05 +00001976 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1977 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001978 if (C->isAllOnesValue())
1979 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001980
Chris Lattner8f2f5982003-11-05 01:06:05 +00001981 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001982 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001983 if (match(Op1, m_Not(m_Value(X))))
1984 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001985 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001986 // -(X >>u 31) -> (X >>s 31)
1987 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001988 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00001989 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001990 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001991 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001992 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001993 if (CU->getZExtValue() ==
1994 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001995 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00001996 return BinaryOperator::create(Instruction::AShr,
1997 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001998 }
1999 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002000 }
2001 else if (SI->getOpcode() == Instruction::AShr) {
2002 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2003 // Check to see if we are shifting out everything but the sign bit.
2004 if (CU->getZExtValue() ==
2005 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002006 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002007 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002008 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002009 }
2010 }
2011 }
Chris Lattner022167f2004-03-13 00:11:49 +00002012 }
Chris Lattner183b3362004-04-09 19:05:30 +00002013
2014 // Try to fold constant sub into select arguments.
2015 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002016 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002017 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002018
2019 if (isa<PHINode>(Op0))
2020 if (Instruction *NV = FoldOpIntoPhi(I))
2021 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002022 }
2023
Chris Lattnera9be4492005-04-07 16:15:25 +00002024 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2025 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002026 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002027 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002028 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002029 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002030 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002031 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2032 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2033 // C1-(X+C2) --> (C1-C2)-X
2034 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2035 Op1I->getOperand(0));
2036 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002037 }
2038
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002039 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002040 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2041 // is not used by anyone else...
2042 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002043 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002044 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002045 // Swap the two operands of the subexpr...
2046 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2047 Op1I->setOperand(0, IIOp1);
2048 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002049
Chris Lattner3082c5a2003-02-18 19:28:33 +00002050 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002051 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002052 }
2053
2054 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2055 //
2056 if (Op1I->getOpcode() == Instruction::And &&
2057 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2058 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2059
Chris Lattner396dbfe2004-06-09 05:08:07 +00002060 Value *NewNot =
2061 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002062 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002063 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002064
Reid Spencer3c514952006-10-16 23:08:08 +00002065 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002066 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002067 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002068 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002069 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002070 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002071 ConstantExpr::getNeg(DivRHS));
2072
Chris Lattner57c8d992003-02-18 19:57:07 +00002073 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002074 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002075 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002076 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002077 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002078 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002079 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002080 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002081 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002082
Chris Lattner7a002fe2006-12-02 00:13:08 +00002083 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002084 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2085 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002086 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2087 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2088 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2089 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002090 } else if (Op0I->getOpcode() == Instruction::Sub) {
2091 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2092 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002093 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002094
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002095 ConstantInt *C1;
2096 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2097 if (X == Op1) { // X*C - X --> X * (C-1)
2098 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2099 return BinaryOperator::createMul(Op1, CP1);
2100 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002101
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002102 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2103 if (X == dyn_castFoldableMul(Op1, C2))
2104 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2105 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002106 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002107}
2108
Reid Spencer266e42b2006-12-23 06:05:41 +00002109/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002110/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002111static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2112 switch (pred) {
2113 case ICmpInst::ICMP_SLT:
2114 // True if LHS s< RHS and RHS == 0
2115 return RHS->isNullValue();
2116 case ICmpInst::ICMP_SLE:
2117 // True if LHS s<= RHS and RHS == -1
2118 return RHS->isAllOnesValue();
2119 case ICmpInst::ICMP_UGE:
2120 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2121 return RHS->getZExtValue() == (1ULL <<
2122 (RHS->getType()->getPrimitiveSizeInBits()-1));
2123 case ICmpInst::ICMP_UGT:
2124 // True if LHS u> RHS and RHS == high-bit-mask - 1
2125 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002126 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002127 default:
2128 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002129 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002130}
2131
Chris Lattner113f4f42002-06-25 16:13:24 +00002132Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002133 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002134 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002135
Chris Lattner81a7a232004-10-16 18:11:37 +00002136 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2137 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2138
Chris Lattnere6794492002-08-12 21:17:25 +00002139 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002140 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002142
2143 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002144 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002145 if (SI->getOpcode() == Instruction::Shl)
2146 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002147 return BinaryOperator::createMul(SI->getOperand(0),
2148 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002149
Chris Lattnercce81be2003-09-11 22:24:54 +00002150 if (CI->isNullValue())
2151 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2152 if (CI->equalsInt(1)) // X * 1 == X
2153 return ReplaceInstUsesWith(I, Op0);
2154 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002155 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002156
Reid Spencere0fc4df2006-10-20 07:07:24 +00002157 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002158 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2159 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002160 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002161 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002162 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002163 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002164 if (Op1F->isNullValue())
2165 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002166
Chris Lattner3082c5a2003-02-18 19:28:33 +00002167 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2168 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2169 if (Op1F->getValue() == 1.0)
2170 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2171 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002172
2173 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2174 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2175 isa<ConstantInt>(Op0I->getOperand(1))) {
2176 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2177 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2178 Op1, "tmp");
2179 InsertNewInstBefore(Add, I);
2180 Value *C1C2 = ConstantExpr::getMul(Op1,
2181 cast<Constant>(Op0I->getOperand(1)));
2182 return BinaryOperator::createAdd(Add, C1C2);
2183
2184 }
Chris Lattner183b3362004-04-09 19:05:30 +00002185
2186 // Try to fold constant mul into select arguments.
2187 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002188 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002189 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002190
2191 if (isa<PHINode>(Op0))
2192 if (Instruction *NV = FoldOpIntoPhi(I))
2193 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002194 }
2195
Chris Lattner934a64cf2003-03-10 23:23:04 +00002196 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2197 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002198 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002199
Chris Lattner2635b522004-02-23 05:39:21 +00002200 // If one of the operands of the multiply is a cast from a boolean value, then
2201 // we know the bool is either zero or one, so this is a 'masking' multiply.
2202 // See if we can simplify things based on how the boolean was originally
2203 // formed.
2204 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002205 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002206 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002207 BoolCast = CI;
2208 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002209 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002210 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002211 BoolCast = CI;
2212 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002213 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002214 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2215 const Type *SCOpTy = SCIOp0->getType();
2216
Reid Spencer266e42b2006-12-23 06:05:41 +00002217 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002218 // multiply into a shift/and combination.
2219 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002220 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002221 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002222 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002223 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002224 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002225 InsertNewInstBefore(
2226 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002227 BoolCast->getOperand(0)->getName()+
2228 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002229
2230 // If the multiply type is not the same as the source type, sign extend
2231 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002232 if (I.getType() != V->getType()) {
2233 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2234 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2235 Instruction::CastOps opcode =
2236 (SrcBits == DstBits ? Instruction::BitCast :
2237 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2238 V = InsertCastBefore(opcode, V, I.getType(), I);
2239 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002240
Chris Lattner2635b522004-02-23 05:39:21 +00002241 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002242 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002243 }
2244 }
2245 }
2246
Chris Lattner113f4f42002-06-25 16:13:24 +00002247 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002248}
2249
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002250/// This function implements the transforms on div instructions that work
2251/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2252/// used by the visitors to those instructions.
2253/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002254Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002256
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002257 // undef / X -> 0
2258 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002259 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002260
2261 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002262 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002263 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002264
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002265 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002266 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2267 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002268 // same basic block, then we replace the select with Y, and the condition
2269 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002270 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002272 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2273 if (ST->isNullValue()) {
2274 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2275 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002276 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002277 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2278 I.setOperand(1, SI->getOperand(2));
2279 else
2280 UpdateValueUsesWith(SI, SI->getOperand(2));
2281 return &I;
2282 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002283
Chris Lattnerd79dc792006-09-09 20:26:32 +00002284 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2285 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2286 if (ST->isNullValue()) {
2287 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2288 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002289 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002290 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2291 I.setOperand(1, SI->getOperand(1));
2292 else
2293 UpdateValueUsesWith(SI, SI->getOperand(1));
2294 return &I;
2295 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002296 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002297
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002298 return 0;
2299}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002300
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002301/// This function implements the transforms common to both integer division
2302/// instructions (udiv and sdiv). It is called by the visitors to those integer
2303/// division instructions.
2304/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002305Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002306 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2307
2308 if (Instruction *Common = commonDivTransforms(I))
2309 return Common;
2310
2311 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2312 // div X, 1 == X
2313 if (RHS->equalsInt(1))
2314 return ReplaceInstUsesWith(I, Op0);
2315
2316 // (X / C1) / C2 -> X / (C1*C2)
2317 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2318 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2319 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2320 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2321 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002322 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002323
2324 if (!RHS->isNullValue()) { // avoid X udiv 0
2325 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2326 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2327 return R;
2328 if (isa<PHINode>(Op0))
2329 if (Instruction *NV = FoldOpIntoPhi(I))
2330 return NV;
2331 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002332 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002333
Chris Lattner3082c5a2003-02-18 19:28:33 +00002334 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002335 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002336 if (LHS->equalsInt(0))
2337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2338
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002339 return 0;
2340}
2341
2342Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2344
2345 // Handle the integer div common cases
2346 if (Instruction *Common = commonIDivTransforms(I))
2347 return Common;
2348
2349 // X udiv C^2 -> X >> C
2350 // Check to see if this is an unsigned division with an exact power of 2,
2351 // if so, convert to a right shift.
2352 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2353 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2354 if (isPowerOf2_64(Val)) {
2355 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002356 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002357 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002358 }
2359 }
2360
2361 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002362 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002363 if (RHSI->getOpcode() == Instruction::Shl &&
2364 isa<ConstantInt>(RHSI->getOperand(0))) {
2365 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2366 if (isPowerOf2_64(C1)) {
2367 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002368 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002370 Constant *C2V = ConstantInt::get(NTy, C2);
2371 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002372 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002373 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002374 }
2375 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002376 }
2377
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002378 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2379 // where C1&C2 are powers of two.
2380 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2381 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2382 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2383 if (!STO->isNullValue() && !STO->isNullValue()) {
2384 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2385 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2386 // Compute the shift amounts
2387 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002388 // Construct the "on true" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002389 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002390 Instruction *TSI = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002391 Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002392 TSI = InsertNewInstBefore(TSI, I);
2393
2394 // Construct the "on false" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002395 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002396 Instruction *FSI = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002397 Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002398 FSI = InsertNewInstBefore(FSI, I);
2399
2400 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002401 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002402 }
2403 }
2404 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002405 return 0;
2406}
2407
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002408Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2410
2411 // Handle the integer div common cases
2412 if (Instruction *Common = commonIDivTransforms(I))
2413 return Common;
2414
2415 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2416 // sdiv X, -1 == -X
2417 if (RHS->isAllOnesValue())
2418 return BinaryOperator::createNeg(Op0);
2419
2420 // -X/C -> X/-C
2421 if (Value *LHSNeg = dyn_castNegVal(Op0))
2422 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2423 }
2424
2425 // If the sign bits of both operands are zero (i.e. we can prove they are
2426 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002427 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002428 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2429 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2430 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2431 }
2432 }
2433
2434 return 0;
2435}
2436
2437Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2438 return commonDivTransforms(I);
2439}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002440
Chris Lattner85dda9a2006-03-02 06:50:58 +00002441/// GetFactor - If we can prove that the specified value is at least a multiple
2442/// of some factor, return that factor.
2443static Constant *GetFactor(Value *V) {
2444 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2445 return CI;
2446
2447 // Unless we can be tricky, we know this is a multiple of 1.
2448 Constant *Result = ConstantInt::get(V->getType(), 1);
2449
2450 Instruction *I = dyn_cast<Instruction>(V);
2451 if (!I) return Result;
2452
2453 if (I->getOpcode() == Instruction::Mul) {
2454 // Handle multiplies by a constant, etc.
2455 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2456 GetFactor(I->getOperand(1)));
2457 } else if (I->getOpcode() == Instruction::Shl) {
2458 // (X<<C) -> X * (1 << C)
2459 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2460 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2461 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2462 }
2463 } else if (I->getOpcode() == Instruction::And) {
2464 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2465 // X & 0xFFF0 is known to be a multiple of 16.
2466 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2467 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2468 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002469 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002470 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002471 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002472 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002473 if (!CI->isIntegerCast())
2474 return Result;
2475 Value *Op = CI->getOperand(0);
2476 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002477 }
2478 return Result;
2479}
2480
Reid Spencer7eb55b32006-11-02 01:53:59 +00002481/// This function implements the transforms on rem instructions that work
2482/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2483/// is used by the visitors to those instructions.
2484/// @brief Transforms common to all three rem instructions
2485Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002486 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002487
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002488 // 0 % X == 0, we don't need to preserve faults!
2489 if (Constant *LHS = dyn_cast<Constant>(Op0))
2490 if (LHS->isNullValue())
2491 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2492
2493 if (isa<UndefValue>(Op0)) // undef % X -> 0
2494 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2495 if (isa<UndefValue>(Op1))
2496 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002497
2498 // Handle cases involving: rem X, (select Cond, Y, Z)
2499 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2500 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2501 // the same basic block, then we replace the select with Y, and the
2502 // condition of the select with false (if the cond value is in the same
2503 // BB). If the select has uses other than the div, this allows them to be
2504 // simplified also.
2505 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2506 if (ST->isNullValue()) {
2507 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2508 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002509 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002510 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2511 I.setOperand(1, SI->getOperand(2));
2512 else
2513 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002514 return &I;
2515 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002516 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2517 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2518 if (ST->isNullValue()) {
2519 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2520 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002521 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002522 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2523 I.setOperand(1, SI->getOperand(1));
2524 else
2525 UpdateValueUsesWith(SI, SI->getOperand(1));
2526 return &I;
2527 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002528 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002529
Reid Spencer7eb55b32006-11-02 01:53:59 +00002530 return 0;
2531}
2532
2533/// This function implements the transforms common to both integer remainder
2534/// instructions (urem and srem). It is called by the visitors to those integer
2535/// remainder instructions.
2536/// @brief Common integer remainder transforms
2537Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2539
2540 if (Instruction *common = commonRemTransforms(I))
2541 return common;
2542
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002544 // X % 0 == undef, we don't need to preserve faults!
2545 if (RHS->equalsInt(0))
2546 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2547
Chris Lattner3082c5a2003-02-18 19:28:33 +00002548 if (RHS->equalsInt(1)) // X % 1 == 0
2549 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2550
Chris Lattnerb70f1412006-02-28 05:49:21 +00002551 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2552 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2553 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2554 return R;
2555 } else if (isa<PHINode>(Op0I)) {
2556 if (Instruction *NV = FoldOpIntoPhi(I))
2557 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002558 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002559 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2560 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002561 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002562 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002563 }
2564
Reid Spencer7eb55b32006-11-02 01:53:59 +00002565 return 0;
2566}
2567
2568Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2570
2571 if (Instruction *common = commonIRemTransforms(I))
2572 return common;
2573
2574 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2575 // X urem C^2 -> X and C
2576 // Check to see if this is an unsigned remainder with an exact power of 2,
2577 // if so, convert to a bitwise and.
2578 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2579 if (isPowerOf2_64(C->getZExtValue()))
2580 return BinaryOperator::createAnd(Op0, SubOne(C));
2581 }
2582
Chris Lattner2e90b732006-02-05 07:54:04 +00002583 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002584 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2585 if (RHSI->getOpcode() == Instruction::Shl &&
2586 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002587 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002588 if (isPowerOf2_64(C1)) {
2589 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2590 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2591 "tmp"), I);
2592 return BinaryOperator::createAnd(Op0, Add);
2593 }
2594 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002595 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002596
Reid Spencer7eb55b32006-11-02 01:53:59 +00002597 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2598 // where C1&C2 are powers of two.
2599 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2600 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2601 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2602 // STO == 0 and SFO == 0 handled above.
2603 if (isPowerOf2_64(STO->getZExtValue()) &&
2604 isPowerOf2_64(SFO->getZExtValue())) {
2605 Value *TrueAnd = InsertNewInstBefore(
2606 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2607 Value *FalseAnd = InsertNewInstBefore(
2608 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2609 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2610 }
2611 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002612 }
2613
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002614 return 0;
2615}
2616
Reid Spencer7eb55b32006-11-02 01:53:59 +00002617Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2618 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2619
2620 if (Instruction *common = commonIRemTransforms(I))
2621 return common;
2622
2623 if (Value *RHSNeg = dyn_castNegVal(Op1))
2624 if (!isa<ConstantInt>(RHSNeg) ||
2625 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2626 // X % -Y -> X % Y
2627 AddUsesToWorkList(I);
2628 I.setOperand(1, RHSNeg);
2629 return &I;
2630 }
2631
2632 // If the top bits of both operands are zero (i.e. we can prove they are
2633 // unsigned inputs), turn this into a urem.
2634 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2635 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2636 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2637 return BinaryOperator::createURem(Op0, Op1, I.getName());
2638 }
2639
2640 return 0;
2641}
2642
2643Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002644 return commonRemTransforms(I);
2645}
2646
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002647// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002648static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2649 if (isSigned) {
2650 // Calculate 0111111111..11111
2651 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2652 int64_t Val = INT64_MAX; // All ones
2653 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2654 return C->getSExtValue() == Val-1;
2655 }
Reid Spencera94d3942007-01-19 21:13:56 +00002656 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002657}
2658
2659// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002660static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2661 if (isSigned) {
2662 // Calculate 1111111111000000000000
2663 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2664 int64_t Val = -1; // All ones
2665 Val <<= TypeBits-1; // Shift over to the right spot
2666 return C->getSExtValue() == Val+1;
2667 }
2668 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002669}
2670
Chris Lattner35167c32004-06-09 07:59:58 +00002671// isOneBitSet - Return true if there is exactly one bit set in the specified
2672// constant.
2673static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002674 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002675 return V && (V & (V-1)) == 0;
2676}
2677
Chris Lattner8fc5af42004-09-23 21:46:38 +00002678#if 0 // Currently unused
2679// isLowOnes - Return true if the constant is of the form 0+1+.
2680static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002681 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002682
2683 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002684 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002685
2686 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2687 return U && V && (U & V) == 0;
2688}
2689#endif
2690
2691// isHighOnes - Return true if the constant is of the form 1+0+.
2692// This is the same as lowones(~X).
2693static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002694 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002695 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002696
2697 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002698 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002699
2700 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2701 return U && V && (U & V) == 0;
2702}
2703
Reid Spencer266e42b2006-12-23 06:05:41 +00002704/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002705/// are carefully arranged to allow folding of expressions such as:
2706///
2707/// (A < B) | (A > B) --> (A != B)
2708///
Reid Spencer266e42b2006-12-23 06:05:41 +00002709/// Note that this is only valid if the first and second predicates have the
2710/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002711///
Reid Spencer266e42b2006-12-23 06:05:41 +00002712/// Three bits are used to represent the condition, as follows:
2713/// 0 A > B
2714/// 1 A == B
2715/// 2 A < B
2716///
2717/// <=> Value Definition
2718/// 000 0 Always false
2719/// 001 1 A > B
2720/// 010 2 A == B
2721/// 011 3 A >= B
2722/// 100 4 A < B
2723/// 101 5 A != B
2724/// 110 6 A <= B
2725/// 111 7 Always true
2726///
2727static unsigned getICmpCode(const ICmpInst *ICI) {
2728 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002729 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002730 case ICmpInst::ICMP_UGT: return 1; // 001
2731 case ICmpInst::ICMP_SGT: return 1; // 001
2732 case ICmpInst::ICMP_EQ: return 2; // 010
2733 case ICmpInst::ICMP_UGE: return 3; // 011
2734 case ICmpInst::ICMP_SGE: return 3; // 011
2735 case ICmpInst::ICMP_ULT: return 4; // 100
2736 case ICmpInst::ICMP_SLT: return 4; // 100
2737 case ICmpInst::ICMP_NE: return 5; // 101
2738 case ICmpInst::ICMP_ULE: return 6; // 110
2739 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002740 // True -> 7
2741 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002742 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002743 return 0;
2744 }
2745}
2746
Reid Spencer266e42b2006-12-23 06:05:41 +00002747/// getICmpValue - This is the complement of getICmpCode, which turns an
2748/// opcode and two operands into either a constant true or false, or a brand
2749/// new /// ICmp instruction. The sign is passed in to determine which kind
2750/// of predicate to use in new icmp instructions.
2751static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2752 switch (code) {
2753 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002754 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002755 case 1:
2756 if (sign)
2757 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2758 else
2759 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2760 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2761 case 3:
2762 if (sign)
2763 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2764 else
2765 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2766 case 4:
2767 if (sign)
2768 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2769 else
2770 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2771 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2772 case 6:
2773 if (sign)
2774 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2775 else
2776 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002777 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002778 }
2779}
2780
Reid Spencer266e42b2006-12-23 06:05:41 +00002781static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2782 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2783 (ICmpInst::isSignedPredicate(p1) &&
2784 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2785 (ICmpInst::isSignedPredicate(p2) &&
2786 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2787}
2788
2789namespace {
2790// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2791struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002792 InstCombiner &IC;
2793 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002794 ICmpInst::Predicate pred;
2795 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2796 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2797 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002798 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002799 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2800 if (PredicatesFoldable(pred, ICI->getPredicate()))
2801 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2802 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002803 return false;
2804 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002805 Instruction *apply(Instruction &Log) const {
2806 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2807 if (ICI->getOperand(0) != LHS) {
2808 assert(ICI->getOperand(1) == LHS);
2809 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002810 }
2811
Reid Spencer266e42b2006-12-23 06:05:41 +00002812 unsigned LHSCode = getICmpCode(ICI);
2813 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002814 unsigned Code;
2815 switch (Log.getOpcode()) {
2816 case Instruction::And: Code = LHSCode & RHSCode; break;
2817 case Instruction::Or: Code = LHSCode | RHSCode; break;
2818 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002819 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002820 }
2821
Reid Spencer266e42b2006-12-23 06:05:41 +00002822 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002823 if (Instruction *I = dyn_cast<Instruction>(RV))
2824 return I;
2825 // Otherwise, it's a constant boolean value...
2826 return IC.ReplaceInstUsesWith(Log, RV);
2827 }
2828};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002829} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002830
Chris Lattnerba1cb382003-09-19 17:17:26 +00002831// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2832// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002833// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002834Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002835 ConstantInt *OpRHS,
2836 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002837 BinaryOperator &TheAnd) {
2838 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002839 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002840 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002841 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002842
Chris Lattnerba1cb382003-09-19 17:17:26 +00002843 switch (Op->getOpcode()) {
2844 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002845 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002846 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002847 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002848 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002849 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002850 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002851 }
2852 break;
2853 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002854 if (Together == AndRHS) // (X | C) & C --> C
2855 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002856
Chris Lattner86102b82005-01-01 16:22:27 +00002857 if (Op->hasOneUse() && Together != OpRHS) {
2858 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002859 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002860 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002861 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002862 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002863 }
2864 break;
2865 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002866 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002867 // Adding a one to a single bit bit-field should be turned into an XOR
2868 // of the bit. First thing to check is to see if this AND is with a
2869 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002870 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002871
2872 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00002873 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002874
2875 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002876 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002877 // Ok, at this point, we know that we are masking the result of the
2878 // ADD down to exactly one bit. If the constant we are adding has
2879 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002880 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002881
Chris Lattnerba1cb382003-09-19 17:17:26 +00002882 // Check to see if any bits below the one bit set in AndRHSV are set.
2883 if ((AddRHS & (AndRHSV-1)) == 0) {
2884 // If not, the only thing that can effect the output of the AND is
2885 // the bit specified by AndRHSV. If that bit is set, the effect of
2886 // the XOR is to toggle the bit. If it is clear, then the ADD has
2887 // no effect.
2888 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2889 TheAnd.setOperand(0, X);
2890 return &TheAnd;
2891 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002892 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002893 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002894 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002895 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002896 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002897 }
2898 }
2899 }
2900 }
2901 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002902
2903 case Instruction::Shl: {
2904 // We know that the AND will not produce any of the bits shifted in, so if
2905 // the anded constant includes them, clear them now!
2906 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002907 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002908 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2909 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002910
Chris Lattner7e794272004-09-24 15:21:34 +00002911 if (CI == ShlMask) { // Masking out bits that the shift already masks
2912 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2913 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002914 TheAnd.setOperand(1, CI);
2915 return &TheAnd;
2916 }
2917 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002918 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002919 case Instruction::LShr:
2920 {
Chris Lattner2da29172003-09-19 19:05:02 +00002921 // We know that the AND will not produce any of the bits shifted in, so if
2922 // the anded constant includes them, clear them now! This only applies to
2923 // unsigned shifts, because a signed shr may bring in set bits!
2924 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002925 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002926 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2927 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002928
Reid Spencerfdff9382006-11-08 06:47:33 +00002929 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2930 return ReplaceInstUsesWith(TheAnd, Op);
2931 } else if (CI != AndRHS) {
2932 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2933 return &TheAnd;
2934 }
2935 break;
2936 }
2937 case Instruction::AShr:
2938 // Signed shr.
2939 // See if this is shifting in some sign extension, then masking it out
2940 // with an and.
2941 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002942 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002943 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002944 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2945 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002946 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002947 // Make the argument unsigned.
2948 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00002949 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00002950 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00002951 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00002952 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002953 }
Chris Lattner2da29172003-09-19 19:05:02 +00002954 }
2955 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002956 }
2957 return 0;
2958}
2959
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002960
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2962/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002963/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2964/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002965/// insert new instructions.
2966Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002967 bool isSigned, bool Inside,
2968 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002969 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002970 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002971 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002972
Chris Lattner6862fbd2004-09-29 17:40:11 +00002973 if (Inside) {
2974 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002975 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002976
Reid Spencer266e42b2006-12-23 06:05:41 +00002977 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002978 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002979 ICmpInst::Predicate pred = (isSigned ?
2980 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2981 return new ICmpInst(pred, V, Hi);
2982 }
2983
2984 // Emit V-Lo <u Hi-Lo
2985 Constant *NegLo = ConstantExpr::getNeg(Lo);
2986 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002987 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002988 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2989 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002990 }
2991
2992 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002993 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002994
Reid Spencer266e42b2006-12-23 06:05:41 +00002995 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002996 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002997 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002998 ICmpInst::Predicate pred = (isSigned ?
2999 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3000 return new ICmpInst(pred, V, Hi);
3001 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003002
Reid Spencer266e42b2006-12-23 06:05:41 +00003003 // Emit V-Lo > Hi-1-Lo
3004 Constant *NegLo = ConstantExpr::getNeg(Lo);
3005 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003006 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003007 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3008 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003009}
3010
Chris Lattnerb4b25302005-09-18 07:22:02 +00003011// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3012// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3013// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3014// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003015static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003016 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003017 if (!isShiftedMask_64(V)) return false;
3018
3019 // look for the first zero bit after the run of ones
3020 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3021 // look for the first non-zero bit
3022 ME = 64-CountLeadingZeros_64(V);
3023 return true;
3024}
3025
3026
3027
3028/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3029/// where isSub determines whether the operator is a sub. If we can fold one of
3030/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003031///
3032/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3033/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3034/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3035///
3036/// return (A +/- B).
3037///
3038Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003039 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003040 Instruction &I) {
3041 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3042 if (!LHSI || LHSI->getNumOperands() != 2 ||
3043 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3044
3045 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3046
3047 switch (LHSI->getOpcode()) {
3048 default: return 0;
3049 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003050 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3051 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003052 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003053 break;
3054
3055 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3056 // part, we don't need any explicit masks to take them out of A. If that
3057 // is all N is, ignore it.
3058 unsigned MB, ME;
3059 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003060 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003061 Mask >>= 64-MB+1;
3062 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003063 break;
3064 }
3065 }
Chris Lattneraf517572005-09-18 04:24:45 +00003066 return 0;
3067 case Instruction::Or:
3068 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003069 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003070 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003071 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003072 break;
3073 return 0;
3074 }
3075
3076 Instruction *New;
3077 if (isSub)
3078 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3079 else
3080 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3081 return InsertNewInstBefore(New, I);
3082}
3083
Chris Lattner113f4f42002-06-25 16:13:24 +00003084Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003085 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003086 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003087
Chris Lattner81a7a232004-10-16 18:11:37 +00003088 if (isa<UndefValue>(Op1)) // X & undef -> 0
3089 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3090
Chris Lattner86102b82005-01-01 16:22:27 +00003091 // and X, X = X
3092 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003093 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003094
Chris Lattner5b2edb12006-02-12 08:02:11 +00003095 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003096 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003097 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003098 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003099 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003100 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003101 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003102 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003103 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003104 if (CP->isAllOnesValue())
3105 return ReplaceInstUsesWith(I, I.getOperand(0));
3106 }
3107 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003108
Zhou Sheng75b871f2007-01-11 12:24:14 +00003109 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003110 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003111 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003112 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003113
Chris Lattnerba1cb382003-09-19 17:17:26 +00003114 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003115 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003116 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003117 Value *Op0LHS = Op0I->getOperand(0);
3118 Value *Op0RHS = Op0I->getOperand(1);
3119 switch (Op0I->getOpcode()) {
3120 case Instruction::Xor:
3121 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003122 // If the mask is only needed on one incoming arm, push it up.
3123 if (Op0I->hasOneUse()) {
3124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3125 // Not masking anything out for the LHS, move to RHS.
3126 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3127 Op0RHS->getName()+".masked");
3128 InsertNewInstBefore(NewRHS, I);
3129 return BinaryOperator::create(
3130 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003131 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003132 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003133 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3134 // Not masking anything out for the RHS, move to LHS.
3135 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3136 Op0LHS->getName()+".masked");
3137 InsertNewInstBefore(NewLHS, I);
3138 return BinaryOperator::create(
3139 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3140 }
3141 }
3142
Chris Lattner86102b82005-01-01 16:22:27 +00003143 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003144 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003145 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3146 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3147 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3149 return BinaryOperator::createAnd(V, AndRHS);
3150 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3151 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003152 break;
3153
3154 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003155 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3156 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3157 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3159 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003160 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003161 }
3162
Chris Lattner16464b32003-07-23 19:25:52 +00003163 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003164 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003165 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003166 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003167 // If this is an integer truncation or change from signed-to-unsigned, and
3168 // if the source is an and/or with immediate, transform it. This
3169 // frequently occurs for bitfield accesses.
3170 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003171 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003172 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003173 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003174 if (CastOp->getOpcode() == Instruction::And) {
3175 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003176 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3177 // This will fold the two constants together, which may allow
3178 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003179 Instruction *NewCast = CastInst::createTruncOrBitCast(
3180 CastOp->getOperand(0), I.getType(),
3181 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003182 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003183 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003184 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003185 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003186 return BinaryOperator::createAnd(NewCast, C3);
3187 } else if (CastOp->getOpcode() == Instruction::Or) {
3188 // Change: and (cast (or X, C1) to T), C2
3189 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003190 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003191 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3192 return ReplaceInstUsesWith(I, AndRHS);
3193 }
3194 }
Chris Lattner33217db2003-07-23 19:36:21 +00003195 }
Chris Lattner183b3362004-04-09 19:05:30 +00003196
3197 // Try to fold constant and into select arguments.
3198 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003200 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003201 if (isa<PHINode>(Op0))
3202 if (Instruction *NV = FoldOpIntoPhi(I))
3203 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003204 }
3205
Chris Lattnerbb74e222003-03-10 23:06:50 +00003206 Value *Op0NotVal = dyn_castNotVal(Op0);
3207 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003208
Chris Lattner023a4832004-06-18 06:07:51 +00003209 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3210 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3211
Misha Brukman9c003d82004-07-30 12:50:08 +00003212 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003213 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003214 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3215 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003216 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003217 return BinaryOperator::createNot(Or);
3218 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003219
3220 {
3221 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003222 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3223 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3224 return ReplaceInstUsesWith(I, Op1);
3225 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3226 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3227 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003228
3229 if (Op0->hasOneUse() &&
3230 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3231 if (A == Op1) { // (A^B)&A -> A&(A^B)
3232 I.swapOperands(); // Simplify below
3233 std::swap(Op0, Op1);
3234 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3235 cast<BinaryOperator>(Op0)->swapOperands();
3236 I.swapOperands(); // Simplify below
3237 std::swap(Op0, Op1);
3238 }
3239 }
3240 if (Op1->hasOneUse() &&
3241 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3242 if (B == Op0) { // B&(A^B) -> B&(B^A)
3243 cast<BinaryOperator>(Op1)->swapOperands();
3244 std::swap(A, B);
3245 }
3246 if (A == Op0) { // A&(A^B) -> A & ~B
3247 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3248 InsertNewInstBefore(NotB, I);
3249 return BinaryOperator::createAnd(A, NotB);
3250 }
3251 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003252 }
3253
Reid Spencer266e42b2006-12-23 06:05:41 +00003254 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3255 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3256 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003257 return R;
3258
Chris Lattner623826c2004-09-28 21:48:02 +00003259 Value *LHSVal, *RHSVal;
3260 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003261 ICmpInst::Predicate LHSCC, RHSCC;
3262 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3263 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3264 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3265 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3266 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3267 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3268 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3269 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003270 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003271 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3272 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3273 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3274 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003275 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003276 std::swap(LHS, RHS);
3277 std::swap(LHSCst, RHSCst);
3278 std::swap(LHSCC, RHSCC);
3279 }
3280
Reid Spencer266e42b2006-12-23 06:05:41 +00003281 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003282 // comparing a value against two constants and and'ing the result
3283 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003284 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3285 // (from the FoldICmpLogical check above), that the two constants
3286 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003287 assert(LHSCst != RHSCst && "Compares not folded above?");
3288
3289 switch (LHSCC) {
3290 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003291 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003292 switch (RHSCC) {
3293 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003294 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3295 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3296 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003297 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003298 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3299 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3300 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003301 return ReplaceInstUsesWith(I, LHS);
3302 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003303 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003304 switch (RHSCC) {
3305 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003306 case ICmpInst::ICMP_ULT:
3307 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3308 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3309 break; // (X != 13 & X u< 15) -> no change
3310 case ICmpInst::ICMP_SLT:
3311 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3312 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3313 break; // (X != 13 & X s< 15) -> no change
3314 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3315 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3316 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003317 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003318 case ICmpInst::ICMP_NE:
3319 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003320 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3321 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3322 LHSVal->getName()+".off");
3323 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003324 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3325 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003326 }
3327 break; // (X != 13 & X != 15) -> no change
3328 }
3329 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003330 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003331 switch (RHSCC) {
3332 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003333 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3334 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003335 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003336 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3337 break;
3338 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3339 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003340 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003341 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3342 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003343 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003344 break;
3345 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003346 switch (RHSCC) {
3347 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003348 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3349 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003350 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003351 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3352 break;
3353 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3354 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003355 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003356 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3357 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003358 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003359 break;
3360 case ICmpInst::ICMP_UGT:
3361 switch (RHSCC) {
3362 default: assert(0 && "Unknown integer condition code!");
3363 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3364 return ReplaceInstUsesWith(I, LHS);
3365 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3366 return ReplaceInstUsesWith(I, RHS);
3367 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3368 break;
3369 case ICmpInst::ICMP_NE:
3370 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3371 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3372 break; // (X u> 13 & X != 15) -> no change
3373 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3374 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3375 true, I);
3376 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3377 break;
3378 }
3379 break;
3380 case ICmpInst::ICMP_SGT:
3381 switch (RHSCC) {
3382 default: assert(0 && "Unknown integer condition code!");
3383 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3384 return ReplaceInstUsesWith(I, LHS);
3385 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3386 return ReplaceInstUsesWith(I, RHS);
3387 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3388 break;
3389 case ICmpInst::ICMP_NE:
3390 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3391 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3392 break; // (X s> 13 & X != 15) -> no change
3393 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3394 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3395 true, I);
3396 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3397 break;
3398 }
3399 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003400 }
3401 }
3402 }
3403
Chris Lattner3af10532006-05-05 06:39:07 +00003404 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003405 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3406 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3407 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3408 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003409 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003410 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003411 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3412 I.getType(), TD) &&
3413 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3414 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003415 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3416 Op1C->getOperand(0),
3417 I.getName());
3418 InsertNewInstBefore(NewOp, I);
3419 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3420 }
Chris Lattner3af10532006-05-05 06:39:07 +00003421 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003422
3423 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003424 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3425 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3426 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003427 SI0->getOperand(1) == SI1->getOperand(1) &&
3428 (SI0->hasOneUse() || SI1->hasOneUse())) {
3429 Instruction *NewOp =
3430 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3431 SI1->getOperand(0),
3432 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003433 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3434 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003435 }
Chris Lattner3af10532006-05-05 06:39:07 +00003436 }
3437
Chris Lattner113f4f42002-06-25 16:13:24 +00003438 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003439}
3440
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003441/// CollectBSwapParts - Look to see if the specified value defines a single byte
3442/// in the result. If it does, and if the specified byte hasn't been filled in
3443/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003444static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003445 Instruction *I = dyn_cast<Instruction>(V);
3446 if (I == 0) return true;
3447
3448 // If this is an or instruction, it is an inner node of the bswap.
3449 if (I->getOpcode() == Instruction::Or)
3450 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3451 CollectBSwapParts(I->getOperand(1), ByteValues);
3452
3453 // If this is a shift by a constant int, and it is "24", then its operand
3454 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003455 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003456 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003457 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003458 8*(ByteValues.size()-1))
3459 return true;
3460
3461 unsigned DestNo;
3462 if (I->getOpcode() == Instruction::Shl) {
3463 // X << 24 defines the top byte with the lowest of the input bytes.
3464 DestNo = ByteValues.size()-1;
3465 } else {
3466 // X >>u 24 defines the low byte with the highest of the input bytes.
3467 DestNo = 0;
3468 }
3469
3470 // If the destination byte value is already defined, the values are or'd
3471 // together, which isn't a bswap (unless it's an or of the same bits).
3472 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3473 return true;
3474 ByteValues[DestNo] = I->getOperand(0);
3475 return false;
3476 }
3477
3478 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3479 // don't have this.
3480 Value *Shift = 0, *ShiftLHS = 0;
3481 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3482 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3483 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3484 return true;
3485 Instruction *SI = cast<Instruction>(Shift);
3486
3487 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003488 if (ShiftAmt->getZExtValue() & 7 ||
3489 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003490 return true;
3491
3492 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3493 unsigned DestByte;
3494 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003495 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003496 break;
3497 // Unknown mask for bswap.
3498 if (DestByte == ByteValues.size()) return true;
3499
Reid Spencere0fc4df2006-10-20 07:07:24 +00003500 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003501 unsigned SrcByte;
3502 if (SI->getOpcode() == Instruction::Shl)
3503 SrcByte = DestByte - ShiftBytes;
3504 else
3505 SrcByte = DestByte + ShiftBytes;
3506
3507 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3508 if (SrcByte != ByteValues.size()-DestByte-1)
3509 return true;
3510
3511 // If the destination byte value is already defined, the values are or'd
3512 // together, which isn't a bswap (unless it's an or of the same bits).
3513 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3514 return true;
3515 ByteValues[DestByte] = SI->getOperand(0);
3516 return false;
3517}
3518
3519/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3520/// If so, insert the new bswap intrinsic and return it.
3521Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003522 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003523 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003524 return 0;
3525
3526 /// ByteValues - For each byte of the result, we keep track of which value
3527 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003528 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003529 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003530
3531 // Try to find all the pieces corresponding to the bswap.
3532 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3533 CollectBSwapParts(I.getOperand(1), ByteValues))
3534 return 0;
3535
3536 // Check to see if all of the bytes come from the same value.
3537 Value *V = ByteValues[0];
3538 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3539
3540 // Check to make sure that all of the bytes come from the same value.
3541 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3542 if (ByteValues[i] != V)
3543 return 0;
3544
3545 // If they do then *success* we can turn this into a bswap. Figure out what
3546 // bswap to make it into.
3547 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003548 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003549 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003550 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003551 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003552 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003553 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003554 FnName = "llvm.bswap.i64";
3555 else
3556 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003557 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003558 return new CallInst(F, V);
3559}
3560
3561
Chris Lattner113f4f42002-06-25 16:13:24 +00003562Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003563 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003565
Chris Lattner81a7a232004-10-16 18:11:37 +00003566 if (isa<UndefValue>(Op1))
3567 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003568 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003569
Chris Lattner5b2edb12006-02-12 08:02:11 +00003570 // or X, X = X
3571 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003572 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003573
Chris Lattner5b2edb12006-02-12 08:02:11 +00003574 // See if we can simplify any instructions used by the instruction whose sole
3575 // purpose is to compute bits we don't care about.
3576 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003577 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003578 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003579 KnownZero, KnownOne))
3580 return &I;
3581
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003582 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003583 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003584 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003585 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3586 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003587 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003588 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003589 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003590 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3591 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003592
Chris Lattnerd4252a72004-07-30 07:50:03 +00003593 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3594 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003595 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003596 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003597 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003598 return BinaryOperator::createXor(Or,
3599 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003600 }
Chris Lattner183b3362004-04-09 19:05:30 +00003601
3602 // Try to fold constant and into select arguments.
3603 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003604 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003605 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003606 if (isa<PHINode>(Op0))
3607 if (Instruction *NV = FoldOpIntoPhi(I))
3608 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003609 }
3610
Chris Lattner330628a2006-01-06 17:59:59 +00003611 Value *A = 0, *B = 0;
3612 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003613
3614 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3615 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3616 return ReplaceInstUsesWith(I, Op1);
3617 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3618 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3619 return ReplaceInstUsesWith(I, Op0);
3620
Chris Lattnerb7845d62006-07-10 20:25:24 +00003621 // (A | B) | C and A | (B | C) -> bswap if possible.
3622 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003623 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003624 match(Op1, m_Or(m_Value(), m_Value())) ||
3625 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3626 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003627 if (Instruction *BSwap = MatchBSwap(I))
3628 return BSwap;
3629 }
3630
Chris Lattnerb62f5082005-05-09 04:58:36 +00003631 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3632 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003633 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003634 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3635 InsertNewInstBefore(NOr, I);
3636 NOr->takeName(Op0);
3637 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003638 }
3639
3640 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3641 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003642 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003643 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3644 InsertNewInstBefore(NOr, I);
3645 NOr->takeName(Op0);
3646 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003647 }
3648
Chris Lattner15212982005-09-18 03:42:07 +00003649 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003650 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003651 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3652
3653 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3654 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3655
3656
Chris Lattner01f56c62005-09-18 06:02:59 +00003657 // If we have: ((V + N) & C1) | (V & C2)
3658 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3659 // replace with V+N.
3660 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003661 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003662 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003663 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3664 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003665 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003666 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003667 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003668 return ReplaceInstUsesWith(I, A);
3669 }
3670 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003671 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003672 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3673 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003674 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003675 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003676 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003677 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003678 }
3679 }
3680 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003681
3682 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003683 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3684 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3685 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003686 SI0->getOperand(1) == SI1->getOperand(1) &&
3687 (SI0->hasOneUse() || SI1->hasOneUse())) {
3688 Instruction *NewOp =
3689 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3690 SI1->getOperand(0),
3691 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003692 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3693 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003694 }
3695 }
Chris Lattner812aab72003-08-12 19:11:07 +00003696
Chris Lattnerd4252a72004-07-30 07:50:03 +00003697 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3698 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003699 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003700 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003701 } else {
3702 A = 0;
3703 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003704 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003705 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3706 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003707 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003708 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003709
Misha Brukman9c003d82004-07-30 12:50:08 +00003710 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003711 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3712 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3713 I.getName()+".demorgan"), I);
3714 return BinaryOperator::createNot(And);
3715 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003716 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003717
Reid Spencer266e42b2006-12-23 06:05:41 +00003718 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3719 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3720 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003721 return R;
3722
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003723 Value *LHSVal, *RHSVal;
3724 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003725 ICmpInst::Predicate LHSCC, RHSCC;
3726 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3727 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3728 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3729 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3730 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3731 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3732 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3733 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003734 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003735 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3736 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3737 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3738 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003739 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003740 std::swap(LHS, RHS);
3741 std::swap(LHSCst, RHSCst);
3742 std::swap(LHSCC, RHSCC);
3743 }
3744
Reid Spencer266e42b2006-12-23 06:05:41 +00003745 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003746 // comparing a value against two constants and or'ing the result
3747 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003748 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3749 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003750 // equal.
3751 assert(LHSCst != RHSCst && "Compares not folded above?");
3752
3753 switch (LHSCC) {
3754 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003756 switch (RHSCC) {
3757 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003759 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3760 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3761 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3762 LHSVal->getName()+".off");
3763 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003764 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003765 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003766 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003767 break; // (X == 13 | X == 15) -> no change
3768 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3769 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003770 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003771 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3772 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3773 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003774 return ReplaceInstUsesWith(I, RHS);
3775 }
3776 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003778 switch (RHSCC) {
3779 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003780 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3781 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3782 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003783 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003784 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3785 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3786 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003787 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003788 }
3789 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003793 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003794 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003795 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3796 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3797 false, I);
3798 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3799 break;
3800 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3801 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003802 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003803 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3804 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003805 }
3806 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003807 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003808 switch (RHSCC) {
3809 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003810 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3811 break;
3812 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3813 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3814 false, I);
3815 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3816 break;
3817 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3818 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3819 return ReplaceInstUsesWith(I, RHS);
3820 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3821 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003822 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003823 break;
3824 case ICmpInst::ICMP_UGT:
3825 switch (RHSCC) {
3826 default: assert(0 && "Unknown integer condition code!");
3827 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3828 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3829 return ReplaceInstUsesWith(I, LHS);
3830 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3831 break;
3832 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3833 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003834 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003835 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3836 break;
3837 }
3838 break;
3839 case ICmpInst::ICMP_SGT:
3840 switch (RHSCC) {
3841 default: assert(0 && "Unknown integer condition code!");
3842 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3843 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3844 return ReplaceInstUsesWith(I, LHS);
3845 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3846 break;
3847 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3848 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003849 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003850 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3851 break;
3852 }
3853 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003854 }
3855 }
3856 }
Chris Lattner3af10532006-05-05 06:39:07 +00003857
3858 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003859 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003860 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003861 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3862 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003863 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003864 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003865 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3866 I.getType(), TD) &&
3867 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3868 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003869 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3870 Op1C->getOperand(0),
3871 I.getName());
3872 InsertNewInstBefore(NewOp, I);
3873 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3874 }
Chris Lattner3af10532006-05-05 06:39:07 +00003875 }
Chris Lattner3af10532006-05-05 06:39:07 +00003876
Chris Lattner15212982005-09-18 03:42:07 +00003877
Chris Lattner113f4f42002-06-25 16:13:24 +00003878 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003879}
3880
Chris Lattnerc2076352004-02-16 01:20:27 +00003881// XorSelf - Implements: X ^ X --> 0
3882struct XorSelf {
3883 Value *RHS;
3884 XorSelf(Value *rhs) : RHS(rhs) {}
3885 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3886 Instruction *apply(BinaryOperator &Xor) const {
3887 return &Xor;
3888 }
3889};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003890
3891
Chris Lattner113f4f42002-06-25 16:13:24 +00003892Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003893 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003894 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003895
Chris Lattner81a7a232004-10-16 18:11:37 +00003896 if (isa<UndefValue>(Op1))
3897 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3898
Chris Lattnerc2076352004-02-16 01:20:27 +00003899 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3900 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3901 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003902 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003903 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003904
3905 // See if we can simplify any instructions used by the instruction whose sole
3906 // purpose is to compute bits we don't care about.
3907 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003908 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003909 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003910 KnownZero, KnownOne))
3911 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003912
Zhou Sheng75b871f2007-01-11 12:24:14 +00003913 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003914 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3915 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003916 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003917 return new ICmpInst(ICI->getInversePredicate(),
3918 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003919
Reid Spencer266e42b2006-12-23 06:05:41 +00003920 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003921 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003922 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3923 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003924 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3925 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003926 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003927 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003928 }
Chris Lattner023a4832004-06-18 06:07:51 +00003929
3930 // ~(~X & Y) --> (X | ~Y)
3931 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3932 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3933 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3934 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003935 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003936 Op0I->getOperand(1)->getName()+".not");
3937 InsertNewInstBefore(NotY, I);
3938 return BinaryOperator::createOr(Op0NotVal, NotY);
3939 }
3940 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003941
Chris Lattner97638592003-07-23 21:37:07 +00003942 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003943 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003944 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003945 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003946 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3947 return BinaryOperator::createSub(
3948 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003949 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003950 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003951 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003952 } else if (Op0I->getOpcode() == Instruction::Or) {
3953 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3954 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3955 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3956 // Anything in both C1 and C2 is known to be zero, remove it from
3957 // NewRHS.
3958 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3959 NewRHS = ConstantExpr::getAnd(NewRHS,
3960 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00003961 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003962 I.setOperand(0, Op0I->getOperand(0));
3963 I.setOperand(1, NewRHS);
3964 return &I;
3965 }
Chris Lattner97638592003-07-23 21:37:07 +00003966 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003967 }
Chris Lattner183b3362004-04-09 19:05:30 +00003968
3969 // Try to fold constant and into select arguments.
3970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003972 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003973 if (isa<PHINode>(Op0))
3974 if (Instruction *NV = FoldOpIntoPhi(I))
3975 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003976 }
3977
Chris Lattnerbb74e222003-03-10 23:06:50 +00003978 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003979 if (X == Op1)
3980 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003981 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003982
Chris Lattnerbb74e222003-03-10 23:06:50 +00003983 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003984 if (X == Op0)
3985 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003986 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003987
Chris Lattnerdcd07922006-04-01 08:03:55 +00003988 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003989 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003990 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003991 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003992 I.swapOperands();
3993 std::swap(Op0, Op1);
3994 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003995 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003996 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003997 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003998 } else if (Op1I->getOpcode() == Instruction::Xor) {
3999 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4000 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4001 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4002 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004003 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4004 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4005 Op1I->swapOperands();
4006 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4007 I.swapOperands(); // Simplified below.
4008 std::swap(Op0, Op1);
4009 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004010 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004011
Chris Lattnerdcd07922006-04-01 08:03:55 +00004012 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004013 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004014 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004015 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004016 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004017 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4018 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004019 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004020 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004021 } else if (Op0I->getOpcode() == Instruction::Xor) {
4022 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4023 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4024 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4025 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004026 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4027 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4028 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004029 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4030 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004031 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4032 InsertNewInstBefore(N, I);
4033 return BinaryOperator::createAnd(N, Op1);
4034 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004035 }
4036
Reid Spencer266e42b2006-12-23 06:05:41 +00004037 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4038 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4039 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004040 return R;
4041
Chris Lattner3af10532006-05-05 06:39:07 +00004042 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004043 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004044 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004045 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4046 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004047 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004048 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004049 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4050 I.getType(), TD) &&
4051 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4052 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004053 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4054 Op1C->getOperand(0),
4055 I.getName());
4056 InsertNewInstBefore(NewOp, I);
4057 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4058 }
Chris Lattner3af10532006-05-05 06:39:07 +00004059 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004060
4061 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004062 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4063 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4064 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004065 SI0->getOperand(1) == SI1->getOperand(1) &&
4066 (SI0->hasOneUse() || SI1->hasOneUse())) {
4067 Instruction *NewOp =
4068 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4069 SI1->getOperand(0),
4070 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004071 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4072 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004073 }
4074 }
Chris Lattner3af10532006-05-05 06:39:07 +00004075
Chris Lattner113f4f42002-06-25 16:13:24 +00004076 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004077}
4078
Chris Lattner6862fbd2004-09-29 17:40:11 +00004079static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004080 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004081}
4082
4083/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4084/// overflowed for this type.
4085static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4086 ConstantInt *In2) {
4087 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4088
Reid Spencerc635f472006-12-31 05:48:39 +00004089 return cast<ConstantInt>(Result)->getZExtValue() <
4090 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004091}
4092
Chris Lattner0798af32005-01-13 20:14:25 +00004093/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4094/// code necessary to compute the offset from the base pointer (without adding
4095/// in the base pointer). Return the result as a signed integer of intptr size.
4096static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4097 TargetData &TD = IC.getTargetData();
4098 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004099 const Type *IntPtrTy = TD.getIntPtrType();
4100 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004101
4102 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004103 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004104
Chris Lattner0798af32005-01-13 20:14:25 +00004105 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4106 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004107 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004108 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004109 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4110 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004111 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004112 Scale = ConstantExpr::getMul(OpC, Scale);
4113 if (Constant *RC = dyn_cast<Constant>(Result))
4114 Result = ConstantExpr::getAdd(RC, Scale);
4115 else {
4116 // Emit an add instruction.
4117 Result = IC.InsertNewInstBefore(
4118 BinaryOperator::createAdd(Result, Scale,
4119 GEP->getName()+".offs"), I);
4120 }
4121 }
4122 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004123 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004124 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004125 Op->getName()+".c"), I);
4126 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004127 // We'll let instcombine(mul) convert this to a shl if possible.
4128 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4129 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004130
4131 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004132 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004133 GEP->getName()+".offs"), I);
4134 }
4135 }
4136 return Result;
4137}
4138
Reid Spencer266e42b2006-12-23 06:05:41 +00004139/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004140/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004141Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4142 ICmpInst::Predicate Cond,
4143 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004144 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004145
4146 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4147 if (isa<PointerType>(CI->getOperand(0)->getType()))
4148 RHS = CI->getOperand(0);
4149
Chris Lattner0798af32005-01-13 20:14:25 +00004150 Value *PtrBase = GEPLHS->getOperand(0);
4151 if (PtrBase == RHS) {
4152 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004153 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4154 // each index is zero or not.
4155 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004156 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004157 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4158 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004159 bool EmitIt = true;
4160 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4161 if (isa<UndefValue>(C)) // undef index -> undef.
4162 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4163 if (C->isNullValue())
4164 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004165 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4166 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004167 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004168 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004169 ConstantInt::get(Type::Int1Ty,
4170 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004171 }
4172
4173 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004174 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004175 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004176 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4177 if (InVal == 0)
4178 InVal = Comp;
4179 else {
4180 InVal = InsertNewInstBefore(InVal, I);
4181 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004182 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004183 InVal = BinaryOperator::createOr(InVal, Comp);
4184 else // True if all are equal
4185 InVal = BinaryOperator::createAnd(InVal, Comp);
4186 }
4187 }
4188 }
4189
4190 if (InVal)
4191 return InVal;
4192 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004193 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004194 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4195 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004196 }
Chris Lattner0798af32005-01-13 20:14:25 +00004197
Reid Spencer266e42b2006-12-23 06:05:41 +00004198 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004199 // the result to fold to a constant!
4200 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4201 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4202 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004203 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4204 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004205 }
4206 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004207 // If the base pointers are different, but the indices are the same, just
4208 // compare the base pointer.
4209 if (PtrBase != GEPRHS->getOperand(0)) {
4210 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004211 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004212 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004213 if (IndicesTheSame)
4214 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4215 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4216 IndicesTheSame = false;
4217 break;
4218 }
4219
4220 // If all indices are the same, just compare the base pointers.
4221 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004222 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4223 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004224
4225 // Otherwise, the base pointers are different and the indices are
4226 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004227 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004228 }
Chris Lattner0798af32005-01-13 20:14:25 +00004229
Chris Lattner81e84172005-01-13 22:25:21 +00004230 // If one of the GEPs has all zero indices, recurse.
4231 bool AllZeros = true;
4232 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4233 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4234 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4235 AllZeros = false;
4236 break;
4237 }
4238 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004239 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4240 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004241
4242 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004243 AllZeros = true;
4244 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4245 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4246 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4247 AllZeros = false;
4248 break;
4249 }
4250 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004251 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004252
Chris Lattner4fa89822005-01-14 00:20:05 +00004253 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4254 // If the GEPs only differ by one index, compare it.
4255 unsigned NumDifferences = 0; // Keep track of # differences.
4256 unsigned DiffOperand = 0; // The operand that differs.
4257 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4258 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004259 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4260 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004261 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004262 NumDifferences = 2;
4263 break;
4264 } else {
4265 if (NumDifferences++) break;
4266 DiffOperand = i;
4267 }
4268 }
4269
4270 if (NumDifferences == 0) // SAME GEP?
4271 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004272 ConstantInt::get(Type::Int1Ty,
4273 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004274 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004275 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4276 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004277 // Make sure we do a signed comparison here.
4278 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004279 }
4280 }
4281
Reid Spencer266e42b2006-12-23 06:05:41 +00004282 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004283 // the result to fold to a constant!
4284 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4285 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4286 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4287 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4288 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004289 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004290 }
4291 }
4292 return 0;
4293}
4294
Reid Spencer266e42b2006-12-23 06:05:41 +00004295Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4296 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004298
Chris Lattner6ee923f2007-01-14 19:42:17 +00004299 // Fold trivial predicates.
4300 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4301 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4302 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4303 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4304
4305 // Simplify 'fcmp pred X, X'
4306 if (Op0 == Op1) {
4307 switch (I.getPredicate()) {
4308 default: assert(0 && "Unknown predicate!");
4309 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4310 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4311 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4312 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4313 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4314 case FCmpInst::FCMP_OLT: // True if ordered and less than
4315 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4316 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4317
4318 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4319 case FCmpInst::FCMP_ULT: // True if unordered or less than
4320 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4321 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4322 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4323 I.setPredicate(FCmpInst::FCMP_UNO);
4324 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4325 return &I;
4326
4327 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4328 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4329 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4330 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4331 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4332 I.setPredicate(FCmpInst::FCMP_ORD);
4333 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4334 return &I;
4335 }
4336 }
4337
Reid Spencer266e42b2006-12-23 06:05:41 +00004338 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004339 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004340
Reid Spencer266e42b2006-12-23 06:05:41 +00004341 // Handle fcmp with constant RHS
4342 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4343 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4344 switch (LHSI->getOpcode()) {
4345 case Instruction::PHI:
4346 if (Instruction *NV = FoldOpIntoPhi(I))
4347 return NV;
4348 break;
4349 case Instruction::Select:
4350 // If either operand of the select is a constant, we can fold the
4351 // comparison into the select arms, which will cause one to be
4352 // constant folded and the select turned into a bitwise or.
4353 Value *Op1 = 0, *Op2 = 0;
4354 if (LHSI->hasOneUse()) {
4355 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4356 // Fold the known value into the constant operand.
4357 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4358 // Insert a new FCmp of the other select operand.
4359 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4360 LHSI->getOperand(2), RHSC,
4361 I.getName()), I);
4362 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4363 // Fold the known value into the constant operand.
4364 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4365 // Insert a new FCmp of the other select operand.
4366 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4367 LHSI->getOperand(1), RHSC,
4368 I.getName()), I);
4369 }
4370 }
4371
4372 if (Op1)
4373 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4374 break;
4375 }
4376 }
4377
4378 return Changed ? &I : 0;
4379}
4380
4381Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4382 bool Changed = SimplifyCompare(I);
4383 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4384 const Type *Ty = Op0->getType();
4385
4386 // icmp X, X
4387 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004388 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4389 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004390
4391 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004392 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004393
4394 // icmp of GlobalValues can never equal each other as long as they aren't
4395 // external weak linkage type.
4396 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4397 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4398 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004399 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4400 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004401
4402 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004403 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004404 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4405 isa<ConstantPointerNull>(Op0)) &&
4406 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004407 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004408 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4409 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004410
Reid Spencer266e42b2006-12-23 06:05:41 +00004411 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004412 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004413 switch (I.getPredicate()) {
4414 default: assert(0 && "Invalid icmp instruction!");
4415 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004416 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004417 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004418 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004419 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004420 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004421 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004422
Reid Spencer266e42b2006-12-23 06:05:41 +00004423 case ICmpInst::ICMP_UGT:
4424 case ICmpInst::ICMP_SGT:
4425 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004426 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004427 case ICmpInst::ICMP_ULT:
4428 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004429 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4430 InsertNewInstBefore(Not, I);
4431 return BinaryOperator::createAnd(Not, Op1);
4432 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004433 case ICmpInst::ICMP_UGE:
4434 case ICmpInst::ICMP_SGE:
4435 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004436 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004437 case ICmpInst::ICMP_ULE:
4438 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004439 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4440 InsertNewInstBefore(Not, I);
4441 return BinaryOperator::createOr(Not, Op1);
4442 }
4443 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004444 }
4445
Chris Lattner2dd01742004-06-09 04:24:29 +00004446 // See if we are doing a comparison between a constant and an instruction that
4447 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004448 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004449 switch (I.getPredicate()) {
4450 default: break;
4451 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4452 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004453 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004454 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4455 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4456 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4457 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4458 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004459
Reid Spencer266e42b2006-12-23 06:05:41 +00004460 case ICmpInst::ICMP_SLT:
4461 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004462 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004463 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4464 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4465 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4466 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4467 break;
4468
4469 case ICmpInst::ICMP_UGT:
4470 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004471 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004472 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4473 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4474 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4475 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4476 break;
4477
4478 case ICmpInst::ICMP_SGT:
4479 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004480 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004481 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4482 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4483 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4484 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4485 break;
4486
4487 case ICmpInst::ICMP_ULE:
4488 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004489 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004490 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4491 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4492 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4493 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4494 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004495
Reid Spencer266e42b2006-12-23 06:05:41 +00004496 case ICmpInst::ICMP_SLE:
4497 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004498 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004499 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4500 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4501 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4502 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4503 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004504
Reid Spencer266e42b2006-12-23 06:05:41 +00004505 case ICmpInst::ICMP_UGE:
4506 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004507 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004508 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4509 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4510 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4511 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4512 break;
4513
4514 case ICmpInst::ICMP_SGE:
4515 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004516 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004517 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4518 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4519 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4520 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4521 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004522 }
4523
Reid Spencer266e42b2006-12-23 06:05:41 +00004524 // If we still have a icmp le or icmp ge instruction, turn it into the
4525 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004526 // already been handled above, this requires little checking.
4527 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004528 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4529 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4530 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4531 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4532 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4533 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4534 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4535 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004536
4537 // See if we can fold the comparison based on bits known to be zero or one
4538 // in the input.
4539 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004540 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004541 KnownZero, KnownOne, 0))
4542 return &I;
4543
4544 // Given the known and unknown bits, compute a range that the LHS could be
4545 // in.
4546 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004547 // Compute the Min, Max and RHS values based on the known bits. For the
4548 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004549 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4550 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004551 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4552 SRHSVal = CI->getSExtValue();
4553 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4554 SMax);
4555 } else {
4556 URHSVal = CI->getZExtValue();
4557 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4558 UMax);
4559 }
4560 switch (I.getPredicate()) { // LE/GE have been folded already.
4561 default: assert(0 && "Unknown icmp opcode!");
4562 case ICmpInst::ICMP_EQ:
4563 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004564 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004565 break;
4566 case ICmpInst::ICMP_NE:
4567 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004568 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004569 break;
4570 case ICmpInst::ICMP_ULT:
4571 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004572 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004573 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004574 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004575 break;
4576 case ICmpInst::ICMP_UGT:
4577 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004578 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004579 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004580 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004581 break;
4582 case ICmpInst::ICMP_SLT:
4583 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004584 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004585 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004586 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004587 break;
4588 case ICmpInst::ICMP_SGT:
4589 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004590 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004591 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004592 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004593 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004594 }
4595 }
4596
Reid Spencer266e42b2006-12-23 06:05:41 +00004597 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004598 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004599 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004600 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004601 switch (LHSI->getOpcode()) {
4602 case Instruction::And:
4603 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4604 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004605 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4606
Reid Spencer266e42b2006-12-23 06:05:41 +00004607 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004608 // and/compare to be the input width without changing the value
4609 // produced, eliminating a cast.
4610 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4611 // We can do this transformation if either the AND constant does not
4612 // have its sign bit set or if it is an equality comparison.
4613 // Extending a relational comparison when we're checking the sign
4614 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004615 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004616 (I.isEquality() ||
4617 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4618 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4619 ConstantInt *NewCST;
4620 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004621 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4622 AndCST->getZExtValue());
4623 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4624 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004625 Instruction *NewAnd =
4626 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4627 LHSI->getName());
4628 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004629 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004630 }
4631 }
4632
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004633 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4634 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4635 // happens a LOT in code produced by the C front-end, for bitfield
4636 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004637 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4638 if (Shift && !Shift->isShift())
4639 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004640
Reid Spencere0fc4df2006-10-20 07:07:24 +00004641 ConstantInt *ShAmt;
4642 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004643 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4644 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004645
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004646 // We can fold this as long as we can't shift unknown bits
4647 // into the mask. This can only happen with signed shift
4648 // rights, as they sign-extend.
4649 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004650 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004651 if (!CanFold) {
4652 // To test for the bad case of the signed shr, see if any
4653 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004654 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004655 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4656
Reid Spencer2341c222007-02-02 02:16:23 +00004657 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004658 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004659 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4660 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004661 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4662 CanFold = true;
4663 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004664
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004665 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004666 Constant *NewCst;
4667 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004668 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004669 else
4670 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004671
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004672 // Check to see if we are shifting out any of the bits being
4673 // compared.
4674 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4675 // If we shifted bits out, the fold is not going to work out.
4676 // As a special case, check to see if this means that the
4677 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004678 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004679 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004680 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004681 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004682 } else {
4683 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004684 Constant *NewAndCST;
4685 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004686 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004687 else
4688 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4689 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004690 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004691 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004692 AddUsesToWorkList(I);
4693 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004694 }
4695 }
Chris Lattner35167c32004-06-09 07:59:58 +00004696 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004697
4698 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4699 // preferable because it allows the C<<Y expression to be hoisted out
4700 // of a loop if Y is invariant and X is not.
4701 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004702 I.isEquality() && !Shift->isArithmeticShift() &&
4703 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004704 // Compute C << Y.
4705 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004706 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004707 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004708 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004709 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004710 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004711 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004712 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004713 }
4714 InsertNewInstBefore(cast<Instruction>(NS), I);
4715
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004716 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004717 Instruction *NewAnd = BinaryOperator::createAnd(
4718 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004719 InsertNewInstBefore(NewAnd, I);
4720
4721 I.setOperand(0, NewAnd);
4722 return &I;
4723 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004724 }
4725 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004726
Reid Spencer266e42b2006-12-23 06:05:41 +00004727 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004728 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004729 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004730 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4731
4732 // Check that the shift amount is in range. If not, don't perform
4733 // undefined shifts. When the shift is visited it will be
4734 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004735 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004736 break;
4737
Chris Lattner272d5ca2004-09-28 18:22:15 +00004738 // If we are comparing against bits always shifted out, the
4739 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004740 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004741 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004742 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004743 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004744 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004745 return ReplaceInstUsesWith(I, Cst);
4746 }
4747
4748 if (LHSI->hasOneUse()) {
4749 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004750 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004751 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004752 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004753
Chris Lattner272d5ca2004-09-28 18:22:15 +00004754 Instruction *AndI =
4755 BinaryOperator::createAnd(LHSI->getOperand(0),
4756 Mask, LHSI->getName()+".mask");
4757 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004758 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004759 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004760 }
4761 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004762 }
4763 break;
4764
Reid Spencer266e42b2006-12-23 06:05:41 +00004765 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004766 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004767 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004768 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004769 // Check that the shift amount is in range. If not, don't perform
4770 // undefined shifts. When the shift is visited it will be
4771 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004772 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004773 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004774 break;
4775
Chris Lattner1023b872004-09-27 16:18:50 +00004776 // If we are comparing against bits always shifted out, the
4777 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004778 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004779 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004780 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4781 ShAmt);
4782 else
4783 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4784 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004785
Chris Lattner1023b872004-09-27 16:18:50 +00004786 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004787 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004788 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004789 return ReplaceInstUsesWith(I, Cst);
4790 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004791
Chris Lattner1023b872004-09-27 16:18:50 +00004792 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004793 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004794
Chris Lattner1023b872004-09-27 16:18:50 +00004795 // Otherwise strength reduce the shift into an and.
4796 uint64_t Val = ~0ULL; // All ones.
4797 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004798 Val &= ~0ULL >> (64-TypeBits);
4799 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004800
Chris Lattner1023b872004-09-27 16:18:50 +00004801 Instruction *AndI =
4802 BinaryOperator::createAnd(LHSI->getOperand(0),
4803 Mask, LHSI->getName()+".mask");
4804 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004805 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004806 ConstantExpr::getShl(CI, ShAmt));
4807 }
Chris Lattner1023b872004-09-27 16:18:50 +00004808 }
4809 }
4810 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004811
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004812 case Instruction::SDiv:
4813 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004814 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004815 // Fold this div into the comparison, producing a range check.
4816 // Determine, based on the divide type, what the range is being
4817 // checked. If there is an overflow on the low or high side, remember
4818 // it, otherwise compute the range [low, hi) bounding the new value.
4819 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004820 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004821 // FIXME: If the operand types don't match the type of the divide
4822 // then don't attempt this transform. The code below doesn't have the
4823 // logic to deal with a signed divide and an unsigned compare (and
4824 // vice versa). This is because (x /s C1) <s C2 produces different
4825 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4826 // (x /u C1) <u C2. Simply casting the operands and result won't
4827 // work. :( The if statement below tests that condition and bails
4828 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004829 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4830 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004831 break;
4832
4833 // Initialize the variables that will indicate the nature of the
4834 // range check.
4835 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004836 ConstantInt *LoBound = 0, *HiBound = 0;
4837
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004838 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4839 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4840 // C2 (CI). By solving for X we can turn this into a range check
4841 // instead of computing a divide.
4842 ConstantInt *Prod =
4843 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004844
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004845 // Determine if the product overflows by seeing if the product is
4846 // not equal to the divide. Make sure we do the same kind of divide
4847 // as in the LHS instruction that we're folding.
4848 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004849 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004850 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4851
Reid Spencer266e42b2006-12-23 06:05:41 +00004852 // Get the ICmp opcode
4853 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004854
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004855 if (DivRHS->isNullValue()) {
4856 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004857 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004858 LoBound = Prod;
4859 LoOverflow = ProdOV;
4860 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004861 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004862 if (CI->isNullValue()) { // (X / pos) op 0
4863 // Can't overflow.
4864 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4865 HiBound = DivRHS;
4866 } else if (isPositive(CI)) { // (X / pos) op pos
4867 LoBound = Prod;
4868 LoOverflow = ProdOV;
4869 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4870 } else { // (X / pos) op neg
4871 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4872 LoOverflow = AddWithOverflow(LoBound, Prod,
4873 cast<ConstantInt>(DivRHSH));
4874 HiBound = Prod;
4875 HiOverflow = ProdOV;
4876 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004877 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004878 if (CI->isNullValue()) { // (X / neg) op 0
4879 LoBound = AddOne(DivRHS);
4880 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004881 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004882 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004883 } else if (isPositive(CI)) { // (X / neg) op pos
4884 HiOverflow = LoOverflow = ProdOV;
4885 if (!LoOverflow)
4886 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4887 HiBound = AddOne(Prod);
4888 } else { // (X / neg) op neg
4889 LoBound = Prod;
4890 LoOverflow = HiOverflow = ProdOV;
4891 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4892 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004893
Chris Lattnera92af962004-10-11 19:40:04 +00004894 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004895 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004896 }
4897
4898 if (LoBound) {
4899 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004900 switch (predicate) {
4901 default: assert(0 && "Unhandled icmp opcode!");
4902 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004903 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004905 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004906 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4907 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004908 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004909 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4910 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004911 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004912 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4913 true, I);
4914 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004915 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004916 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004917 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004918 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4919 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004920 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4922 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004923 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004924 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4925 false, I);
4926 case ICmpInst::ICMP_ULT:
4927 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004928 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004929 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004930 return new ICmpInst(predicate, X, LoBound);
4931 case ICmpInst::ICMP_UGT:
4932 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004933 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004934 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004935 if (predicate == ICmpInst::ICMP_UGT)
4936 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4937 else
4938 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004939 }
4940 }
4941 }
4942 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004943 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004944
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004946 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004947 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004948
Reid Spencere0fc4df2006-10-20 07:07:24 +00004949 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4950 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004951 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4952 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004953 case Instruction::SRem:
4954 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4955 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4956 BO->hasOneUse()) {
4957 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4958 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004959 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4960 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004961 return new ICmpInst(I.getPredicate(), NewRem,
4962 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004963 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004964 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004965 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004966 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004967 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4968 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004969 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004970 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4971 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004972 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004973 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4974 // efficiently invertible, or if the add has just this one use.
4975 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004976
Chris Lattnerc992add2003-08-13 05:33:12 +00004977 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004978 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004979 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004980 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004981 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004982 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00004983 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004984 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00004985 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004986 }
4987 }
4988 break;
4989 case Instruction::Xor:
4990 // For the xor case, we can xor two constants together, eliminating
4991 // the explicit xor.
4992 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004993 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4994 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004995
4996 // FALLTHROUGH
4997 case Instruction::Sub:
4998 // Replace (([sub|xor] A, B) != 0) with (A != B)
4999 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005000 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5001 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005002 break;
5003
5004 case Instruction::Or:
5005 // If bits are being or'd in that are not present in the constant we
5006 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005007 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005008 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005009 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005010 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5011 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005012 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005013 break;
5014
5015 case Instruction::And:
5016 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005017 // If bits are being compared against that are and'd out, then the
5018 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005019 if (!ConstantExpr::getAnd(CI,
5020 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005021 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5022 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005023
Chris Lattner35167c32004-06-09 07:59:58 +00005024 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005025 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005026 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5027 ICmpInst::ICMP_NE, Op0,
5028 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005029
Reid Spencer266e42b2006-12-23 06:05:41 +00005030 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005031 if (isSignBit(BOC)) {
5032 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005033 Constant *Zero = Constant::getNullValue(X->getType());
5034 ICmpInst::Predicate pred = isICMP_NE ?
5035 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5036 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005037 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005038
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005039 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005040 if (CI->isNullValue() && isHighOnes(BOC)) {
5041 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005042 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005043 ICmpInst::Predicate pred = isICMP_NE ?
5044 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5045 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005046 }
5047
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005048 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005049 default: break;
5050 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005051 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5052 // Handle set{eq|ne} <intrinsic>, intcst.
5053 switch (II->getIntrinsicID()) {
5054 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005055 case Intrinsic::bswap_i16:
5056 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005057 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005058 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005059 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005060 ByteSwap_16(CI->getZExtValue())));
5061 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005062 case Intrinsic::bswap_i32:
5063 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005064 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005065 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005066 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005067 ByteSwap_32(CI->getZExtValue())));
5068 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005069 case Intrinsic::bswap_i64:
5070 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005071 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005072 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005073 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005074 ByteSwap_64(CI->getZExtValue())));
5075 return &I;
5076 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005077 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005078 } else { // Not a ICMP_EQ/ICMP_NE
5079 // If the LHS is a cast from an integral value of the same size, then
5080 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005081 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5082 Value *CastOp = Cast->getOperand(0);
5083 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005084 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005085 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005086 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005087 // If this is an unsigned comparison, try to make the comparison use
5088 // smaller constant values.
5089 switch (I.getPredicate()) {
5090 default: break;
5091 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5092 ConstantInt *CUI = cast<ConstantInt>(CI);
5093 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5094 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer24f1a0e2007-03-01 19:33:52 +00005095 ConstantInt::get(SrcTy, -1ULL));
Reid Spencer266e42b2006-12-23 06:05:41 +00005096 break;
5097 }
5098 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5099 ConstantInt *CUI = cast<ConstantInt>(CI);
5100 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5101 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5102 Constant::getNullValue(SrcTy));
5103 break;
5104 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005105 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005106
Chris Lattner2b55ea32004-02-23 07:16:20 +00005107 }
5108 }
Chris Lattnere967b342003-06-04 05:10:11 +00005109 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005110 }
5111
Reid Spencer266e42b2006-12-23 06:05:41 +00005112 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005113 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5114 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5115 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005116 case Instruction::GetElementPtr:
5117 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005118 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005119 bool isAllZeros = true;
5120 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5121 if (!isa<Constant>(LHSI->getOperand(i)) ||
5122 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5123 isAllZeros = false;
5124 break;
5125 }
5126 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005127 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005128 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5129 }
5130 break;
5131
Chris Lattner77c32c32005-04-23 15:31:55 +00005132 case Instruction::PHI:
5133 if (Instruction *NV = FoldOpIntoPhi(I))
5134 return NV;
5135 break;
5136 case Instruction::Select:
5137 // If either operand of the select is a constant, we can fold the
5138 // comparison into the select arms, which will cause one to be
5139 // constant folded and the select turned into a bitwise or.
5140 Value *Op1 = 0, *Op2 = 0;
5141 if (LHSI->hasOneUse()) {
5142 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5143 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005144 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5145 // Insert a new ICmp of the other select operand.
5146 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5147 LHSI->getOperand(2), RHSC,
5148 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005149 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5150 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005151 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5152 // Insert a new ICmp of the other select operand.
5153 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5154 LHSI->getOperand(1), RHSC,
5155 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005156 }
5157 }
Jeff Cohen82639852005-04-23 21:38:35 +00005158
Chris Lattner77c32c32005-04-23 15:31:55 +00005159 if (Op1)
5160 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5161 break;
5162 }
5163 }
5164
Reid Spencer266e42b2006-12-23 06:05:41 +00005165 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005166 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005167 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005168 return NI;
5169 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005170 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5171 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005172 return NI;
5173
Reid Spencer266e42b2006-12-23 06:05:41 +00005174 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005175 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5176 // now.
5177 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5178 if (isa<PointerType>(Op0->getType()) &&
5179 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005180 // We keep moving the cast from the left operand over to the right
5181 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005182 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005183
Chris Lattner64d87b02007-01-06 01:45:59 +00005184 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5185 // so eliminate it as well.
5186 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5187 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005188
Chris Lattner16930792003-11-03 04:25:02 +00005189 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005190 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005191 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005192 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005193 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005194 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005195 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005196 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005197 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005198 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005199 }
5200
5201 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005202 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005203 // This comes up when you have code like
5204 // int X = A < B;
5205 // if (X) ...
5206 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005207 // with a constant or another cast from the same type.
5208 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005209 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005210 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005211 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005212
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005213 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005214 Value *A, *B, *C, *D;
5215 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5216 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5217 Value *OtherVal = A == Op1 ? B : A;
5218 return new ICmpInst(I.getPredicate(), OtherVal,
5219 Constant::getNullValue(A->getType()));
5220 }
5221
5222 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5223 // A^c1 == C^c2 --> A == C^(c1^c2)
5224 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5225 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5226 if (Op1->hasOneUse()) {
5227 Constant *NC = ConstantExpr::getXor(C1, C2);
5228 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5229 return new ICmpInst(I.getPredicate(), A,
5230 InsertNewInstBefore(Xor, I));
5231 }
5232
5233 // A^B == A^D -> B == D
5234 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5235 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5236 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5237 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5238 }
5239 }
5240
5241 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5242 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005243 // A == (A^B) -> B == 0
5244 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005245 return new ICmpInst(I.getPredicate(), OtherVal,
5246 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005247 }
5248 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005249 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005250 return new ICmpInst(I.getPredicate(), B,
5251 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005252 }
5253 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005254 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005255 return new ICmpInst(I.getPredicate(), B,
5256 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005257 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005258
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005259 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5260 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5261 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5262 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5263 Value *X = 0, *Y = 0, *Z = 0;
5264
5265 if (A == C) {
5266 X = B; Y = D; Z = A;
5267 } else if (A == D) {
5268 X = B; Y = C; Z = A;
5269 } else if (B == C) {
5270 X = A; Y = D; Z = B;
5271 } else if (B == D) {
5272 X = A; Y = C; Z = B;
5273 }
5274
5275 if (X) { // Build (X^Y) & Z
5276 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5277 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5278 I.setOperand(0, Op1);
5279 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5280 return &I;
5281 }
5282 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005283 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005284 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005285}
5286
Reid Spencer266e42b2006-12-23 06:05:41 +00005287// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005288// We only handle extending casts so far.
5289//
Reid Spencer266e42b2006-12-23 06:05:41 +00005290Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5291 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005292 Value *LHSCIOp = LHSCI->getOperand(0);
5293 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005294 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005295 Value *RHSCIOp;
5296
Reid Spencer266e42b2006-12-23 06:05:41 +00005297 // We only handle extension cast instructions, so far. Enforce this.
5298 if (LHSCI->getOpcode() != Instruction::ZExt &&
5299 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005300 return 0;
5301
Reid Spencer266e42b2006-12-23 06:05:41 +00005302 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5303 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005304
Reid Spencer266e42b2006-12-23 06:05:41 +00005305 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005306 // Not an extension from the same type?
5307 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005308 if (RHSCIOp->getType() != LHSCIOp->getType())
5309 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005310
5311 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5312 // and the other is a zext), then we can't handle this.
5313 if (CI->getOpcode() != LHSCI->getOpcode())
5314 return 0;
5315
5316 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5317 // then we can't handle this.
5318 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5319 return 0;
5320
5321 // Okay, just insert a compare of the reduced operands now!
5322 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005323 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005324
Reid Spencer266e42b2006-12-23 06:05:41 +00005325 // If we aren't dealing with a constant on the RHS, exit early
5326 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5327 if (!CI)
5328 return 0;
5329
5330 // Compute the constant that would happen if we truncated to SrcTy then
5331 // reextended to DestTy.
5332 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5333 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5334
5335 // If the re-extended constant didn't change...
5336 if (Res2 == CI) {
5337 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5338 // For example, we might have:
5339 // %A = sext short %X to uint
5340 // %B = icmp ugt uint %A, 1330
5341 // It is incorrect to transform this into
5342 // %B = icmp ugt short %X, 1330
5343 // because %A may have negative value.
5344 //
5345 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5346 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005347 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005348 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5349 else
5350 return 0;
5351 }
5352
5353 // The re-extended constant changed so the constant cannot be represented
5354 // in the shorter type. Consequently, we cannot emit a simple comparison.
5355
5356 // First, handle some easy cases. We know the result cannot be equal at this
5357 // point so handle the ICI.isEquality() cases
5358 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005359 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005360 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005361 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005362
5363 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5364 // should have been folded away previously and not enter in here.
5365 Value *Result;
5366 if (isSignedCmp) {
5367 // We're performing a signed comparison.
5368 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005369 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005370 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005371 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005372 } else {
5373 // We're performing an unsigned comparison.
5374 if (isSignedExt) {
5375 // We're performing an unsigned comp with a sign extended value.
5376 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005377 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005378 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5379 NegOne, ICI.getName()), ICI);
5380 } else {
5381 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005382 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005383 }
5384 }
5385
5386 // Finally, return the value computed.
5387 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5388 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5389 return ReplaceInstUsesWith(ICI, Result);
5390 } else {
5391 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5392 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5393 "ICmp should be folded!");
5394 if (Constant *CI = dyn_cast<Constant>(Result))
5395 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5396 else
5397 return BinaryOperator::createNot(Result);
5398 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005399}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005400
Reid Spencer2341c222007-02-02 02:16:23 +00005401Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5402 return commonShiftTransforms(I);
5403}
5404
5405Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5406 return commonShiftTransforms(I);
5407}
5408
5409Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5410 return commonShiftTransforms(I);
5411}
5412
5413Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5414 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005416
5417 // shl X, 0 == X and shr X, 0 == X
5418 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005419 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005420 Op0 == Constant::getNullValue(Op0->getType()))
5421 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005422
Reid Spencer266e42b2006-12-23 06:05:41 +00005423 if (isa<UndefValue>(Op0)) {
5424 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005425 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005426 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005427 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5428 }
5429 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005430 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5431 return ReplaceInstUsesWith(I, Op0);
5432 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005433 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005434 }
5435
Chris Lattnerd4dee402006-11-10 23:38:52 +00005436 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5437 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005438 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005439 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005440 return ReplaceInstUsesWith(I, CSI);
5441
Chris Lattner183b3362004-04-09 19:05:30 +00005442 // Try to fold constant and into select arguments.
5443 if (isa<Constant>(Op0))
5444 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005445 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005446 return R;
5447
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005448 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005449 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005450 if (MaskedValueIsZero(Op0,
5451 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005452 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005453 }
5454 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005455
Reid Spencere0fc4df2006-10-20 07:07:24 +00005456 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005457 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5458 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005459 return 0;
5460}
5461
Reid Spencere0fc4df2006-10-20 07:07:24 +00005462Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005463 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005464 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005465
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005466 // See if we can simplify any instructions used by the instruction whose sole
5467 // purpose is to compute bits we don't care about.
5468 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005469 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005470 KnownZero, KnownOne))
5471 return &I;
5472
Chris Lattner14553932006-01-06 07:12:35 +00005473 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5474 // of a signed value.
5475 //
5476 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005477 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005478 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005479 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5480 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005481 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005482 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005483 }
Chris Lattner14553932006-01-06 07:12:35 +00005484 }
5485
5486 // ((X*C1) << C2) == (X * (C1 << C2))
5487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5488 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5489 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5490 return BinaryOperator::createMul(BO->getOperand(0),
5491 ConstantExpr::getShl(BOOp, Op1));
5492
5493 // Try to fold constant and into select arguments.
5494 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5495 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5496 return R;
5497 if (isa<PHINode>(Op0))
5498 if (Instruction *NV = FoldOpIntoPhi(I))
5499 return NV;
5500
5501 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005502 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5503 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5504 Value *V1, *V2;
5505 ConstantInt *CC;
5506 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005507 default: break;
5508 case Instruction::Add:
5509 case Instruction::And:
5510 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005511 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005512 // These operators commute.
5513 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005514 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5515 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005516 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005517 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005518 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005519 Op0BO->getName());
5520 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005521 Instruction *X =
5522 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5523 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005524 InsertNewInstBefore(X, I); // (X + (Y << C))
5525 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005526 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005527 return BinaryOperator::createAnd(X, C2);
5528 }
Chris Lattner14553932006-01-06 07:12:35 +00005529
Chris Lattner797dee72005-09-18 06:30:59 +00005530 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005531 Value *Op0BOOp1 = Op0BO->getOperand(1);
5532 if (isLeftShift && Op0BOOp1->hasOneUse() && V2 == Op1 &&
5533 match(Op0BOOp1,
5534 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5535 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)-> hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005536 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005537 Op0BO->getOperand(0), Op1,
5538 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005539 InsertNewInstBefore(YS, I); // (Y << C)
5540 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005541 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005542 V1->getName()+".mask");
5543 InsertNewInstBefore(XM, I); // X & (CC << C)
5544
5545 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5546 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005547 }
Chris Lattner14553932006-01-06 07:12:35 +00005548
Reid Spencer2f34b982007-02-02 14:41:37 +00005549 // FALL THROUGH.
5550 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005551 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005552 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5553 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005554 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005555 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005556 Op0BO->getOperand(1), Op1,
5557 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005558 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005559 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005560 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005561 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005562 InsertNewInstBefore(X, I); // (X + (Y << C))
5563 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005564 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005565 return BinaryOperator::createAnd(X, C2);
5566 }
Chris Lattner14553932006-01-06 07:12:35 +00005567
Chris Lattner1df0e982006-05-31 21:14:00 +00005568 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005569 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5570 match(Op0BO->getOperand(0),
5571 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005572 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005573 cast<BinaryOperator>(Op0BO->getOperand(0))
5574 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005575 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005576 Op0BO->getOperand(1), Op1,
5577 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005578 InsertNewInstBefore(YS, I); // (Y << C)
5579 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005580 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005581 V1->getName()+".mask");
5582 InsertNewInstBefore(XM, I); // X & (CC << C)
5583
Chris Lattner1df0e982006-05-31 21:14:00 +00005584 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005585 }
Chris Lattner14553932006-01-06 07:12:35 +00005586
Chris Lattner27cb9db2005-09-18 05:12:10 +00005587 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005588 }
Chris Lattner14553932006-01-06 07:12:35 +00005589 }
5590
5591
5592 // If the operand is an bitwise operator with a constant RHS, and the
5593 // shift is the only use, we can pull it out of the shift.
5594 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5595 bool isValid = true; // Valid only for And, Or, Xor
5596 bool highBitSet = false; // Transform if high bit of constant set?
5597
5598 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005599 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005600 case Instruction::Add:
5601 isValid = isLeftShift;
5602 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005603 case Instruction::Or:
5604 case Instruction::Xor:
5605 highBitSet = false;
5606 break;
5607 case Instruction::And:
5608 highBitSet = true;
5609 break;
Chris Lattner14553932006-01-06 07:12:35 +00005610 }
5611
5612 // If this is a signed shift right, and the high bit is modified
5613 // by the logical operation, do not perform the transformation.
5614 // The highBitSet boolean indicates the value of the high bit of
5615 // the constant which would cause it to be modified for this
5616 // operation.
5617 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005618 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005619 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005620 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5621 }
5622
5623 if (isValid) {
5624 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5625
5626 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005627 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005628 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005629 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005630
5631 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5632 NewRHS);
5633 }
5634 }
5635 }
5636 }
5637
Chris Lattnereb372a02006-01-06 07:52:12 +00005638 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005639 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5640 if (ShiftOp && !ShiftOp->isShift())
5641 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005642
Reid Spencere0fc4df2006-10-20 07:07:24 +00005643 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005644 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00005645 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5646 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005647 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5648 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5649 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005650
Chris Lattner3e009e82007-02-05 00:57:54 +00005651 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5652 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5653 AmtSum = I.getType()->getPrimitiveSizeInBits();
5654
5655 const IntegerType *Ty = cast<IntegerType>(I.getType());
5656
5657 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005658 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005659 return BinaryOperator::create(I.getOpcode(), X,
5660 ConstantInt::get(Ty, AmtSum));
5661 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5662 I.getOpcode() == Instruction::AShr) {
5663 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5664 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5665 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5666 I.getOpcode() == Instruction::LShr) {
5667 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5668 Instruction *Shift =
5669 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5670 InsertNewInstBefore(Shift, I);
5671
5672 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5673 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005674 }
5675
Chris Lattner3e009e82007-02-05 00:57:54 +00005676 // Okay, if we get here, one shift must be left, and the other shift must be
5677 // right. See if the amounts are equal.
5678 if (ShiftAmt1 == ShiftAmt2) {
5679 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5680 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005681 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005682 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5683 }
5684 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5685 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005686 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005687 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5688 }
5689 // We can simplify ((X << C) >>s C) into a trunc + sext.
5690 // NOTE: we could do this for any C, but that would make 'unusual' integer
5691 // types. For now, just stick to ones well-supported by the code
5692 // generators.
5693 const Type *SExtType = 0;
5694 switch (Ty->getBitWidth() - ShiftAmt1) {
5695 case 8 : SExtType = Type::Int8Ty; break;
5696 case 16: SExtType = Type::Int16Ty; break;
5697 case 32: SExtType = Type::Int32Ty; break;
5698 default: break;
5699 }
5700 if (SExtType) {
5701 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5702 InsertNewInstBefore(NewTrunc, I);
5703 return new SExtInst(NewTrunc, Ty);
5704 }
5705 // Otherwise, we can't handle it yet.
5706 } else if (ShiftAmt1 < ShiftAmt2) {
5707 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005708
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005709 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005710 if (I.getOpcode() == Instruction::Shl) {
5711 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5712 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005713 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005714 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005715 InsertNewInstBefore(Shift, I);
5716
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005717 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005718 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005719 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005720
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005721 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005722 if (I.getOpcode() == Instruction::LShr) {
5723 assert(ShiftOp->getOpcode() == Instruction::Shl);
5724 Instruction *Shift =
5725 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5726 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005727
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005728 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005729 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005730 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005731
5732 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5733 } else {
5734 assert(ShiftAmt2 < ShiftAmt1);
5735 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5736
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005737 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005738 if (I.getOpcode() == Instruction::Shl) {
5739 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5740 ShiftOp->getOpcode() == Instruction::AShr);
5741 Instruction *Shift =
5742 BinaryOperator::create(ShiftOp->getOpcode(), X,
5743 ConstantInt::get(Ty, ShiftDiff));
5744 InsertNewInstBefore(Shift, I);
5745
5746 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5747 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5748 }
5749
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005750 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005751 if (I.getOpcode() == Instruction::LShr) {
5752 assert(ShiftOp->getOpcode() == Instruction::Shl);
5753 Instruction *Shift =
5754 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5755 InsertNewInstBefore(Shift, I);
5756
5757 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5758 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5759 }
5760
5761 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005762 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005763 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005764 return 0;
5765}
5766
Chris Lattner48a44f72002-05-02 17:06:02 +00005767
Chris Lattner8f663e82005-10-29 04:36:15 +00005768/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5769/// expression. If so, decompose it, returning some value X, such that Val is
5770/// X*Scale+Offset.
5771///
5772static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5773 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005774 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005775 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005776 Offset = CI->getZExtValue();
5777 Scale = 1;
5778 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005779 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5780 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005781 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005782 if (I->getOpcode() == Instruction::Shl) {
5783 // This is a value scaled by '1 << the shift amt'.
5784 Scale = 1U << CUI->getZExtValue();
5785 Offset = 0;
5786 return I->getOperand(0);
5787 } else if (I->getOpcode() == Instruction::Mul) {
5788 // This value is scaled by 'CUI'.
5789 Scale = CUI->getZExtValue();
5790 Offset = 0;
5791 return I->getOperand(0);
5792 } else if (I->getOpcode() == Instruction::Add) {
5793 // We have X+C. Check to see if we really have (X*C2)+C1,
5794 // where C1 is divisible by C2.
5795 unsigned SubScale;
5796 Value *SubVal =
5797 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5798 Offset += CUI->getZExtValue();
5799 if (SubScale > 1 && (Offset % SubScale == 0)) {
5800 Scale = SubScale;
5801 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005802 }
5803 }
5804 }
5805 }
5806 }
5807
5808 // Otherwise, we can't look past this.
5809 Scale = 1;
5810 Offset = 0;
5811 return Val;
5812}
5813
5814
Chris Lattner216be912005-10-24 06:03:58 +00005815/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5816/// try to eliminate the cast by moving the type information into the alloc.
5817Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5818 AllocationInst &AI) {
5819 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005820 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005821
Chris Lattnerac87beb2005-10-24 06:22:12 +00005822 // Remove any uses of AI that are dead.
5823 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005824
Chris Lattnerac87beb2005-10-24 06:22:12 +00005825 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5826 Instruction *User = cast<Instruction>(*UI++);
5827 if (isInstructionTriviallyDead(User)) {
5828 while (UI != E && *UI == User)
5829 ++UI; // If this instruction uses AI more than once, don't break UI.
5830
Chris Lattnerac87beb2005-10-24 06:22:12 +00005831 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005832 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005833 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005834 }
5835 }
5836
Chris Lattner216be912005-10-24 06:03:58 +00005837 // Get the type really allocated and the type casted to.
5838 const Type *AllocElTy = AI.getAllocatedType();
5839 const Type *CastElTy = PTy->getElementType();
5840 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005841
Chris Lattner945e4372007-02-14 05:52:17 +00005842 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5843 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005844 if (CastElTyAlign < AllocElTyAlign) return 0;
5845
Chris Lattner46705b22005-10-24 06:35:18 +00005846 // If the allocation has multiple uses, only promote it if we are strictly
5847 // increasing the alignment of the resultant allocation. If we keep it the
5848 // same, we open the door to infinite loops of various kinds.
5849 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5850
Chris Lattner216be912005-10-24 06:03:58 +00005851 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5852 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005853 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005854
Chris Lattner8270c332005-10-29 03:19:53 +00005855 // See if we can satisfy the modulus by pulling a scale out of the array
5856 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005857 unsigned ArraySizeScale, ArrayOffset;
5858 Value *NumElements = // See if the array size is a decomposable linear expr.
5859 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5860
Chris Lattner8270c332005-10-29 03:19:53 +00005861 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5862 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005863 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5864 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005865
Chris Lattner8270c332005-10-29 03:19:53 +00005866 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5867 Value *Amt = 0;
5868 if (Scale == 1) {
5869 Amt = NumElements;
5870 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005871 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005872 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5873 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005874 Amt = ConstantExpr::getMul(
5875 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5876 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005877 else if (Scale != 1) {
5878 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5879 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005880 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005881 }
5882
Chris Lattner8f663e82005-10-29 04:36:15 +00005883 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005884 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005885 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5886 Amt = InsertNewInstBefore(Tmp, AI);
5887 }
5888
Chris Lattner216be912005-10-24 06:03:58 +00005889 AllocationInst *New;
5890 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00005891 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005892 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00005893 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005894 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005895 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005896
5897 // If the allocation has multiple uses, insert a cast and change all things
5898 // that used it to use the new cast. This will also hack on CI, but it will
5899 // die soon.
5900 if (!AI.hasOneUse()) {
5901 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005902 // New is the allocation instruction, pointer typed. AI is the original
5903 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5904 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005905 InsertNewInstBefore(NewCast, AI);
5906 AI.replaceAllUsesWith(NewCast);
5907 }
Chris Lattner216be912005-10-24 06:03:58 +00005908 return ReplaceInstUsesWith(CI, New);
5909}
5910
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005911/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005912/// and return it as type Ty without inserting any new casts and without
5913/// changing the computed value. This is used by code that tries to decide
5914/// whether promoting or shrinking integer operations to wider or smaller types
5915/// will allow us to eliminate a truncate or extend.
5916///
5917/// This is a truncation operation if Ty is smaller than V->getType(), or an
5918/// extension operation if Ty is larger.
5919static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005920 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005921 // We can always evaluate constants in another type.
5922 if (isa<ConstantInt>(V))
5923 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005924
5925 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005926 if (!I) return false;
5927
5928 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005929
5930 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005931 case Instruction::Add:
5932 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005933 case Instruction::And:
5934 case Instruction::Or:
5935 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005936 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005937 // These operators can all arbitrarily be extended or truncated.
5938 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5939 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005940
Chris Lattner960acb02006-11-29 07:18:39 +00005941 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005942 if (!I->hasOneUse()) return false;
5943 // If we are truncating the result of this SHL, and if it's a shift of a
5944 // constant amount, we can always perform a SHL in a smaller type.
5945 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5946 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5947 CI->getZExtValue() < Ty->getBitWidth())
5948 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
5949 }
5950 break;
5951 case Instruction::LShr:
5952 if (!I->hasOneUse()) return false;
5953 // If this is a truncate of a logical shr, we can truncate it to a smaller
5954 // lshr iff we know that the bits we would otherwise be shifting in are
5955 // already zeros.
5956 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5957 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5958 MaskedValueIsZero(I->getOperand(0),
5959 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
5960 CI->getZExtValue() < Ty->getBitWidth()) {
5961 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5962 }
5963 }
Chris Lattner960acb02006-11-29 07:18:39 +00005964 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005965 case Instruction::Trunc:
5966 case Instruction::ZExt:
5967 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005968 // If this is a cast from the destination type, we can trivially eliminate
5969 // it, and this will remove a cast overall.
5970 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005971 // If the first operand is itself a cast, and is eliminable, do not count
5972 // this as an eliminable cast. We would prefer to eliminate those two
5973 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005974 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005975 return true;
5976
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005977 ++NumCastsRemoved;
5978 return true;
5979 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005980 break;
5981 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005982 // TODO: Can handle more cases here.
5983 break;
5984 }
5985
5986 return false;
5987}
5988
5989/// EvaluateInDifferentType - Given an expression that
5990/// CanEvaluateInDifferentType returns true for, actually insert the code to
5991/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005992Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005993 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005994 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005995 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005996
5997 // Otherwise, it must be an instruction.
5998 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005999 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006000 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006001 case Instruction::Add:
6002 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006003 case Instruction::And:
6004 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006005 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006006 case Instruction::AShr:
6007 case Instruction::LShr:
6008 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006009 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006010 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6011 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6012 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006013 break;
6014 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006015 case Instruction::Trunc:
6016 case Instruction::ZExt:
6017 case Instruction::SExt:
6018 case Instruction::BitCast:
6019 // If the source type of the cast is the type we're trying for then we can
6020 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006021 if (I->getOperand(0)->getType() == Ty)
6022 return I->getOperand(0);
6023
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006024 // Some other kind of cast, which shouldn't happen, so just ..
6025 // FALL THROUGH
6026 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006027 // TODO: Can handle more cases here.
6028 assert(0 && "Unreachable!");
6029 break;
6030 }
6031
6032 return InsertNewInstBefore(Res, *I);
6033}
6034
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006035/// @brief Implement the transforms common to all CastInst visitors.
6036Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006037 Value *Src = CI.getOperand(0);
6038
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006039 // Casting undef to anything results in undef so might as just replace it and
6040 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006041 if (isa<UndefValue>(Src)) // cast undef -> undef
6042 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6043
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006044 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6045 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006046 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006047 if (Instruction::CastOps opc =
6048 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6049 // The first cast (CSrc) is eliminable so we need to fix up or replace
6050 // the second cast (CI). CSrc will then have a good chance of being dead.
6051 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006052 }
6053 }
Chris Lattner03841652004-05-25 04:29:21 +00006054
Chris Lattnerd0d51602003-06-21 23:12:02 +00006055 // If casting the result of a getelementptr instruction with no offset, turn
6056 // this into a cast of the original pointer!
6057 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006058 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006059 bool AllZeroOperands = true;
6060 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6061 if (!isa<Constant>(GEP->getOperand(i)) ||
6062 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6063 AllZeroOperands = false;
6064 break;
6065 }
6066 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006067 // Changing the cast operand is usually not a good idea but it is safe
6068 // here because the pointer operand is being replaced with another
6069 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006070 CI.setOperand(0, GEP->getOperand(0));
6071 return &CI;
6072 }
6073 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006074
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006075 // If we are casting a malloc or alloca to a pointer to a type of the same
6076 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006077 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006078 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6079 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006080
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006081 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006082 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6083 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6084 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006085
6086 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006087 if (isa<PHINode>(Src))
6088 if (Instruction *NV = FoldOpIntoPhi(CI))
6089 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006090
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006091 return 0;
6092}
6093
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006094/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6095/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006096/// cases.
6097/// @brief Implement the transforms common to CastInst with integer operands
6098Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6099 if (Instruction *Result = commonCastTransforms(CI))
6100 return Result;
6101
6102 Value *Src = CI.getOperand(0);
6103 const Type *SrcTy = Src->getType();
6104 const Type *DestTy = CI.getType();
6105 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6106 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6107
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006108 // See if we can simplify any instructions used by the LHS whose sole
6109 // purpose is to compute bits we don't care about.
6110 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006111 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006112 KnownZero, KnownOne))
6113 return &CI;
6114
6115 // If the source isn't an instruction or has more than one use then we
6116 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006117 Instruction *SrcI = dyn_cast<Instruction>(Src);
6118 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006119 return 0;
6120
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006121 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006122 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006123 if (!isa<BitCastInst>(CI) &&
6124 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6125 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006126 // If this cast is a truncate, evaluting in a different type always
6127 // eliminates the cast, so it is always a win. If this is a noop-cast
6128 // this just removes a noop cast which isn't pointful, but simplifies
6129 // the code. If this is a zero-extension, we need to do an AND to
6130 // maintain the clear top-part of the computation, so we require that
6131 // the input have eliminated at least one cast. If this is a sign
6132 // extension, we insert two new casts (to do the extension) so we
6133 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006134 bool DoXForm;
6135 switch (CI.getOpcode()) {
6136 default:
6137 // All the others use floating point so we shouldn't actually
6138 // get here because of the check above.
6139 assert(0 && "Unknown cast type");
6140 case Instruction::Trunc:
6141 DoXForm = true;
6142 break;
6143 case Instruction::ZExt:
6144 DoXForm = NumCastsRemoved >= 1;
6145 break;
6146 case Instruction::SExt:
6147 DoXForm = NumCastsRemoved >= 2;
6148 break;
6149 case Instruction::BitCast:
6150 DoXForm = false;
6151 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006152 }
6153
6154 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006155 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6156 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006157 assert(Res->getType() == DestTy);
6158 switch (CI.getOpcode()) {
6159 default: assert(0 && "Unknown cast type!");
6160 case Instruction::Trunc:
6161 case Instruction::BitCast:
6162 // Just replace this cast with the result.
6163 return ReplaceInstUsesWith(CI, Res);
6164 case Instruction::ZExt: {
6165 // We need to emit an AND to clear the high bits.
6166 assert(SrcBitSize < DestBitSize && "Not a zext?");
6167 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006168 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006169 if (DestBitSize < 64)
6170 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006171 return BinaryOperator::createAnd(Res, C);
6172 }
6173 case Instruction::SExt:
6174 // We need to emit a cast to truncate, then a cast to sext.
6175 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006176 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6177 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006178 }
6179 }
6180 }
6181
6182 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6183 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6184
6185 switch (SrcI->getOpcode()) {
6186 case Instruction::Add:
6187 case Instruction::Mul:
6188 case Instruction::And:
6189 case Instruction::Or:
6190 case Instruction::Xor:
6191 // If we are discarding information, or just changing the sign,
6192 // rewrite.
6193 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6194 // Don't insert two casts if they cannot be eliminated. We allow
6195 // two casts to be inserted if the sizes are the same. This could
6196 // only be converting signedness, which is a noop.
6197 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006198 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6199 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006200 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006201 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6202 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6203 return BinaryOperator::create(
6204 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006205 }
6206 }
6207
6208 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6209 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6210 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006211 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006212 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006213 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006214 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6215 }
6216 break;
6217 case Instruction::SDiv:
6218 case Instruction::UDiv:
6219 case Instruction::SRem:
6220 case Instruction::URem:
6221 // If we are just changing the sign, rewrite.
6222 if (DestBitSize == SrcBitSize) {
6223 // Don't insert two casts if they cannot be eliminated. We allow
6224 // two casts to be inserted if the sizes are the same. This could
6225 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006226 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6227 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006228 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6229 Op0, DestTy, SrcI);
6230 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6231 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006232 return BinaryOperator::create(
6233 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6234 }
6235 }
6236 break;
6237
6238 case Instruction::Shl:
6239 // Allow changing the sign of the source operand. Do not allow
6240 // changing the size of the shift, UNLESS the shift amount is a
6241 // constant. We must not change variable sized shifts to a smaller
6242 // size, because it is undefined to shift more bits out than exist
6243 // in the value.
6244 if (DestBitSize == SrcBitSize ||
6245 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006246 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6247 Instruction::BitCast : Instruction::Trunc);
6248 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006249 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006250 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006251 }
6252 break;
6253 case Instruction::AShr:
6254 // If this is a signed shr, and if all bits shifted in are about to be
6255 // truncated off, turn it into an unsigned shr to allow greater
6256 // simplifications.
6257 if (DestBitSize < SrcBitSize &&
6258 isa<ConstantInt>(Op1)) {
6259 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6260 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6261 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006262 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006263 }
6264 }
6265 break;
6266
Reid Spencer266e42b2006-12-23 06:05:41 +00006267 case Instruction::ICmp:
6268 // If we are just checking for a icmp eq of a single bit and casting it
6269 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006270 // cast to integer to avoid the comparison.
6271 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6272 uint64_t Op1CV = Op1C->getZExtValue();
6273 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6274 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6275 // cast (X == 1) to int --> X iff X has only the low bit set.
6276 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6277 // cast (X != 0) to int --> X iff X has only the low bit set.
6278 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6279 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6280 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6281 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6282 // If Op1C some other power of two, convert:
6283 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006284 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006285 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006286
6287 // This only works for EQ and NE
6288 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6289 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6290 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006291
6292 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006293 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006294 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6295 // (X&4) == 2 --> false
6296 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006297 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006298 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006299 return ReplaceInstUsesWith(CI, Res);
6300 }
6301
6302 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6303 Value *In = Op0;
6304 if (ShiftAmt) {
6305 // Perform a logical shr by shiftamt.
6306 // Insert the shift to put the result in the low bit.
6307 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006308 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006309 ConstantInt::get(In->getType(), ShiftAmt),
6310 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006311 }
6312
Reid Spencer266e42b2006-12-23 06:05:41 +00006313 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006314 Constant *One = ConstantInt::get(In->getType(), 1);
6315 In = BinaryOperator::createXor(In, One, "tmp");
6316 InsertNewInstBefore(cast<Instruction>(In), CI);
6317 }
6318
6319 if (CI.getType() == In->getType())
6320 return ReplaceInstUsesWith(CI, In);
6321 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006322 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006323 }
6324 }
6325 }
6326 break;
6327 }
6328 return 0;
6329}
6330
6331Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006332 if (Instruction *Result = commonIntCastTransforms(CI))
6333 return Result;
6334
6335 Value *Src = CI.getOperand(0);
6336 const Type *Ty = CI.getType();
6337 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6338
6339 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6340 switch (SrcI->getOpcode()) {
6341 default: break;
6342 case Instruction::LShr:
6343 // We can shrink lshr to something smaller if we know the bits shifted in
6344 // are already zeros.
6345 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6346 unsigned ShAmt = ShAmtV->getZExtValue();
6347
6348 // Get a mask for the bits shifting in.
6349 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006350 Value* SrcIOp0 = SrcI->getOperand(0);
6351 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006352 if (ShAmt >= DestBitWidth) // All zeros.
6353 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6354
6355 // Okay, we can shrink this. Truncate the input, then return a new
6356 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006357 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6358 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6359 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006360 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006361 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006362 } else { // This is a variable shr.
6363
6364 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6365 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6366 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006367 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006368 Value *One = ConstantInt::get(SrcI->getType(), 1);
6369
Reid Spencer2341c222007-02-02 02:16:23 +00006370 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006371 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006372 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006373 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6374 SrcI->getOperand(0),
6375 "tmp"), CI);
6376 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006377 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006378 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006379 }
6380 break;
6381 }
6382 }
6383
6384 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006385}
6386
6387Instruction *InstCombiner::visitZExt(CastInst &CI) {
6388 // If one of the common conversion will work ..
6389 if (Instruction *Result = commonIntCastTransforms(CI))
6390 return Result;
6391
6392 Value *Src = CI.getOperand(0);
6393
6394 // If this is a cast of a cast
6395 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006396 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6397 // types and if the sizes are just right we can convert this into a logical
6398 // 'and' which will be much cheaper than the pair of casts.
6399 if (isa<TruncInst>(CSrc)) {
6400 // Get the sizes of the types involved
6401 Value *A = CSrc->getOperand(0);
6402 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6403 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6404 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6405 // If we're actually extending zero bits and the trunc is a no-op
6406 if (MidSize < DstSize && SrcSize == DstSize) {
6407 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006408 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006409 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6410 Instruction *And =
6411 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6412 // Unfortunately, if the type changed, we need to cast it back.
6413 if (And->getType() != CI.getType()) {
6414 And->setName(CSrc->getName()+".mask");
6415 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006416 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006417 }
6418 return And;
6419 }
6420 }
6421 }
6422
6423 return 0;
6424}
6425
6426Instruction *InstCombiner::visitSExt(CastInst &CI) {
6427 return commonIntCastTransforms(CI);
6428}
6429
6430Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6431 return commonCastTransforms(CI);
6432}
6433
6434Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6435 return commonCastTransforms(CI);
6436}
6437
6438Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006439 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006440}
6441
6442Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006443 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006444}
6445
6446Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6447 return commonCastTransforms(CI);
6448}
6449
6450Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6451 return commonCastTransforms(CI);
6452}
6453
6454Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006455 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006456}
6457
6458Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6459 return commonCastTransforms(CI);
6460}
6461
6462Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6463
6464 // If the operands are integer typed then apply the integer transforms,
6465 // otherwise just apply the common ones.
6466 Value *Src = CI.getOperand(0);
6467 const Type *SrcTy = Src->getType();
6468 const Type *DestTy = CI.getType();
6469
Chris Lattner03c49532007-01-15 02:27:26 +00006470 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006471 if (Instruction *Result = commonIntCastTransforms(CI))
6472 return Result;
6473 } else {
6474 if (Instruction *Result = commonCastTransforms(CI))
6475 return Result;
6476 }
6477
6478
6479 // Get rid of casts from one type to the same type. These are useless and can
6480 // be replaced by the operand.
6481 if (DestTy == Src->getType())
6482 return ReplaceInstUsesWith(CI, Src);
6483
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006484 // If the source and destination are pointers, and this cast is equivalent to
6485 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6486 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006487 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6488 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6489 const Type *DstElTy = DstPTy->getElementType();
6490 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006491
Reid Spencerc635f472006-12-31 05:48:39 +00006492 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006493 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006494 while (SrcElTy != DstElTy &&
6495 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6496 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6497 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006498 ++NumZeros;
6499 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006500
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006501 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006502 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006503 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6504 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006505 }
6506 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006507 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006508
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006509 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6510 if (SVI->hasOneUse()) {
6511 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6512 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006513 if (isa<VectorType>(DestTy) &&
6514 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006515 SVI->getType()->getNumElements()) {
6516 CastInst *Tmp;
6517 // If either of the operands is a cast from CI.getType(), then
6518 // evaluating the shuffle in the casted destination's type will allow
6519 // us to eliminate at least one cast.
6520 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6521 Tmp->getOperand(0)->getType() == DestTy) ||
6522 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6523 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006524 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6525 SVI->getOperand(0), DestTy, &CI);
6526 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6527 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006528 // Return a new shuffle vector. Use the same element ID's, as we
6529 // know the vector types match #elts.
6530 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006531 }
6532 }
6533 }
6534 }
Chris Lattner260ab202002-04-18 17:39:14 +00006535 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006536}
6537
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006538/// GetSelectFoldableOperands - We want to turn code that looks like this:
6539/// %C = or %A, %B
6540/// %D = select %cond, %C, %A
6541/// into:
6542/// %C = select %cond, %B, 0
6543/// %D = or %A, %C
6544///
6545/// Assuming that the specified instruction is an operand to the select, return
6546/// a bitmask indicating which operands of this instruction are foldable if they
6547/// equal the other incoming value of the select.
6548///
6549static unsigned GetSelectFoldableOperands(Instruction *I) {
6550 switch (I->getOpcode()) {
6551 case Instruction::Add:
6552 case Instruction::Mul:
6553 case Instruction::And:
6554 case Instruction::Or:
6555 case Instruction::Xor:
6556 return 3; // Can fold through either operand.
6557 case Instruction::Sub: // Can only fold on the amount subtracted.
6558 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006559 case Instruction::LShr:
6560 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006561 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006562 default:
6563 return 0; // Cannot fold
6564 }
6565}
6566
6567/// GetSelectFoldableConstant - For the same transformation as the previous
6568/// function, return the identity constant that goes into the select.
6569static Constant *GetSelectFoldableConstant(Instruction *I) {
6570 switch (I->getOpcode()) {
6571 default: assert(0 && "This cannot happen!"); abort();
6572 case Instruction::Add:
6573 case Instruction::Sub:
6574 case Instruction::Or:
6575 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006576 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006577 case Instruction::LShr:
6578 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006579 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006580 case Instruction::And:
6581 return ConstantInt::getAllOnesValue(I->getType());
6582 case Instruction::Mul:
6583 return ConstantInt::get(I->getType(), 1);
6584 }
6585}
6586
Chris Lattner411336f2005-01-19 21:50:18 +00006587/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6588/// have the same opcode and only one use each. Try to simplify this.
6589Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6590 Instruction *FI) {
6591 if (TI->getNumOperands() == 1) {
6592 // If this is a non-volatile load or a cast from the same type,
6593 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006594 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006595 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6596 return 0;
6597 } else {
6598 return 0; // unknown unary op.
6599 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006600
Chris Lattner411336f2005-01-19 21:50:18 +00006601 // Fold this by inserting a select from the input values.
6602 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6603 FI->getOperand(0), SI.getName()+".v");
6604 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006605 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6606 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006607 }
6608
Reid Spencer2341c222007-02-02 02:16:23 +00006609 // Only handle binary operators here.
6610 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006611 return 0;
6612
6613 // Figure out if the operations have any operands in common.
6614 Value *MatchOp, *OtherOpT, *OtherOpF;
6615 bool MatchIsOpZero;
6616 if (TI->getOperand(0) == FI->getOperand(0)) {
6617 MatchOp = TI->getOperand(0);
6618 OtherOpT = TI->getOperand(1);
6619 OtherOpF = FI->getOperand(1);
6620 MatchIsOpZero = true;
6621 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6622 MatchOp = TI->getOperand(1);
6623 OtherOpT = TI->getOperand(0);
6624 OtherOpF = FI->getOperand(0);
6625 MatchIsOpZero = false;
6626 } else if (!TI->isCommutative()) {
6627 return 0;
6628 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6629 MatchOp = TI->getOperand(0);
6630 OtherOpT = TI->getOperand(1);
6631 OtherOpF = FI->getOperand(0);
6632 MatchIsOpZero = true;
6633 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6634 MatchOp = TI->getOperand(1);
6635 OtherOpT = TI->getOperand(0);
6636 OtherOpF = FI->getOperand(1);
6637 MatchIsOpZero = true;
6638 } else {
6639 return 0;
6640 }
6641
6642 // If we reach here, they do have operations in common.
6643 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6644 OtherOpF, SI.getName()+".v");
6645 InsertNewInstBefore(NewSI, SI);
6646
6647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6648 if (MatchIsOpZero)
6649 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6650 else
6651 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006652 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006653 assert(0 && "Shouldn't get here");
6654 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006655}
6656
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006657Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006658 Value *CondVal = SI.getCondition();
6659 Value *TrueVal = SI.getTrueValue();
6660 Value *FalseVal = SI.getFalseValue();
6661
6662 // select true, X, Y -> X
6663 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006664 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006665 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006666
6667 // select C, X, X -> X
6668 if (TrueVal == FalseVal)
6669 return ReplaceInstUsesWith(SI, TrueVal);
6670
Chris Lattner81a7a232004-10-16 18:11:37 +00006671 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6672 return ReplaceInstUsesWith(SI, FalseVal);
6673 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6674 return ReplaceInstUsesWith(SI, TrueVal);
6675 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6676 if (isa<Constant>(TrueVal))
6677 return ReplaceInstUsesWith(SI, TrueVal);
6678 else
6679 return ReplaceInstUsesWith(SI, FalseVal);
6680 }
6681
Reid Spencer542964f2007-01-11 18:21:29 +00006682 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006683 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006684 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006685 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006686 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006687 } else {
6688 // Change: A = select B, false, C --> A = and !B, C
6689 Value *NotCond =
6690 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6691 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006692 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006693 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006694 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006695 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006696 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006697 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006698 } else {
6699 // Change: A = select B, C, true --> A = or !B, C
6700 Value *NotCond =
6701 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6702 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006703 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006704 }
6705 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006706 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006707
Chris Lattner183b3362004-04-09 19:05:30 +00006708 // Selecting between two integer constants?
6709 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6710 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6711 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006712 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006713 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006714 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006715 // select C, 0, 1 -> cast !C to int
6716 Value *NotCond =
6717 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006718 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006719 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006720 }
Chris Lattner35167c32004-06-09 07:59:58 +00006721
Reid Spencer266e42b2006-12-23 06:05:41 +00006722 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006723
Reid Spencer266e42b2006-12-23 06:05:41 +00006724 // (x <s 0) ? -1 : 0 -> ashr x, 31
6725 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006726 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6727 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6728 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006729 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006730 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006731 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006732 else {
6733 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006734 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006735 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006736 }
6737
6738 if (CanXForm) {
6739 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006740 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006741 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006742 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006743 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6744 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6745 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006746 InsertNewInstBefore(SRA, SI);
6747
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006748 // Finally, convert to the type of the select RHS. We figure out
6749 // if this requires a SExt, Trunc or BitCast based on the sizes.
6750 Instruction::CastOps opc = Instruction::BitCast;
6751 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6752 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6753 if (SRASize < SISize)
6754 opc = Instruction::SExt;
6755 else if (SRASize > SISize)
6756 opc = Instruction::Trunc;
6757 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006758 }
6759 }
6760
6761
6762 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006763 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006764 // non-constant value, eliminate this whole mess. This corresponds to
6765 // cases like this: ((X & 27) ? 27 : 0)
6766 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006767 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006768 cast<Constant>(IC->getOperand(1))->isNullValue())
6769 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6770 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006771 isa<ConstantInt>(ICA->getOperand(1)) &&
6772 (ICA->getOperand(1) == TrueValC ||
6773 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006774 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6775 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006776 // know whether we have a icmp_ne or icmp_eq and whether the
6777 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006778 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006779 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006780 Value *V = ICA;
6781 if (ShouldNotVal)
6782 V = InsertNewInstBefore(BinaryOperator::create(
6783 Instruction::Xor, V, ICA->getOperand(1)), SI);
6784 return ReplaceInstUsesWith(SI, V);
6785 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006786 }
Chris Lattner533bc492004-03-30 19:37:13 +00006787 }
Chris Lattner623fba12004-04-10 22:21:27 +00006788
6789 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006790 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6791 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006792 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006793 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006794 return ReplaceInstUsesWith(SI, FalseVal);
6795 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006796 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006797 return ReplaceInstUsesWith(SI, TrueVal);
6798 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6799
Reid Spencer266e42b2006-12-23 06:05:41 +00006800 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006801 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006802 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006803 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006804 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006805 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6806 return ReplaceInstUsesWith(SI, TrueVal);
6807 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6808 }
6809 }
6810
6811 // See if we are selecting two values based on a comparison of the two values.
6812 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6813 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6814 // Transform (X == Y) ? X : Y -> Y
6815 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6816 return ReplaceInstUsesWith(SI, FalseVal);
6817 // Transform (X != Y) ? X : Y -> X
6818 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6819 return ReplaceInstUsesWith(SI, TrueVal);
6820 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6821
6822 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6823 // Transform (X == Y) ? Y : X -> X
6824 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6825 return ReplaceInstUsesWith(SI, FalseVal);
6826 // Transform (X != Y) ? Y : X -> Y
6827 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006828 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006829 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6830 }
6831 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006832
Chris Lattnera04c9042005-01-13 22:52:24 +00006833 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6834 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6835 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006836 Instruction *AddOp = 0, *SubOp = 0;
6837
Chris Lattner411336f2005-01-19 21:50:18 +00006838 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6839 if (TI->getOpcode() == FI->getOpcode())
6840 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6841 return IV;
6842
6843 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6844 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006845 if (TI->getOpcode() == Instruction::Sub &&
6846 FI->getOpcode() == Instruction::Add) {
6847 AddOp = FI; SubOp = TI;
6848 } else if (FI->getOpcode() == Instruction::Sub &&
6849 TI->getOpcode() == Instruction::Add) {
6850 AddOp = TI; SubOp = FI;
6851 }
6852
6853 if (AddOp) {
6854 Value *OtherAddOp = 0;
6855 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6856 OtherAddOp = AddOp->getOperand(1);
6857 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6858 OtherAddOp = AddOp->getOperand(0);
6859 }
6860
6861 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006862 // So at this point we know we have (Y -> OtherAddOp):
6863 // select C, (add X, Y), (sub X, Z)
6864 Value *NegVal; // Compute -Z
6865 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6866 NegVal = ConstantExpr::getNeg(C);
6867 } else {
6868 NegVal = InsertNewInstBefore(
6869 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006870 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006871
6872 Value *NewTrueOp = OtherAddOp;
6873 Value *NewFalseOp = NegVal;
6874 if (AddOp != TI)
6875 std::swap(NewTrueOp, NewFalseOp);
6876 Instruction *NewSel =
6877 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6878
6879 NewSel = InsertNewInstBefore(NewSel, SI);
6880 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006881 }
6882 }
6883 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006884
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006885 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006886 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006887 // See the comment above GetSelectFoldableOperands for a description of the
6888 // transformation we are doing here.
6889 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6890 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6891 !isa<Constant>(FalseVal))
6892 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6893 unsigned OpToFold = 0;
6894 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6895 OpToFold = 1;
6896 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6897 OpToFold = 2;
6898 }
6899
6900 if (OpToFold) {
6901 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006902 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006903 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006904 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006905 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006906 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6907 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006908 else {
6909 assert(0 && "Unknown instruction!!");
6910 }
6911 }
6912 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006913
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006914 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6915 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6916 !isa<Constant>(TrueVal))
6917 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6918 unsigned OpToFold = 0;
6919 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6920 OpToFold = 1;
6921 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6922 OpToFold = 2;
6923 }
6924
6925 if (OpToFold) {
6926 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006927 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006928 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006929 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006930 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006931 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6932 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00006933 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006934 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006935 }
6936 }
6937 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006938
6939 if (BinaryOperator::isNot(CondVal)) {
6940 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6941 SI.setOperand(1, FalseVal);
6942 SI.setOperand(2, TrueVal);
6943 return &SI;
6944 }
6945
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006946 return 0;
6947}
6948
Chris Lattner82f2ef22006-03-06 20:18:44 +00006949/// GetKnownAlignment - If the specified pointer has an alignment that we can
6950/// determine, return it, otherwise return 0.
6951static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6952 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6953 unsigned Align = GV->getAlignment();
6954 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00006955 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006956 return Align;
6957 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6958 unsigned Align = AI->getAlignment();
6959 if (Align == 0 && TD) {
6960 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00006961 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006962 else if (isa<MallocInst>(AI)) {
6963 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00006964 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00006965 Align =
6966 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00006967 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00006968 Align =
6969 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00006970 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006971 }
6972 }
6973 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006974 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006975 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006976 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006977 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006978 if (isa<PointerType>(CI->getOperand(0)->getType()))
6979 return GetKnownAlignment(CI->getOperand(0), TD);
6980 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006981 } else if (isa<GetElementPtrInst>(V) ||
6982 (isa<ConstantExpr>(V) &&
6983 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6984 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006985 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6986 if (BaseAlignment == 0) return 0;
6987
6988 // If all indexes are zero, it is just the alignment of the base pointer.
6989 bool AllZeroOperands = true;
6990 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6991 if (!isa<Constant>(GEPI->getOperand(i)) ||
6992 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6993 AllZeroOperands = false;
6994 break;
6995 }
6996 if (AllZeroOperands)
6997 return BaseAlignment;
6998
6999 // Otherwise, if the base alignment is >= the alignment we expect for the
7000 // base pointer type, then we know that the resultant pointer is aligned at
7001 // least as much as its type requires.
7002 if (!TD) return 0;
7003
7004 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007005 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007006 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007007 <= BaseAlignment) {
7008 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007009 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007010 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007011 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007012 return 0;
7013 }
7014 return 0;
7015}
7016
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007017
Chris Lattnerc66b2232006-01-13 20:11:04 +00007018/// visitCallInst - CallInst simplification. This mostly only handles folding
7019/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7020/// the heavy lifting.
7021///
Chris Lattner970c33a2003-06-19 17:00:31 +00007022Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007023 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7024 if (!II) return visitCallSite(&CI);
7025
Chris Lattner51ea1272004-02-28 05:22:00 +00007026 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7027 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007028 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007029 bool Changed = false;
7030
7031 // memmove/cpy/set of zero bytes is a noop.
7032 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7033 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7034
Chris Lattner00648e12004-10-12 04:52:52 +00007035 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007036 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007037 // Replace the instruction with just byte operations. We would
7038 // transform other cases to loads/stores, but we don't know if
7039 // alignment is sufficient.
7040 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007041 }
7042
Chris Lattner00648e12004-10-12 04:52:52 +00007043 // If we have a memmove and the source operation is a constant global,
7044 // then the source and dest pointers can't alias, so we can change this
7045 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007046 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007047 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7048 if (GVSrc->isConstant()) {
7049 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007050 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007051 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007052 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007053 Name = "llvm.memcpy.i32";
7054 else
7055 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007056 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007057 CI.getCalledFunction()->getFunctionType());
7058 CI.setOperand(0, MemCpy);
7059 Changed = true;
7060 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007061 }
Chris Lattner00648e12004-10-12 04:52:52 +00007062
Chris Lattner82f2ef22006-03-06 20:18:44 +00007063 // If we can determine a pointer alignment that is bigger than currently
7064 // set, update the alignment.
7065 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7066 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7067 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7068 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007069 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007070 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007071 Changed = true;
7072 }
7073 } else if (isa<MemSetInst>(MI)) {
7074 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007075 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007076 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007077 Changed = true;
7078 }
7079 }
7080
Chris Lattnerc66b2232006-01-13 20:11:04 +00007081 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007082 } else {
7083 switch (II->getIntrinsicID()) {
7084 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007085 case Intrinsic::ppc_altivec_lvx:
7086 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007087 case Intrinsic::x86_sse_loadu_ps:
7088 case Intrinsic::x86_sse2_loadu_pd:
7089 case Intrinsic::x86_sse2_loadu_dq:
7090 // Turn PPC lvx -> load if the pointer is known aligned.
7091 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007092 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007093 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007094 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007095 return new LoadInst(Ptr);
7096 }
7097 break;
7098 case Intrinsic::ppc_altivec_stvx:
7099 case Intrinsic::ppc_altivec_stvxl:
7100 // Turn stvx -> store if the pointer is known aligned.
7101 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007102 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007103 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7104 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007105 return new StoreInst(II->getOperand(1), Ptr);
7106 }
7107 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007108 case Intrinsic::x86_sse_storeu_ps:
7109 case Intrinsic::x86_sse2_storeu_pd:
7110 case Intrinsic::x86_sse2_storeu_dq:
7111 case Intrinsic::x86_sse2_storel_dq:
7112 // Turn X86 storeu -> store if the pointer is known aligned.
7113 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7114 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007115 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7116 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007117 return new StoreInst(II->getOperand(2), Ptr);
7118 }
7119 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007120
7121 case Intrinsic::x86_sse_cvttss2si: {
7122 // These intrinsics only demands the 0th element of its input vector. If
7123 // we can simplify the input based on that, do so now.
7124 uint64_t UndefElts;
7125 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7126 UndefElts)) {
7127 II->setOperand(1, V);
7128 return II;
7129 }
7130 break;
7131 }
7132
Chris Lattnere79d2492006-04-06 19:19:17 +00007133 case Intrinsic::ppc_altivec_vperm:
7134 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007135 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007136 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7137
7138 // Check that all of the elements are integer constants or undefs.
7139 bool AllEltsOk = true;
7140 for (unsigned i = 0; i != 16; ++i) {
7141 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7142 !isa<UndefValue>(Mask->getOperand(i))) {
7143 AllEltsOk = false;
7144 break;
7145 }
7146 }
7147
7148 if (AllEltsOk) {
7149 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007150 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7151 II->getOperand(1), Mask->getType(), CI);
7152 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7153 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007154 Value *Result = UndefValue::get(Op0->getType());
7155
7156 // Only extract each element once.
7157 Value *ExtractedElts[32];
7158 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7159
7160 for (unsigned i = 0; i != 16; ++i) {
7161 if (isa<UndefValue>(Mask->getOperand(i)))
7162 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007163 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007164 Idx &= 31; // Match the hardware behavior.
7165
7166 if (ExtractedElts[Idx] == 0) {
7167 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007168 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007169 InsertNewInstBefore(Elt, CI);
7170 ExtractedElts[Idx] = Elt;
7171 }
7172
7173 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007174 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007175 InsertNewInstBefore(cast<Instruction>(Result), CI);
7176 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007177 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007178 }
7179 }
7180 break;
7181
Chris Lattner503221f2006-01-13 21:28:09 +00007182 case Intrinsic::stackrestore: {
7183 // If the save is right next to the restore, remove the restore. This can
7184 // happen when variable allocas are DCE'd.
7185 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7186 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7187 BasicBlock::iterator BI = SS;
7188 if (&*++BI == II)
7189 return EraseInstFromFunction(CI);
7190 }
7191 }
7192
7193 // If the stack restore is in a return/unwind block and if there are no
7194 // allocas or calls between the restore and the return, nuke the restore.
7195 TerminatorInst *TI = II->getParent()->getTerminator();
7196 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7197 BasicBlock::iterator BI = II;
7198 bool CannotRemove = false;
7199 for (++BI; &*BI != TI; ++BI) {
7200 if (isa<AllocaInst>(BI) ||
7201 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7202 CannotRemove = true;
7203 break;
7204 }
7205 }
7206 if (!CannotRemove)
7207 return EraseInstFromFunction(CI);
7208 }
7209 break;
7210 }
7211 }
Chris Lattner00648e12004-10-12 04:52:52 +00007212 }
7213
Chris Lattnerc66b2232006-01-13 20:11:04 +00007214 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007215}
7216
7217// InvokeInst simplification
7218//
7219Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007220 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007221}
7222
Chris Lattneraec3d942003-10-07 22:32:43 +00007223// visitCallSite - Improvements for call and invoke instructions.
7224//
7225Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007226 bool Changed = false;
7227
7228 // If the callee is a constexpr cast of a function, attempt to move the cast
7229 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007230 if (transformConstExprCastCall(CS)) return 0;
7231
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007232 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007233
Chris Lattner61d9d812005-05-13 07:09:09 +00007234 if (Function *CalleeF = dyn_cast<Function>(Callee))
7235 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7236 Instruction *OldCall = CS.getInstruction();
7237 // If the call and callee calling conventions don't match, this call must
7238 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007239 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007240 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007241 if (!OldCall->use_empty())
7242 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7243 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7244 return EraseInstFromFunction(*OldCall);
7245 return 0;
7246 }
7247
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007248 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7249 // This instruction is not reachable, just remove it. We insert a store to
7250 // undef so that we know that this code is not reachable, despite the fact
7251 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007252 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007253 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007254 CS.getInstruction());
7255
7256 if (!CS.getInstruction()->use_empty())
7257 CS.getInstruction()->
7258 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7259
7260 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7261 // Don't break the CFG, insert a dummy cond branch.
7262 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007263 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007264 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007265 return EraseInstFromFunction(*CS.getInstruction());
7266 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007267
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007268 const PointerType *PTy = cast<PointerType>(Callee->getType());
7269 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7270 if (FTy->isVarArg()) {
7271 // See if we can optimize any arguments passed through the varargs area of
7272 // the call.
7273 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7274 E = CS.arg_end(); I != E; ++I)
7275 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7276 // If this cast does not effect the value passed through the varargs
7277 // area, we can eliminate the use of the cast.
7278 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007279 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007280 *I = Op;
7281 Changed = true;
7282 }
7283 }
7284 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007285
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007286 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007287}
7288
Chris Lattner970c33a2003-06-19 17:00:31 +00007289// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7290// attempt to move the cast to the arguments of the call/invoke.
7291//
7292bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7293 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7294 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007295 if (CE->getOpcode() != Instruction::BitCast ||
7296 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007297 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007298 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007299 Instruction *Caller = CS.getInstruction();
7300
7301 // Okay, this is a cast from a function to a different type. Unless doing so
7302 // would cause a type conversion of one of our arguments, change this call to
7303 // be a direct call with arguments casted to the appropriate types.
7304 //
7305 const FunctionType *FT = Callee->getFunctionType();
7306 const Type *OldRetTy = Caller->getType();
7307
Chris Lattner1f7942f2004-01-14 06:06:08 +00007308 // Check to see if we are changing the return type...
7309 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007310 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007311 OldRetTy != FT->getReturnType() &&
7312 // Conversion is ok if changing from pointer to int of same size.
7313 !(isa<PointerType>(FT->getReturnType()) &&
7314 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007315 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007316
7317 // If the callsite is an invoke instruction, and the return value is used by
7318 // a PHI node in a successor, we cannot change the return type of the call
7319 // because there is no place to put the cast instruction (without breaking
7320 // the critical edge). Bail out in this case.
7321 if (!Caller->use_empty())
7322 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7323 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7324 UI != E; ++UI)
7325 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7326 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007327 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007328 return false;
7329 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007330
7331 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7332 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007333
Chris Lattner970c33a2003-06-19 17:00:31 +00007334 CallSite::arg_iterator AI = CS.arg_begin();
7335 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7336 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007337 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007338 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007339 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007340 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007341 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007342 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007343 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7344 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7345 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007346 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007347 }
7348
7349 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007350 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007351 return false; // Do not delete arguments unless we have a function body...
7352
7353 // Okay, we decided that this is a safe thing to do: go ahead and start
7354 // inserting cast instructions as necessary...
7355 std::vector<Value*> Args;
7356 Args.reserve(NumActualArgs);
7357
7358 AI = CS.arg_begin();
7359 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7360 const Type *ParamTy = FT->getParamType(i);
7361 if ((*AI)->getType() == ParamTy) {
7362 Args.push_back(*AI);
7363 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007364 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007365 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007366 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007367 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007368 }
7369 }
7370
7371 // If the function takes more arguments than the call was taking, add them
7372 // now...
7373 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7374 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7375
7376 // If we are removing arguments to the function, emit an obnoxious warning...
7377 if (FT->getNumParams() < NumActualArgs)
7378 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007379 cerr << "WARNING: While resolving call to function '"
7380 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007381 } else {
7382 // Add all of the arguments in their promoted form to the arg list...
7383 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7384 const Type *PTy = getPromotedType((*AI)->getType());
7385 if (PTy != (*AI)->getType()) {
7386 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007387 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7388 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007389 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007390 InsertNewInstBefore(Cast, *Caller);
7391 Args.push_back(Cast);
7392 } else {
7393 Args.push_back(*AI);
7394 }
7395 }
7396 }
7397
7398 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007399 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007400
7401 Instruction *NC;
7402 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007403 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007404 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007405 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007406 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007407 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007408 if (cast<CallInst>(Caller)->isTailCall())
7409 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007410 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007411 }
7412
Chris Lattner6e0123b2007-02-11 01:23:03 +00007413 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007414 Value *NV = NC;
7415 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7416 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007417 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007418 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7419 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007420 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007421
7422 // If this is an invoke instruction, we should insert it after the first
7423 // non-phi, instruction in the normal successor block.
7424 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7425 BasicBlock::iterator I = II->getNormalDest()->begin();
7426 while (isa<PHINode>(I)) ++I;
7427 InsertNewInstBefore(NC, *I);
7428 } else {
7429 // Otherwise, it's a call, just insert cast right after the call instr
7430 InsertNewInstBefore(NC, *Caller);
7431 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007432 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007433 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007434 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007435 }
7436 }
7437
7438 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7439 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007440 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007441 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007442 return true;
7443}
7444
Chris Lattnercadac0c2006-11-01 04:51:18 +00007445/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7446/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7447/// and a single binop.
7448Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7449 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007450 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7451 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007452 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007453 Value *LHSVal = FirstInst->getOperand(0);
7454 Value *RHSVal = FirstInst->getOperand(1);
7455
7456 const Type *LHSType = LHSVal->getType();
7457 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007458
7459 // Scan to see if all operands are the same opcode, all have one use, and all
7460 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007461 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007462 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007463 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007464 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007465 // types or GEP's with different index types.
7466 I->getOperand(0)->getType() != LHSType ||
7467 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007468 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007469
7470 // If they are CmpInst instructions, check their predicates
7471 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7472 if (cast<CmpInst>(I)->getPredicate() !=
7473 cast<CmpInst>(FirstInst)->getPredicate())
7474 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007475
7476 // Keep track of which operand needs a phi node.
7477 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7478 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007479 }
7480
Chris Lattner4f218d52006-11-08 19:42:28 +00007481 // Otherwise, this is safe to transform, determine if it is profitable.
7482
7483 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7484 // Indexes are often folded into load/store instructions, so we don't want to
7485 // hide them behind a phi.
7486 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7487 return 0;
7488
Chris Lattnercadac0c2006-11-01 04:51:18 +00007489 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007490 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007491 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007492 if (LHSVal == 0) {
7493 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7494 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7495 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007496 InsertNewInstBefore(NewLHS, PN);
7497 LHSVal = NewLHS;
7498 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007499
7500 if (RHSVal == 0) {
7501 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7502 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7503 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007504 InsertNewInstBefore(NewRHS, PN);
7505 RHSVal = NewRHS;
7506 }
7507
Chris Lattnercd62f112006-11-08 19:29:23 +00007508 // Add all operands to the new PHIs.
7509 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7510 if (NewLHS) {
7511 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7512 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7513 }
7514 if (NewRHS) {
7515 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7516 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7517 }
7518 }
7519
Chris Lattnercadac0c2006-11-01 04:51:18 +00007520 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007521 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007522 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7523 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7524 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007525 else {
7526 assert(isa<GetElementPtrInst>(FirstInst));
7527 return new GetElementPtrInst(LHSVal, RHSVal);
7528 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007529}
7530
Chris Lattner14f82c72006-11-01 07:13:54 +00007531/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7532/// of the block that defines it. This means that it must be obvious the value
7533/// of the load is not changed from the point of the load to the end of the
7534/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007535///
7536/// Finally, it is safe, but not profitable, to sink a load targetting a
7537/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7538/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007539static bool isSafeToSinkLoad(LoadInst *L) {
7540 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7541
7542 for (++BBI; BBI != E; ++BBI)
7543 if (BBI->mayWriteToMemory())
7544 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007545
7546 // Check for non-address taken alloca. If not address-taken already, it isn't
7547 // profitable to do this xform.
7548 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7549 bool isAddressTaken = false;
7550 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7551 UI != E; ++UI) {
7552 if (isa<LoadInst>(UI)) continue;
7553 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7554 // If storing TO the alloca, then the address isn't taken.
7555 if (SI->getOperand(1) == AI) continue;
7556 }
7557 isAddressTaken = true;
7558 break;
7559 }
7560
7561 if (!isAddressTaken)
7562 return false;
7563 }
7564
Chris Lattner14f82c72006-11-01 07:13:54 +00007565 return true;
7566}
7567
Chris Lattner970c33a2003-06-19 17:00:31 +00007568
Chris Lattner7515cab2004-11-14 19:13:23 +00007569// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7570// operator and they all are only used by the PHI, PHI together their
7571// inputs, and do the operation once, to the result of the PHI.
7572Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7573 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7574
7575 // Scan the instruction, looking for input operations that can be folded away.
7576 // If all input operands to the phi are the same instruction (e.g. a cast from
7577 // the same type or "+42") we can pull the operation through the PHI, reducing
7578 // code size and simplifying code.
7579 Constant *ConstantOp = 0;
7580 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007581 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007582 if (isa<CastInst>(FirstInst)) {
7583 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007584 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007585 // Can fold binop, compare or shift here if the RHS is a constant,
7586 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007587 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007588 if (ConstantOp == 0)
7589 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007590 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7591 isVolatile = LI->isVolatile();
7592 // We can't sink the load if the loaded value could be modified between the
7593 // load and the PHI.
7594 if (LI->getParent() != PN.getIncomingBlock(0) ||
7595 !isSafeToSinkLoad(LI))
7596 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007597 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007598 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007599 return FoldPHIArgBinOpIntoPHI(PN);
7600 // Can't handle general GEPs yet.
7601 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007602 } else {
7603 return 0; // Cannot fold this operation.
7604 }
7605
7606 // Check to see if all arguments are the same operation.
7607 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7608 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7609 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007610 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007611 return 0;
7612 if (CastSrcTy) {
7613 if (I->getOperand(0)->getType() != CastSrcTy)
7614 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007615 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007616 // We can't sink the load if the loaded value could be modified between
7617 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007618 if (LI->isVolatile() != isVolatile ||
7619 LI->getParent() != PN.getIncomingBlock(i) ||
7620 !isSafeToSinkLoad(LI))
7621 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007622 } else if (I->getOperand(1) != ConstantOp) {
7623 return 0;
7624 }
7625 }
7626
7627 // Okay, they are all the same operation. Create a new PHI node of the
7628 // correct type, and PHI together all of the LHS's of the instructions.
7629 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7630 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007631 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007632
7633 Value *InVal = FirstInst->getOperand(0);
7634 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007635
7636 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007637 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7638 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7639 if (NewInVal != InVal)
7640 InVal = 0;
7641 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7642 }
7643
7644 Value *PhiVal;
7645 if (InVal) {
7646 // The new PHI unions all of the same values together. This is really
7647 // common, so we handle it intelligently here for compile-time speed.
7648 PhiVal = InVal;
7649 delete NewPN;
7650 } else {
7651 InsertNewInstBefore(NewPN, PN);
7652 PhiVal = NewPN;
7653 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007654
Chris Lattner7515cab2004-11-14 19:13:23 +00007655 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007656 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7657 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007658 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007659 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007660 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007661 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007662 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7663 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7664 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007665 else
Reid Spencer2341c222007-02-02 02:16:23 +00007666 assert(0 && "Unknown operation");
Chris Lattner7515cab2004-11-14 19:13:23 +00007667}
Chris Lattner48a44f72002-05-02 17:06:02 +00007668
Chris Lattner71536432005-01-17 05:10:15 +00007669/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7670/// that is dead.
7671static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7672 if (PN->use_empty()) return true;
7673 if (!PN->hasOneUse()) return false;
7674
7675 // Remember this node, and if we find the cycle, return.
7676 if (!PotentiallyDeadPHIs.insert(PN).second)
7677 return true;
7678
7679 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7680 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007681
Chris Lattner71536432005-01-17 05:10:15 +00007682 return false;
7683}
7684
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007685// PHINode simplification
7686//
Chris Lattner113f4f42002-06-25 16:13:24 +00007687Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007688 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007689 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007690
Owen Andersonae8aa642006-07-10 22:03:18 +00007691 if (Value *V = PN.hasConstantValue())
7692 return ReplaceInstUsesWith(PN, V);
7693
Owen Andersonae8aa642006-07-10 22:03:18 +00007694 // If all PHI operands are the same operation, pull them through the PHI,
7695 // reducing code size.
7696 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7697 PN.getIncomingValue(0)->hasOneUse())
7698 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7699 return Result;
7700
7701 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7702 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7703 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007704 if (PN.hasOneUse()) {
7705 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7706 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007707 std::set<PHINode*> PotentiallyDeadPHIs;
7708 PotentiallyDeadPHIs.insert(&PN);
7709 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7710 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7711 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007712
7713 // If this phi has a single use, and if that use just computes a value for
7714 // the next iteration of a loop, delete the phi. This occurs with unused
7715 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7716 // common case here is good because the only other things that catch this
7717 // are induction variable analysis (sometimes) and ADCE, which is only run
7718 // late.
7719 if (PHIUser->hasOneUse() &&
7720 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7721 PHIUser->use_back() == &PN) {
7722 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7723 }
7724 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007725
Chris Lattner91daeb52003-12-19 05:58:40 +00007726 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007727}
7728
Reid Spencer13bc5d72006-12-12 09:18:51 +00007729static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7730 Instruction *InsertPoint,
7731 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007732 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7733 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007734 // We must cast correctly to the pointer type. Ensure that we
7735 // sign extend the integer value if it is smaller as this is
7736 // used for address computation.
7737 Instruction::CastOps opcode =
7738 (VTySize < PtrSize ? Instruction::SExt :
7739 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7740 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007741}
7742
Chris Lattner48a44f72002-05-02 17:06:02 +00007743
Chris Lattner113f4f42002-06-25 16:13:24 +00007744Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007745 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007746 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007747 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007748 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007749 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007750
Chris Lattner81a7a232004-10-16 18:11:37 +00007751 if (isa<UndefValue>(GEP.getOperand(0)))
7752 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7753
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007754 bool HasZeroPointerIndex = false;
7755 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7756 HasZeroPointerIndex = C->isNullValue();
7757
7758 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007759 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007760
Chris Lattner69193f92004-04-05 01:30:19 +00007761 // Eliminate unneeded casts for indices.
7762 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007763 gep_type_iterator GTI = gep_type_begin(GEP);
7764 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7765 if (isa<SequentialType>(*GTI)) {
7766 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007767 if (CI->getOpcode() == Instruction::ZExt ||
7768 CI->getOpcode() == Instruction::SExt) {
7769 const Type *SrcTy = CI->getOperand(0)->getType();
7770 // We can eliminate a cast from i32 to i64 iff the target
7771 // is a 32-bit pointer target.
7772 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7773 MadeChange = true;
7774 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007775 }
7776 }
7777 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007778 // If we are using a wider index than needed for this platform, shrink it
7779 // to what we need. If the incoming value needs a cast instruction,
7780 // insert it. This explicit cast can make subsequent optimizations more
7781 // obvious.
7782 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007783 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007784 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007785 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007786 MadeChange = true;
7787 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007788 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7789 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007790 GEP.setOperand(i, Op);
7791 MadeChange = true;
7792 }
Chris Lattner69193f92004-04-05 01:30:19 +00007793 }
7794 if (MadeChange) return &GEP;
7795
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007796 // Combine Indices - If the source pointer to this getelementptr instruction
7797 // is a getelementptr instruction, combine the indices of the two
7798 // getelementptr instructions into a single instruction.
7799 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007800 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007801 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007802 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007803
7804 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007805 // Note that if our source is a gep chain itself that we wait for that
7806 // chain to be resolved before we perform this transformation. This
7807 // avoids us creating a TON of code in some cases.
7808 //
7809 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7810 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7811 return 0; // Wait until our source is folded to completion.
7812
Chris Lattneraf6094f2007-02-15 22:48:32 +00007813 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007814
7815 // Find out whether the last index in the source GEP is a sequential idx.
7816 bool EndsWithSequential = false;
7817 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7818 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007819 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007820
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007821 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007822 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007823 // Replace: gep (gep %P, long B), long A, ...
7824 // With: T = long A+B; gep %P, T, ...
7825 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007826 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007827 if (SO1 == Constant::getNullValue(SO1->getType())) {
7828 Sum = GO1;
7829 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7830 Sum = SO1;
7831 } else {
7832 // If they aren't the same type, convert both to an integer of the
7833 // target's pointer size.
7834 if (SO1->getType() != GO1->getType()) {
7835 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007836 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007837 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007838 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007839 } else {
7840 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007841 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007842 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007843 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007844
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007845 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007846 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007847 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007848 } else {
7849 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007850 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7851 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007852 }
7853 }
7854 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007855 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7856 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7857 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007858 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7859 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007860 }
Chris Lattner69193f92004-04-05 01:30:19 +00007861 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007862
7863 // Recycle the GEP we already have if possible.
7864 if (SrcGEPOperands.size() == 2) {
7865 GEP.setOperand(0, SrcGEPOperands[0]);
7866 GEP.setOperand(1, Sum);
7867 return &GEP;
7868 } else {
7869 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7870 SrcGEPOperands.end()-1);
7871 Indices.push_back(Sum);
7872 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7873 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007874 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007875 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007876 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007877 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007878 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7879 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007880 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7881 }
7882
7883 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00007884 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7885 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007886
Chris Lattner5f667a62004-05-07 22:09:22 +00007887 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007888 // GEP of global variable. If all of the indices for this GEP are
7889 // constants, we can promote this to a constexpr instead of an instruction.
7890
7891 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007892 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007893 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7894 for (; I != E && isa<Constant>(*I); ++I)
7895 Indices.push_back(cast<Constant>(*I));
7896
7897 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007898 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7899 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007900
7901 // Replace all uses of the GEP with the new constexpr...
7902 return ReplaceInstUsesWith(GEP, CE);
7903 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007904 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007905 if (!isa<PointerType>(X->getType())) {
7906 // Not interesting. Source pointer must be a cast from pointer.
7907 } else if (HasZeroPointerIndex) {
7908 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7909 // into : GEP [10 x ubyte]* X, long 0, ...
7910 //
7911 // This occurs when the program declares an array extern like "int X[];"
7912 //
7913 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7914 const PointerType *XTy = cast<PointerType>(X->getType());
7915 if (const ArrayType *XATy =
7916 dyn_cast<ArrayType>(XTy->getElementType()))
7917 if (const ArrayType *CATy =
7918 dyn_cast<ArrayType>(CPTy->getElementType()))
7919 if (CATy->getElementType() == XATy->getElementType()) {
7920 // At this point, we know that the cast source type is a pointer
7921 // to an array of the same type as the destination pointer
7922 // array. Because the array type is never stepped over (there
7923 // is a leading zero) we can fold the cast into this GEP.
7924 GEP.setOperand(0, X);
7925 return &GEP;
7926 }
7927 } else if (GEP.getNumOperands() == 2) {
7928 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007929 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7930 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007931 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7932 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7933 if (isa<ArrayType>(SrcElTy) &&
7934 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7935 TD->getTypeSize(ResElTy)) {
7936 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007937 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007938 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007939 // V and GEP are both pointer types --> BitCast
7940 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007941 }
Chris Lattner2a893292005-09-13 18:36:04 +00007942
7943 // Transform things like:
7944 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7945 // (where tmp = 8*tmp2) into:
7946 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7947
7948 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007949 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007950 uint64_t ArrayEltSize =
7951 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7952
7953 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7954 // allow either a mul, shift, or constant here.
7955 Value *NewIdx = 0;
7956 ConstantInt *Scale = 0;
7957 if (ArrayEltSize == 1) {
7958 NewIdx = GEP.getOperand(1);
7959 Scale = ConstantInt::get(NewIdx->getType(), 1);
7960 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007961 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007962 Scale = CI;
7963 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7964 if (Inst->getOpcode() == Instruction::Shl &&
7965 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007966 unsigned ShAmt =
7967 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007968 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007969 NewIdx = Inst->getOperand(0);
7970 } else if (Inst->getOpcode() == Instruction::Mul &&
7971 isa<ConstantInt>(Inst->getOperand(1))) {
7972 Scale = cast<ConstantInt>(Inst->getOperand(1));
7973 NewIdx = Inst->getOperand(0);
7974 }
7975 }
7976
7977 // If the index will be to exactly the right offset with the scale taken
7978 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007979 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007980 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007981 Scale = ConstantInt::get(Scale->getType(),
7982 Scale->getZExtValue() / ArrayEltSize);
7983 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007984 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7985 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007986 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7987 NewIdx = InsertNewInstBefore(Sc, GEP);
7988 }
7989
7990 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007991 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007992 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007993 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007994 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7995 // The NewGEP must be pointer typed, so must the old one -> BitCast
7996 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007997 }
7998 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007999 }
Chris Lattnerca081252001-12-14 16:52:21 +00008000 }
8001
Chris Lattnerca081252001-12-14 16:52:21 +00008002 return 0;
8003}
8004
Chris Lattner1085bdf2002-11-04 16:18:53 +00008005Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8006 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8007 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008008 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8009 const Type *NewTy =
8010 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008011 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008012
8013 // Create and insert the replacement instruction...
8014 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008015 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008016 else {
8017 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008018 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008019 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008020
8021 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008022
Chris Lattner1085bdf2002-11-04 16:18:53 +00008023 // Scan to the end of the allocation instructions, to skip over a block of
8024 // allocas if possible...
8025 //
8026 BasicBlock::iterator It = New;
8027 while (isa<AllocationInst>(*It)) ++It;
8028
8029 // Now that I is pointing to the first non-allocation-inst in the block,
8030 // insert our getelementptr instruction...
8031 //
Reid Spencerc635f472006-12-31 05:48:39 +00008032 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008033 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8034 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008035
8036 // Now make everything use the getelementptr instead of the original
8037 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008038 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008039 } else if (isa<UndefValue>(AI.getArraySize())) {
8040 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008041 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008042
8043 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8044 // Note that we only do this for alloca's, because malloc should allocate and
8045 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008046 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008047 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008048 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8049
Chris Lattner1085bdf2002-11-04 16:18:53 +00008050 return 0;
8051}
8052
Chris Lattner8427bff2003-12-07 01:24:23 +00008053Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8054 Value *Op = FI.getOperand(0);
8055
8056 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8057 if (CastInst *CI = dyn_cast<CastInst>(Op))
8058 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8059 FI.setOperand(0, CI->getOperand(0));
8060 return &FI;
8061 }
8062
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008063 // free undef -> unreachable.
8064 if (isa<UndefValue>(Op)) {
8065 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008066 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008067 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008068 return EraseInstFromFunction(FI);
8069 }
8070
Chris Lattnerf3a36602004-02-28 04:57:37 +00008071 // If we have 'free null' delete the instruction. This can happen in stl code
8072 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008073 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008074 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008075
Chris Lattner8427bff2003-12-07 01:24:23 +00008076 return 0;
8077}
8078
8079
Chris Lattner72684fe2005-01-31 05:51:45 +00008080/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008081static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8082 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008083 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008084
8085 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008086 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008087 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008088
Reid Spencer31a4ef42007-01-22 05:51:25 +00008089 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008090 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008091 // If the source is an array, the code below will not succeed. Check to
8092 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8093 // constants.
8094 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8095 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8096 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008097 Value *Idxs[2];
8098 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8099 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008100 SrcTy = cast<PointerType>(CastOp->getType());
8101 SrcPTy = SrcTy->getElementType();
8102 }
8103
Reid Spencer31a4ef42007-01-22 05:51:25 +00008104 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008105 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008106 // Do not allow turning this into a load of an integer, which is then
8107 // casted to a pointer, this pessimizes pointer analysis a lot.
8108 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008109 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8110 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008111
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008112 // Okay, we are casting from one integer or pointer type to another of
8113 // the same size. Instead of casting the pointer before the load, cast
8114 // the result of the loaded value.
8115 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8116 CI->getName(),
8117 LI.isVolatile()),LI);
8118 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008119 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008120 }
Chris Lattner35e24772004-07-13 01:49:43 +00008121 }
8122 }
8123 return 0;
8124}
8125
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008126/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008127/// from this value cannot trap. If it is not obviously safe to load from the
8128/// specified pointer, we do a quick local scan of the basic block containing
8129/// ScanFrom, to determine if the address is already accessed.
8130static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8131 // If it is an alloca or global variable, it is always safe to load from.
8132 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8133
8134 // Otherwise, be a little bit agressive by scanning the local block where we
8135 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008136 // from/to. If so, the previous load or store would have already trapped,
8137 // so there is no harm doing an extra load (also, CSE will later eliminate
8138 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008139 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8140
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008141 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008142 --BBI;
8143
8144 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8145 if (LI->getOperand(0) == V) return true;
8146 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8147 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008148
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008149 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008150 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008151}
8152
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008153Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8154 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008155
Chris Lattnera9d84e32005-05-01 04:24:53 +00008156 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008157 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008158 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8159 return Res;
8160
8161 // None of the following transforms are legal for volatile loads.
8162 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008163
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008164 if (&LI.getParent()->front() != &LI) {
8165 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008166 // If the instruction immediately before this is a store to the same
8167 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008168 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8169 if (SI->getOperand(1) == LI.getOperand(0))
8170 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008171 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8172 if (LIB->getOperand(0) == LI.getOperand(0))
8173 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008174 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008175
8176 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8177 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8178 isa<UndefValue>(GEPI->getOperand(0))) {
8179 // Insert a new store to null instruction before the load to indicate
8180 // that this code is not reachable. We do this instead of inserting
8181 // an unreachable instruction directly because we cannot modify the
8182 // CFG.
8183 new StoreInst(UndefValue::get(LI.getType()),
8184 Constant::getNullValue(Op->getType()), &LI);
8185 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8186 }
8187
Chris Lattner81a7a232004-10-16 18:11:37 +00008188 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008189 // load null/undef -> undef
8190 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008191 // Insert a new store to null instruction before the load to indicate that
8192 // this code is not reachable. We do this instead of inserting an
8193 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008194 new StoreInst(UndefValue::get(LI.getType()),
8195 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008196 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008197 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008198
Chris Lattner81a7a232004-10-16 18:11:37 +00008199 // Instcombine load (constant global) into the value loaded.
8200 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008201 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008202 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008203
Chris Lattner81a7a232004-10-16 18:11:37 +00008204 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8205 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8206 if (CE->getOpcode() == Instruction::GetElementPtr) {
8207 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008208 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008209 if (Constant *V =
8210 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008211 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008212 if (CE->getOperand(0)->isNullValue()) {
8213 // Insert a new store to null instruction before the load to indicate
8214 // that this code is not reachable. We do this instead of inserting
8215 // an unreachable instruction directly because we cannot modify the
8216 // CFG.
8217 new StoreInst(UndefValue::get(LI.getType()),
8218 Constant::getNullValue(Op->getType()), &LI);
8219 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8220 }
8221
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008222 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008223 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8224 return Res;
8225 }
8226 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008227
Chris Lattnera9d84e32005-05-01 04:24:53 +00008228 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008229 // Change select and PHI nodes to select values instead of addresses: this
8230 // helps alias analysis out a lot, allows many others simplifications, and
8231 // exposes redundancy in the code.
8232 //
8233 // Note that we cannot do the transformation unless we know that the
8234 // introduced loads cannot trap! Something like this is valid as long as
8235 // the condition is always false: load (select bool %C, int* null, int* %G),
8236 // but it would not be valid if we transformed it to load from null
8237 // unconditionally.
8238 //
8239 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8240 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008241 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8242 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008243 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008244 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008245 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008246 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008247 return new SelectInst(SI->getCondition(), V1, V2);
8248 }
8249
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008250 // load (select (cond, null, P)) -> load P
8251 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8252 if (C->isNullValue()) {
8253 LI.setOperand(0, SI->getOperand(2));
8254 return &LI;
8255 }
8256
8257 // load (select (cond, P, null)) -> load P
8258 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8259 if (C->isNullValue()) {
8260 LI.setOperand(0, SI->getOperand(1));
8261 return &LI;
8262 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008263 }
8264 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008265 return 0;
8266}
8267
Reid Spencere928a152007-01-19 21:20:31 +00008268/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008269/// when possible.
8270static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8271 User *CI = cast<User>(SI.getOperand(1));
8272 Value *CastOp = CI->getOperand(0);
8273
8274 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8275 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8276 const Type *SrcPTy = SrcTy->getElementType();
8277
Reid Spencer31a4ef42007-01-22 05:51:25 +00008278 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008279 // If the source is an array, the code below will not succeed. Check to
8280 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8281 // constants.
8282 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8283 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8284 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008285 Value* Idxs[2];
8286 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8287 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008288 SrcTy = cast<PointerType>(CastOp->getType());
8289 SrcPTy = SrcTy->getElementType();
8290 }
8291
Reid Spencer9a4bed02007-01-20 23:35:48 +00008292 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8293 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8294 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008295
8296 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008297 // the same size. Instead of casting the pointer before
8298 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008299 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008300 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008301 Instruction::CastOps opcode = Instruction::BitCast;
8302 const Type* CastSrcTy = SIOp0->getType();
8303 const Type* CastDstTy = SrcPTy;
8304 if (isa<PointerType>(CastDstTy)) {
8305 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008306 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008307 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008308 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008309 opcode = Instruction::PtrToInt;
8310 }
8311 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008312 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008313 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008314 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008315 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8316 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008317 return new StoreInst(NewCast, CastOp);
8318 }
8319 }
8320 }
8321 return 0;
8322}
8323
Chris Lattner31f486c2005-01-31 05:36:43 +00008324Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8325 Value *Val = SI.getOperand(0);
8326 Value *Ptr = SI.getOperand(1);
8327
8328 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008329 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008330 ++NumCombined;
8331 return 0;
8332 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008333
8334 // If the RHS is an alloca with a single use, zapify the store, making the
8335 // alloca dead.
8336 if (Ptr->hasOneUse()) {
8337 if (isa<AllocaInst>(Ptr)) {
8338 EraseInstFromFunction(SI);
8339 ++NumCombined;
8340 return 0;
8341 }
8342
8343 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8344 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8345 GEP->getOperand(0)->hasOneUse()) {
8346 EraseInstFromFunction(SI);
8347 ++NumCombined;
8348 return 0;
8349 }
8350 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008351
Chris Lattner5997cf92006-02-08 03:25:32 +00008352 // Do really simple DSE, to catch cases where there are several consequtive
8353 // stores to the same location, separated by a few arithmetic operations. This
8354 // situation often occurs with bitfield accesses.
8355 BasicBlock::iterator BBI = &SI;
8356 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8357 --ScanInsts) {
8358 --BBI;
8359
8360 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8361 // Prev store isn't volatile, and stores to the same location?
8362 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8363 ++NumDeadStore;
8364 ++BBI;
8365 EraseInstFromFunction(*PrevSI);
8366 continue;
8367 }
8368 break;
8369 }
8370
Chris Lattnerdab43b22006-05-26 19:19:20 +00008371 // If this is a load, we have to stop. However, if the loaded value is from
8372 // the pointer we're loading and is producing the pointer we're storing,
8373 // then *this* store is dead (X = load P; store X -> P).
8374 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8375 if (LI == Val && LI->getOperand(0) == Ptr) {
8376 EraseInstFromFunction(SI);
8377 ++NumCombined;
8378 return 0;
8379 }
8380 // Otherwise, this is a load from some other location. Stores before it
8381 // may not be dead.
8382 break;
8383 }
8384
Chris Lattner5997cf92006-02-08 03:25:32 +00008385 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008386 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008387 break;
8388 }
8389
8390
8391 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008392
8393 // store X, null -> turns into 'unreachable' in SimplifyCFG
8394 if (isa<ConstantPointerNull>(Ptr)) {
8395 if (!isa<UndefValue>(Val)) {
8396 SI.setOperand(0, UndefValue::get(Val->getType()));
8397 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008398 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008399 ++NumCombined;
8400 }
8401 return 0; // Do not modify these!
8402 }
8403
8404 // store undef, Ptr -> noop
8405 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008406 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008407 ++NumCombined;
8408 return 0;
8409 }
8410
Chris Lattner72684fe2005-01-31 05:51:45 +00008411 // If the pointer destination is a cast, see if we can fold the cast into the
8412 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008413 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008414 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8415 return Res;
8416 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008417 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008418 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8419 return Res;
8420
Chris Lattner219175c2005-09-12 23:23:25 +00008421
8422 // If this store is the last instruction in the basic block, and if the block
8423 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008424 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008425 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8426 if (BI->isUnconditional()) {
8427 // Check to see if the successor block has exactly two incoming edges. If
8428 // so, see if the other predecessor contains a store to the same location.
8429 // if so, insert a PHI node (if needed) and move the stores down.
8430 BasicBlock *Dest = BI->getSuccessor(0);
8431
8432 pred_iterator PI = pred_begin(Dest);
8433 BasicBlock *Other = 0;
8434 if (*PI != BI->getParent())
8435 Other = *PI;
8436 ++PI;
8437 if (PI != pred_end(Dest)) {
8438 if (*PI != BI->getParent())
8439 if (Other)
8440 Other = 0;
8441 else
8442 Other = *PI;
8443 if (++PI != pred_end(Dest))
8444 Other = 0;
8445 }
8446 if (Other) { // If only one other pred...
8447 BBI = Other->getTerminator();
8448 // Make sure this other block ends in an unconditional branch and that
8449 // there is an instruction before the branch.
8450 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8451 BBI != Other->begin()) {
8452 --BBI;
8453 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8454
8455 // If this instruction is a store to the same location.
8456 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8457 // Okay, we know we can perform this transformation. Insert a PHI
8458 // node now if we need it.
8459 Value *MergedVal = OtherStore->getOperand(0);
8460 if (MergedVal != SI.getOperand(0)) {
8461 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8462 PN->reserveOperandSpace(2);
8463 PN->addIncoming(SI.getOperand(0), SI.getParent());
8464 PN->addIncoming(OtherStore->getOperand(0), Other);
8465 MergedVal = InsertNewInstBefore(PN, Dest->front());
8466 }
8467
8468 // Advance to a place where it is safe to insert the new store and
8469 // insert it.
8470 BBI = Dest->begin();
8471 while (isa<PHINode>(BBI)) ++BBI;
8472 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8473 OtherStore->isVolatile()), *BBI);
8474
8475 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008476 EraseInstFromFunction(SI);
8477 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008478 ++NumCombined;
8479 return 0;
8480 }
8481 }
8482 }
8483 }
8484
Chris Lattner31f486c2005-01-31 05:36:43 +00008485 return 0;
8486}
8487
8488
Chris Lattner9eef8a72003-06-04 04:46:00 +00008489Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8490 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008491 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008492 BasicBlock *TrueDest;
8493 BasicBlock *FalseDest;
8494 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8495 !isa<Constant>(X)) {
8496 // Swap Destinations and condition...
8497 BI.setCondition(X);
8498 BI.setSuccessor(0, FalseDest);
8499 BI.setSuccessor(1, TrueDest);
8500 return &BI;
8501 }
8502
Reid Spencer266e42b2006-12-23 06:05:41 +00008503 // Cannonicalize fcmp_one -> fcmp_oeq
8504 FCmpInst::Predicate FPred; Value *Y;
8505 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8506 TrueDest, FalseDest)))
8507 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8508 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8509 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008510 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008511 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8512 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008513 // Swap Destinations and condition...
8514 BI.setCondition(NewSCC);
8515 BI.setSuccessor(0, FalseDest);
8516 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008517 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008518 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008519 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008520 return &BI;
8521 }
8522
8523 // Cannonicalize icmp_ne -> icmp_eq
8524 ICmpInst::Predicate IPred;
8525 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8526 TrueDest, FalseDest)))
8527 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8528 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8529 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8530 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008531 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008532 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8533 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008534 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008535 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008536 BI.setSuccessor(0, FalseDest);
8537 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008538 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008539 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008540 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008541 return &BI;
8542 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008543
Chris Lattner9eef8a72003-06-04 04:46:00 +00008544 return 0;
8545}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008546
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008547Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8548 Value *Cond = SI.getCondition();
8549 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8550 if (I->getOpcode() == Instruction::Add)
8551 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8552 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8553 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008554 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008555 AddRHS));
8556 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008557 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008558 return &SI;
8559 }
8560 }
8561 return 0;
8562}
8563
Chris Lattner6bc98652006-03-05 00:22:33 +00008564/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8565/// is to leave as a vector operation.
8566static bool CheapToScalarize(Value *V, bool isConstant) {
8567 if (isa<ConstantAggregateZero>(V))
8568 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008569 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008570 if (isConstant) return true;
8571 // If all elts are the same, we can extract.
8572 Constant *Op0 = C->getOperand(0);
8573 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8574 if (C->getOperand(i) != Op0)
8575 return false;
8576 return true;
8577 }
8578 Instruction *I = dyn_cast<Instruction>(V);
8579 if (!I) return false;
8580
8581 // Insert element gets simplified to the inserted element or is deleted if
8582 // this is constant idx extract element and its a constant idx insertelt.
8583 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8584 isa<ConstantInt>(I->getOperand(2)))
8585 return true;
8586 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8587 return true;
8588 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8589 if (BO->hasOneUse() &&
8590 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8591 CheapToScalarize(BO->getOperand(1), isConstant)))
8592 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008593 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8594 if (CI->hasOneUse() &&
8595 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8596 CheapToScalarize(CI->getOperand(1), isConstant)))
8597 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008598
8599 return false;
8600}
8601
Chris Lattner945e4372007-02-14 05:52:17 +00008602/// Read and decode a shufflevector mask.
8603///
8604/// It turns undef elements into values that are larger than the number of
8605/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008606static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8607 unsigned NElts = SVI->getType()->getNumElements();
8608 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8609 return std::vector<unsigned>(NElts, 0);
8610 if (isa<UndefValue>(SVI->getOperand(2)))
8611 return std::vector<unsigned>(NElts, 2*NElts);
8612
8613 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008614 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008615 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8616 if (isa<UndefValue>(CP->getOperand(i)))
8617 Result.push_back(NElts*2); // undef -> 8
8618 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008619 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008620 return Result;
8621}
8622
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008623/// FindScalarElement - Given a vector and an element number, see if the scalar
8624/// value is already around as a register, for example if it were inserted then
8625/// extracted from the vector.
8626static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008627 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8628 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008629 unsigned Width = PTy->getNumElements();
8630 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008631 return UndefValue::get(PTy->getElementType());
8632
8633 if (isa<UndefValue>(V))
8634 return UndefValue::get(PTy->getElementType());
8635 else if (isa<ConstantAggregateZero>(V))
8636 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008637 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008638 return CP->getOperand(EltNo);
8639 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8640 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008641 if (!isa<ConstantInt>(III->getOperand(2)))
8642 return 0;
8643 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008644
8645 // If this is an insert to the element we are looking for, return the
8646 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008647 if (EltNo == IIElt)
8648 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008649
8650 // Otherwise, the insertelement doesn't modify the value, recurse on its
8651 // vector input.
8652 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008653 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008654 unsigned InEl = getShuffleMask(SVI)[EltNo];
8655 if (InEl < Width)
8656 return FindScalarElement(SVI->getOperand(0), InEl);
8657 else if (InEl < Width*2)
8658 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8659 else
8660 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008661 }
8662
8663 // Otherwise, we don't know.
8664 return 0;
8665}
8666
Robert Bocchinoa8352962006-01-13 22:48:06 +00008667Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008668
Chris Lattner92346c32006-03-31 18:25:14 +00008669 // If packed val is undef, replace extract with scalar undef.
8670 if (isa<UndefValue>(EI.getOperand(0)))
8671 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8672
8673 // If packed val is constant 0, replace extract with scalar 0.
8674 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8675 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8676
Reid Spencerd84d35b2007-02-15 02:26:10 +00008677 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008678 // If packed val is constant with uniform operands, replace EI
8679 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008680 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008681 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008682 if (C->getOperand(i) != op0) {
8683 op0 = 0;
8684 break;
8685 }
8686 if (op0)
8687 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008688 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008689
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008690 // If extracting a specified index from the vector, see if we can recursively
8691 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008692 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008693 // This instruction only demands the single element from the input vector.
8694 // If the input vector has a single use, simplify it based on this use
8695 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008696 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008697 if (EI.getOperand(0)->hasOneUse()) {
8698 uint64_t UndefElts;
8699 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008700 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008701 UndefElts)) {
8702 EI.setOperand(0, V);
8703 return &EI;
8704 }
8705 }
8706
Reid Spencere0fc4df2006-10-20 07:07:24 +00008707 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008708 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008709 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008710
Chris Lattner83f65782006-05-25 22:53:38 +00008711 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008712 if (I->hasOneUse()) {
8713 // Push extractelement into predecessor operation if legal and
8714 // profitable to do so
8715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008716 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8717 if (CheapToScalarize(BO, isConstantElt)) {
8718 ExtractElementInst *newEI0 =
8719 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8720 EI.getName()+".lhs");
8721 ExtractElementInst *newEI1 =
8722 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8723 EI.getName()+".rhs");
8724 InsertNewInstBefore(newEI0, EI);
8725 InsertNewInstBefore(newEI1, EI);
8726 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8727 }
Reid Spencerde46e482006-11-02 20:25:50 +00008728 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008729 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008730 PointerType::get(EI.getType()), EI);
8731 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008732 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008733 InsertNewInstBefore(GEP, EI);
8734 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008735 }
8736 }
8737 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8738 // Extracting the inserted element?
8739 if (IE->getOperand(2) == EI.getOperand(1))
8740 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8741 // If the inserted and extracted elements are constants, they must not
8742 // be the same value, extract from the pre-inserted value instead.
8743 if (isa<Constant>(IE->getOperand(2)) &&
8744 isa<Constant>(EI.getOperand(1))) {
8745 AddUsesToWorkList(EI);
8746 EI.setOperand(0, IE->getOperand(0));
8747 return &EI;
8748 }
8749 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8750 // If this is extracting an element from a shufflevector, figure out where
8751 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008752 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8753 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008754 Value *Src;
8755 if (SrcIdx < SVI->getType()->getNumElements())
8756 Src = SVI->getOperand(0);
8757 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8758 SrcIdx -= SVI->getType()->getNumElements();
8759 Src = SVI->getOperand(1);
8760 } else {
8761 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008762 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008763 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008764 }
8765 }
Chris Lattner83f65782006-05-25 22:53:38 +00008766 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008767 return 0;
8768}
8769
Chris Lattner90951862006-04-16 00:51:47 +00008770/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8771/// elements from either LHS or RHS, return the shuffle mask and true.
8772/// Otherwise, return false.
8773static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8774 std::vector<Constant*> &Mask) {
8775 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8776 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008777 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008778
8779 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008780 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008781 return true;
8782 } else if (V == LHS) {
8783 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008784 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008785 return true;
8786 } else if (V == RHS) {
8787 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008788 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008789 return true;
8790 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8791 // If this is an insert of an extract from some other vector, include it.
8792 Value *VecOp = IEI->getOperand(0);
8793 Value *ScalarOp = IEI->getOperand(1);
8794 Value *IdxOp = IEI->getOperand(2);
8795
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008796 if (!isa<ConstantInt>(IdxOp))
8797 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008798 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008799
8800 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8801 // Okay, we can handle this if the vector we are insertinting into is
8802 // transitively ok.
8803 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8804 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008805 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008806 return true;
8807 }
8808 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8809 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008810 EI->getOperand(0)->getType() == V->getType()) {
8811 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008812 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008813
8814 // This must be extracting from either LHS or RHS.
8815 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8816 // Okay, we can handle this if the vector we are insertinting into is
8817 // transitively ok.
8818 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8819 // If so, update the mask to reflect the inserted value.
8820 if (EI->getOperand(0) == LHS) {
8821 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008822 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008823 } else {
8824 assert(EI->getOperand(0) == RHS);
8825 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008826 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008827
8828 }
8829 return true;
8830 }
8831 }
8832 }
8833 }
8834 }
8835 // TODO: Handle shufflevector here!
8836
8837 return false;
8838}
8839
8840/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8841/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8842/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008843static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008844 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008845 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00008846 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008847 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008848 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00008849
8850 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008851 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008852 return V;
8853 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008854 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008855 return V;
8856 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8857 // If this is an insert of an extract from some other vector, include it.
8858 Value *VecOp = IEI->getOperand(0);
8859 Value *ScalarOp = IEI->getOperand(1);
8860 Value *IdxOp = IEI->getOperand(2);
8861
8862 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8863 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8864 EI->getOperand(0)->getType() == V->getType()) {
8865 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008866 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8867 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008868
8869 // Either the extracted from or inserted into vector must be RHSVec,
8870 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008871 if (EI->getOperand(0) == RHS || RHS == 0) {
8872 RHS = EI->getOperand(0);
8873 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008874 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008875 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008876 return V;
8877 }
8878
Chris Lattner90951862006-04-16 00:51:47 +00008879 if (VecOp == RHS) {
8880 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008881 // Everything but the extracted element is replaced with the RHS.
8882 for (unsigned i = 0; i != NumElts; ++i) {
8883 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008884 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008885 }
8886 return V;
8887 }
Chris Lattner90951862006-04-16 00:51:47 +00008888
8889 // If this insertelement is a chain that comes from exactly these two
8890 // vectors, return the vector and the effective shuffle.
8891 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8892 return EI->getOperand(0);
8893
Chris Lattner39fac442006-04-15 01:39:45 +00008894 }
8895 }
8896 }
Chris Lattner90951862006-04-16 00:51:47 +00008897 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008898
8899 // Otherwise, can't do anything fancy. Return an identity vector.
8900 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008901 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008902 return V;
8903}
8904
8905Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8906 Value *VecOp = IE.getOperand(0);
8907 Value *ScalarOp = IE.getOperand(1);
8908 Value *IdxOp = IE.getOperand(2);
8909
8910 // If the inserted element was extracted from some other vector, and if the
8911 // indexes are constant, try to turn this into a shufflevector operation.
8912 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8913 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8914 EI->getOperand(0)->getType() == IE.getType()) {
8915 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008916 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8917 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008918
8919 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8920 return ReplaceInstUsesWith(IE, VecOp);
8921
8922 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8923 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8924
8925 // If we are extracting a value from a vector, then inserting it right
8926 // back into the same place, just use the input vector.
8927 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8928 return ReplaceInstUsesWith(IE, VecOp);
8929
8930 // We could theoretically do this for ANY input. However, doing so could
8931 // turn chains of insertelement instructions into a chain of shufflevector
8932 // instructions, and right now we do not merge shufflevectors. As such,
8933 // only do this in a situation where it is clear that there is benefit.
8934 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8935 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8936 // the values of VecOp, except then one read from EIOp0.
8937 // Build a new shuffle mask.
8938 std::vector<Constant*> Mask;
8939 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008940 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008941 else {
8942 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008943 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008944 NumVectorElts));
8945 }
Reid Spencerc635f472006-12-31 05:48:39 +00008946 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008947 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00008948 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008949 }
8950
8951 // If this insertelement isn't used by some other insertelement, turn it
8952 // (and any insertelements it points to), into one big shuffle.
8953 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8954 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008955 Value *RHS = 0;
8956 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8957 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8958 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00008959 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008960 }
8961 }
8962 }
8963
8964 return 0;
8965}
8966
8967
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008968Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8969 Value *LHS = SVI.getOperand(0);
8970 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008971 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008972
8973 bool MadeChange = false;
8974
Chris Lattner2deeaea2006-10-05 06:55:50 +00008975 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008976 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008977 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8978
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008979 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008980 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008981 if (isa<UndefValue>(SVI.getOperand(1))) {
8982 // Scan to see if there are any references to the RHS. If so, replace them
8983 // with undef element refs and set MadeChange to true.
8984 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8985 if (Mask[i] >= e && Mask[i] != 2*e) {
8986 Mask[i] = 2*e;
8987 MadeChange = true;
8988 }
8989 }
8990
8991 if (MadeChange) {
8992 // Remap any references to RHS to use LHS.
8993 std::vector<Constant*> Elts;
8994 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8995 if (Mask[i] == 2*e)
8996 Elts.push_back(UndefValue::get(Type::Int32Ty));
8997 else
8998 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8999 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009000 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009001 }
9002 }
Chris Lattner39fac442006-04-15 01:39:45 +00009003
Chris Lattner12249be2006-05-25 23:48:38 +00009004 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9005 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9006 if (LHS == RHS || isa<UndefValue>(LHS)) {
9007 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009008 // shuffle(undef,undef,mask) -> undef.
9009 return ReplaceInstUsesWith(SVI, LHS);
9010 }
9011
Chris Lattner12249be2006-05-25 23:48:38 +00009012 // Remap any references to RHS to use LHS.
9013 std::vector<Constant*> Elts;
9014 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009015 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009016 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009017 else {
9018 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9019 (Mask[i] < e && isa<UndefValue>(LHS)))
9020 Mask[i] = 2*e; // Turn into undef.
9021 else
9022 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009023 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009024 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009025 }
Chris Lattner12249be2006-05-25 23:48:38 +00009026 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009027 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009028 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009029 LHS = SVI.getOperand(0);
9030 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009031 MadeChange = true;
9032 }
9033
Chris Lattner0e477162006-05-26 00:29:06 +00009034 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009035 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009036
Chris Lattner12249be2006-05-25 23:48:38 +00009037 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9038 if (Mask[i] >= e*2) continue; // Ignore undef values.
9039 // Is this an identity shuffle of the LHS value?
9040 isLHSID &= (Mask[i] == i);
9041
9042 // Is this an identity shuffle of the RHS value?
9043 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009044 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009045
Chris Lattner12249be2006-05-25 23:48:38 +00009046 // Eliminate identity shuffles.
9047 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9048 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009049
Chris Lattner0e477162006-05-26 00:29:06 +00009050 // If the LHS is a shufflevector itself, see if we can combine it with this
9051 // one without producing an unusual shuffle. Here we are really conservative:
9052 // we are absolutely afraid of producing a shuffle mask not in the input
9053 // program, because the code gen may not be smart enough to turn a merged
9054 // shuffle into two specific shuffles: it may produce worse code. As such,
9055 // we only merge two shuffles if the result is one of the two input shuffle
9056 // masks. In this case, merging the shuffles just removes one instruction,
9057 // which we know is safe. This is good for things like turning:
9058 // (splat(splat)) -> splat.
9059 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9060 if (isa<UndefValue>(RHS)) {
9061 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9062
9063 std::vector<unsigned> NewMask;
9064 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9065 if (Mask[i] >= 2*e)
9066 NewMask.push_back(2*e);
9067 else
9068 NewMask.push_back(LHSMask[Mask[i]]);
9069
9070 // If the result mask is equal to the src shuffle or this shuffle mask, do
9071 // the replacement.
9072 if (NewMask == LHSMask || NewMask == Mask) {
9073 std::vector<Constant*> Elts;
9074 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9075 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009076 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009077 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009078 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009079 }
9080 }
9081 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9082 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009083 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009084 }
9085 }
9086 }
Chris Lattner4284f642007-01-30 22:32:46 +00009087
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009088 return MadeChange ? &SVI : 0;
9089}
9090
9091
Robert Bocchinoa8352962006-01-13 22:48:06 +00009092
Chris Lattner39c98bb2004-12-08 23:43:58 +00009093
9094/// TryToSinkInstruction - Try to move the specified instruction from its
9095/// current block into the beginning of DestBlock, which can only happen if it's
9096/// safe to move the instruction past all of the instructions between it and the
9097/// end of its block.
9098static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9099 assert(I->hasOneUse() && "Invariants didn't hold!");
9100
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009101 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9102 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009103
Chris Lattner39c98bb2004-12-08 23:43:58 +00009104 // Do not sink alloca instructions out of the entry block.
9105 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9106 return false;
9107
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009108 // We can only sink load instructions if there is nothing between the load and
9109 // the end of block that could change the value.
9110 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009111 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9112 Scan != E; ++Scan)
9113 if (Scan->mayWriteToMemory())
9114 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009115 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009116
9117 BasicBlock::iterator InsertPos = DestBlock->begin();
9118 while (isa<PHINode>(InsertPos)) ++InsertPos;
9119
Chris Lattner9f269e42005-08-08 19:11:57 +00009120 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009121 ++NumSunkInst;
9122 return true;
9123}
9124
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009125
9126/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9127/// all reachable code to the worklist.
9128///
9129/// This has a couple of tricks to make the code faster and more powerful. In
9130/// particular, we constant fold and DCE instructions as we go, to avoid adding
9131/// them to the worklist (this significantly speeds up instcombine on code where
9132/// many instructions are dead or constant). Additionally, if we find a branch
9133/// whose condition is a known constant, we only visit the reachable successors.
9134///
9135static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009136 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009137 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009138 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009139 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009140 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009141
9142 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9143 Instruction *Inst = BBI++;
9144
9145 // DCE instruction if trivially dead.
9146 if (isInstructionTriviallyDead(Inst)) {
9147 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009148 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009149 Inst->eraseFromParent();
9150 continue;
9151 }
9152
9153 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009154 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009155 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009156 Inst->replaceAllUsesWith(C);
9157 ++NumConstProp;
9158 Inst->eraseFromParent();
9159 continue;
9160 }
9161
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009162 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009163 }
9164
9165 // Recursively visit successors. If this is a branch or switch on a constant,
9166 // only visit the reachable successor.
9167 TerminatorInst *TI = BB->getTerminator();
9168 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009169 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009170 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009171 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009172 return;
9173 }
9174 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9175 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9176 // See if this is an explicit destination.
9177 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9178 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009179 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009180 return;
9181 }
9182
9183 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009184 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009185 return;
9186 }
9187 }
9188
9189 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009190 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009191}
9192
Chris Lattner960a5432007-03-03 02:04:50 +00009193bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009194 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009195 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009196
9197 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9198 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009199
Chris Lattner4ed40f72005-07-07 20:40:38 +00009200 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009201 // Do a depth-first traversal of the function, populate the worklist with
9202 // the reachable instructions. Ignore blocks that are not reachable. Keep
9203 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009204 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009205 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009206
Chris Lattner4ed40f72005-07-07 20:40:38 +00009207 // Do a quick scan over the function. If we find any blocks that are
9208 // unreachable, remove any instructions inside of them. This prevents
9209 // the instcombine code from having to deal with some bad special cases.
9210 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9211 if (!Visited.count(BB)) {
9212 Instruction *Term = BB->getTerminator();
9213 while (Term != BB->begin()) { // Remove instrs bottom-up
9214 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009215
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009216 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009217 ++NumDeadInst;
9218
9219 if (!I->use_empty())
9220 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9221 I->eraseFromParent();
9222 }
9223 }
9224 }
Chris Lattnerca081252001-12-14 16:52:21 +00009225
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009226 while (!Worklist.empty()) {
9227 Instruction *I = RemoveOneFromWorkList();
9228 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009229
Chris Lattner1443bc52006-05-11 17:11:52 +00009230 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009231 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009232 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009233 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009234 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009235 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009236
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009237 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009238
9239 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009240 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009241 continue;
9242 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009243
Chris Lattner1443bc52006-05-11 17:11:52 +00009244 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009245 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009246 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009247
Chris Lattner1443bc52006-05-11 17:11:52 +00009248 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009249 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009250 ReplaceInstUsesWith(*I, C);
9251
Chris Lattner99f48c62002-09-02 04:59:56 +00009252 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009253 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009254 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009255 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009256 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009257
Chris Lattner39c98bb2004-12-08 23:43:58 +00009258 // See if we can trivially sink this instruction to a successor basic block.
9259 if (I->hasOneUse()) {
9260 BasicBlock *BB = I->getParent();
9261 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9262 if (UserParent != BB) {
9263 bool UserIsSuccessor = false;
9264 // See if the user is one of our successors.
9265 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9266 if (*SI == UserParent) {
9267 UserIsSuccessor = true;
9268 break;
9269 }
9270
9271 // If the user is one of our immediate successors, and if that successor
9272 // only has us as a predecessors (we'd have to split the critical edge
9273 // otherwise), we can keep going.
9274 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9275 next(pred_begin(UserParent)) == pred_end(UserParent))
9276 // Okay, the CFG is simple enough, try to sink this instruction.
9277 Changed |= TryToSinkInstruction(I, UserParent);
9278 }
9279 }
9280
Chris Lattnerca081252001-12-14 16:52:21 +00009281 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009282 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009283 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009284 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009285 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009286 DOUT << "IC: Old = " << *I
9287 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009288
Chris Lattner396dbfe2004-06-09 05:08:07 +00009289 // Everything uses the new instruction now.
9290 I->replaceAllUsesWith(Result);
9291
9292 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009293 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009294 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009295
Chris Lattner6e0123b2007-02-11 01:23:03 +00009296 // Move the name to the new instruction first.
9297 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009298
9299 // Insert the new instruction into the basic block...
9300 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009301 BasicBlock::iterator InsertPos = I;
9302
9303 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9304 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9305 ++InsertPos;
9306
9307 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009308
Chris Lattner63d75af2004-05-01 23:27:23 +00009309 // Make sure that we reprocess all operands now that we reduced their
9310 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009311 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009312
Chris Lattner396dbfe2004-06-09 05:08:07 +00009313 // Instructions can end up on the worklist more than once. Make sure
9314 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009315 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009316
9317 // Erase the old instruction.
9318 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009319 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009320 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009321
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009322 // If the instruction was modified, it's possible that it is now dead.
9323 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009324 if (isInstructionTriviallyDead(I)) {
9325 // Make sure we process all operands now that we are reducing their
9326 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009327 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009328
Chris Lattner63d75af2004-05-01 23:27:23 +00009329 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009330 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009331 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009332 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009333 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009334 AddToWorkList(I);
9335 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009336 }
Chris Lattner053c0932002-05-14 15:24:07 +00009337 }
Chris Lattner260ab202002-04-18 17:39:14 +00009338 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009339 }
9340 }
9341
Chris Lattner960a5432007-03-03 02:04:50 +00009342 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009343 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009344}
9345
Chris Lattner960a5432007-03-03 02:04:50 +00009346
9347bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009348 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9349
Chris Lattner960a5432007-03-03 02:04:50 +00009350 bool EverMadeChange = false;
9351
9352 // Iterate while there is work to do.
9353 unsigned Iteration = 0;
9354 while (DoOneIteration(F, Iteration++))
9355 EverMadeChange = true;
9356 return EverMadeChange;
9357}
9358
Brian Gaeke38b79e82004-07-27 17:43:21 +00009359FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009360 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009361}
Brian Gaeke960707c2003-11-11 22:41:34 +00009362