blob: 93dde275b6cd15361c25c1788af4c8e61cf6f706 [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
Reid Spencer1791f232007-03-12 17:25:59 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000325
Reid Spencer1791f232007-03-12 17:25:59 +0000326 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
327 APInt& KnownZero, APInt& KnownOne,
328 unsigned Depth = 0);
329
Chris Lattner2deeaea2006-10-05 06:55:50 +0000330 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
331 uint64_t &UndefElts, unsigned Depth = 0);
332
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000333 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
334 // PHI node as operand #0, see if we can fold the instruction into the PHI
335 // (which is only possible if all operands to the PHI are constants).
336 Instruction *FoldOpIntoPhi(Instruction &I);
337
Chris Lattner7515cab2004-11-14 19:13:23 +0000338 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
339 // operator and they all are only used by the PHI, PHI together their
340 // inputs, and do the operation once, to the result of the PHI.
341 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000342 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
343
344
Zhou Sheng75b871f2007-01-11 12:24:14 +0000345 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
346 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000347
Zhou Sheng75b871f2007-01-11 12:24:14 +0000348 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000349 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000350 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000351 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000352 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000353 Instruction *MatchBSwap(BinaryOperator &I);
354
Reid Spencer74a528b2006-12-13 18:21:21 +0000355 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000356 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000357
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000358 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000359}
360
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000361// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000362// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000363static unsigned getComplexity(Value *V) {
364 if (isa<Instruction>(V)) {
365 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000366 return 3;
367 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000368 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000369 if (isa<Argument>(V)) return 3;
370 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000371}
Chris Lattner260ab202002-04-18 17:39:14 +0000372
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373// isOnlyUse - Return true if this instruction will be deleted if we stop using
374// it.
375static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000376 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000377}
378
Chris Lattnere79e8542004-02-23 06:38:22 +0000379// getPromotedType - Return the specified type promoted as it would be to pass
380// though a va_arg area...
381static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000382 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
383 if (ITy->getBitWidth() < 32)
384 return Type::Int32Ty;
385 } else if (Ty == Type::FloatTy)
386 return Type::DoubleTy;
387 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000388}
389
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000390/// getBitCastOperand - If the specified operand is a CastInst or a constant
391/// expression bitcast, return the operand value, otherwise return null.
392static Value *getBitCastOperand(Value *V) {
393 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000394 return I->getOperand(0);
395 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000396 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000397 return CE->getOperand(0);
398 return 0;
399}
400
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000401/// This function is a wrapper around CastInst::isEliminableCastPair. It
402/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000403static Instruction::CastOps
404isEliminableCastPair(
405 const CastInst *CI, ///< The first cast instruction
406 unsigned opcode, ///< The opcode of the second cast instruction
407 const Type *DstTy, ///< The target type for the second cast instruction
408 TargetData *TD ///< The target data for pointer size
409) {
410
411 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
412 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000413
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000414 // Get the opcodes of the two Cast instructions
415 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
416 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000417
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000418 return Instruction::CastOps(
419 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
420 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000421}
422
423/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
424/// in any code being generated. It does not require codegen if V is simple
425/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000426static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
427 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000428 if (V->getType() == Ty || isa<Constant>(V)) return false;
429
Chris Lattner99155be2006-05-25 23:24:33 +0000430 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000432 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000433 return false;
434 return true;
435}
436
437/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
438/// InsertBefore instruction. This is specialized a bit to avoid inserting
439/// casts that are known to not do anything...
440///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000441Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
442 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000443 Instruction *InsertBefore) {
444 if (V->getType() == DestTy) return V;
445 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000446 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447
Reid Spencer13bc5d72006-12-12 09:18:51 +0000448 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000449}
450
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000451// SimplifyCommutative - This performs a few simplifications for commutative
452// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000453//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454// 1. Order operands such that they are listed from right (least complex) to
455// left (most complex). This puts constants before unary operators before
456// binary operators.
457//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000458// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
459// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000461bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000462 bool Changed = false;
463 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
464 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000465
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000466 if (!I.isAssociative()) return Changed;
467 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000468 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
469 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
470 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000471 Constant *Folded = ConstantExpr::get(I.getOpcode(),
472 cast<Constant>(I.getOperand(1)),
473 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000474 I.setOperand(0, Op->getOperand(0));
475 I.setOperand(1, Folded);
476 return true;
477 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
478 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
479 isOnlyUse(Op) && isOnlyUse(Op1)) {
480 Constant *C1 = cast<Constant>(Op->getOperand(1));
481 Constant *C2 = cast<Constant>(Op1->getOperand(1));
482
483 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000484 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000485 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
486 Op1->getOperand(0),
487 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000488 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000489 I.setOperand(0, New);
490 I.setOperand(1, Folded);
491 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000492 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000493 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000494 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000495}
Chris Lattnerca081252001-12-14 16:52:21 +0000496
Reid Spencer266e42b2006-12-23 06:05:41 +0000497/// SimplifyCompare - For a CmpInst this function just orders the operands
498/// so that theyare listed from right (least complex) to left (most complex).
499/// This puts constants before unary operators before binary operators.
500bool InstCombiner::SimplifyCompare(CmpInst &I) {
501 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
502 return false;
503 I.swapOperands();
504 // Compare instructions are not associative so there's nothing else we can do.
505 return true;
506}
507
Chris Lattnerbb74e222003-03-10 23:06:50 +0000508// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
509// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000510//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000511static inline Value *dyn_castNegVal(Value *V) {
512 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000513 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514
Chris Lattner9ad0d552004-12-14 20:08:06 +0000515 // Constants can be considered to be negated values if they can be folded.
516 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
517 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000518 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000519}
520
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521static inline Value *dyn_castNotVal(Value *V) {
522 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000523 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524
525 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000526 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000527 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000528 return 0;
529}
530
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531// dyn_castFoldableMul - If this value is a multiply that can be folded into
532// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000533// non-constant operand of the multiply, and set CST to point to the multiplier.
534// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000535//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000537 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000540 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000541 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000542 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000544 // The multiplier is really 1 << CST.
545 Constant *One = ConstantInt::get(V->getType(), 1);
546 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
547 return I->getOperand(0);
548 }
549 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000550 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000551}
Chris Lattner31ae8632002-08-14 17:51:49 +0000552
Chris Lattner0798af32005-01-13 20:14:25 +0000553/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554/// expression, return it.
555static User *dyn_castGetElementPtr(Value *V) {
556 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558 if (CE->getOpcode() == Instruction::GetElementPtr)
559 return cast<User>(V);
560 return false;
561}
562
Chris Lattner623826c2004-09-28 21:48:02 +0000563// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000564static ConstantInt *AddOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getAdd(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000567}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000568static ConstantInt *SubOne(ConstantInt *C) {
569 return cast<ConstantInt>(ConstantExpr::getSub(C,
570 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000571}
572
Chris Lattner4534dd592006-02-09 07:38:58 +0000573/// ComputeMaskedBits - Determine which of the bits specified in Mask are
574/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000575/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
576/// processing.
577/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
578/// we cannot optimize based on the assumption that it is zero without changing
579/// it to be an explicit zero. If we don't change it to zero, other code could
580/// optimized based on the contradictory assumption that it is non-zero.
581/// Because instcombine aggressively folds operations with undef args anyway,
582/// this won't lose us code quality.
583static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
584 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000585 assert(V && "No Value?");
586 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000587 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaf4341d2007-03-13 02:23:10 +0000588 const IntegerType *VTy = cast<IntegerType>(V->getType());
589 assert(VTy->getBitWidth() == BitWidth &&
590 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000591 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000592 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000593 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
594 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000595 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000596 KnownZero = ~KnownOne & Mask;
597 return;
598 }
599
Reid Spenceraa696402007-03-08 01:46:38 +0000600 if (Depth == 6 || Mask == 0)
601 return; // Limit search depth.
602
603 Instruction *I = dyn_cast<Instruction>(V);
604 if (!I) return;
605
Zhou Shengaf4341d2007-03-13 02:23:10 +0000606 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000607 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000608 Mask &= APInt::getAllOnesValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000609
610 switch (I->getOpcode()) {
611 case Instruction::And:
612 // If either the LHS or the RHS are Zero, the result is zero.
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 Mask &= ~KnownZero;
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-1 bits are only known if set in both the LHS & RHS.
620 KnownOne &= KnownOne2;
621 // Output known-0 are known to be clear if zero in either the LHS | RHS.
622 KnownZero |= KnownZero2;
623 return;
624 case Instruction::Or:
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626 Mask &= ~KnownOne;
627 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
628 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
629 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
630
631 // Output known-0 bits are only known if clear in both the LHS & RHS.
632 KnownZero &= KnownZero2;
633 // Output known-1 are known to be set if set in either the LHS | RHS.
634 KnownOne |= KnownOne2;
635 return;
636 case Instruction::Xor: {
637 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Output known-0 bits are known if clear or set in both the LHS & RHS.
643 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
644 // Output known-1 are known to be set if set in only one of the LHS, RHS.
645 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
646 KnownZero = KnownZeroOut;
647 return;
648 }
649 case Instruction::Select:
650 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
651 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
654
655 // Only known if known in both the LHS and RHS.
656 KnownOne &= KnownOne2;
657 KnownZero &= KnownZero2;
658 return;
659 case Instruction::FPTrunc:
660 case Instruction::FPExt:
661 case Instruction::FPToUI:
662 case Instruction::FPToSI:
663 case Instruction::SIToFP:
664 case Instruction::PtrToInt:
665 case Instruction::UIToFP:
666 case Instruction::IntToPtr:
667 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000668 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000669 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000670 uint32_t SrcBitWidth =
671 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
672 ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth),
673 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
674 KnownZero.trunc(BitWidth);
675 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000676 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000677 }
Reid Spenceraa696402007-03-08 01:46:38 +0000678 case Instruction::BitCast: {
679 const Type *SrcTy = I->getOperand(0)->getType();
680 if (SrcTy->isInteger()) {
681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682 return;
683 }
684 break;
685 }
686 case Instruction::ZExt: {
687 // Compute the bits in the result that are not present in the input.
688 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000689 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000690
Zhou Shengaf4341d2007-03-13 02:23:10 +0000691 uint32_t SrcBitWidth = SrcTy->getBitWidth();
692 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
693 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
695 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000696 KnownZero.zext(BitWidth);
697 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000698 KnownZero |= NewBits;
699 return;
700 }
701 case Instruction::SExt: {
702 // Compute the bits in the result that are not present in the input.
703 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000704 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000705
Zhou Shengaf4341d2007-03-13 02:23:10 +0000706 uint32_t SrcBitWidth = SrcTy->getBitWidth();
707 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
708 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000710 KnownZero.zext(BitWidth);
711 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000712
713 // If the sign bit of the input is known set or clear, then we know the
714 // top bits of the result.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000715 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Zhou Shengaf4341d2007-03-13 02:23:10 +0000716 InSignBit.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000717 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
718 KnownZero |= NewBits;
719 KnownOne &= ~NewBits;
720 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
721 KnownOne |= NewBits;
722 KnownZero &= ~NewBits;
723 } else { // Input sign bit unknown
724 KnownZero &= ~NewBits;
725 KnownOne &= ~NewBits;
726 }
727 return;
728 }
729 case Instruction::Shl:
730 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
731 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732 uint64_t ShiftAmt = SA->getZExtValue();
733 Mask = APIntOps::lshr(Mask, ShiftAmt);
734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000736 KnownZero <<= ShiftAmt;
737 KnownOne <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000738 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
739 return;
740 }
741 break;
742 case Instruction::LShr:
743 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
744 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745 // Compute the new bits that are at the top now.
746 uint64_t ShiftAmt = SA->getZExtValue();
747 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748
749 // Unsigned shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000750 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
753 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
755 KnownZero |= HighBits; // high bits known zero.
756 return;
757 }
758 break;
759 case Instruction::AShr:
760 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
761 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762 // Compute the new bits that are at the top now.
763 uint64_t ShiftAmt = SA->getZExtValue();
764 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
765
766 // Signed shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000767 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000768 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
772
773 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000774 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000775
776 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
777 KnownZero |= HighBits;
778 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
779 KnownOne |= HighBits;
780 }
781 return;
782 }
783 break;
784 }
785}
786
787/// ComputeMaskedBits - Determine which of the bits specified in Mask are
788/// known to be either zero or one and return them in the KnownZero/KnownOne
Chris Lattner4534dd592006-02-09 07:38:58 +0000789/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
790/// processing.
Reid Spenceraa696402007-03-08 01:46:38 +0000791static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
Chris Lattner4534dd592006-02-09 07:38:58 +0000792 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000793 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
794 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000795 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000796 // optimized based on the contradictory assumption that it is non-zero.
797 // Because instcombine aggressively folds operations with undef args anyway,
798 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000800 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000801 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000802 KnownZero = ~KnownOne & Mask;
803 return;
804 }
805
806 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000807 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000808 return; // Limit search depth.
809
810 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811 Instruction *I = dyn_cast<Instruction>(V);
812 if (!I) return;
813
Reid Spencera94d3942007-01-19 21:13:56 +0000814 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000815
Chris Lattner0157e7f2006-02-11 09:31:47 +0000816 switch (I->getOpcode()) {
817 case Instruction::And:
818 // If either the LHS or the RHS are Zero, the result is zero.
819 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
820 Mask &= ~KnownZero;
821 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
822 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
823 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
824
825 // Output known-1 bits are only known if set in both the LHS & RHS.
826 KnownOne &= KnownOne2;
827 // Output known-0 are known to be clear if zero in either the LHS | RHS.
828 KnownZero |= KnownZero2;
829 return;
830 case Instruction::Or:
831 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
832 Mask &= ~KnownOne;
833 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
834 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
835 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
836
837 // Output known-0 bits are only known if clear in both the LHS & RHS.
838 KnownZero &= KnownZero2;
839 // Output known-1 are known to be set if set in either the LHS | RHS.
840 KnownOne |= KnownOne2;
841 return;
842 case Instruction::Xor: {
843 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
845 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
846 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
847
848 // Output known-0 bits are known if clear or set in both the LHS & RHS.
849 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
850 // Output known-1 are known to be set if set in only one of the LHS, RHS.
851 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
852 KnownZero = KnownZeroOut;
853 return;
854 }
855 case Instruction::Select:
856 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
857 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
860
861 // Only known if known in both the LHS and RHS.
862 KnownOne &= KnownOne2;
863 KnownZero &= KnownZero2;
864 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000865 case Instruction::FPTrunc:
866 case Instruction::FPExt:
867 case Instruction::FPToUI:
868 case Instruction::FPToSI:
869 case Instruction::SIToFP:
870 case Instruction::PtrToInt:
871 case Instruction::UIToFP:
872 case Instruction::IntToPtr:
873 return; // Can't work with floating point or pointers
874 case Instruction::Trunc:
875 // All these have integer operands
876 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877 return;
878 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000879 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000880 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000882 return;
883 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000884 break;
885 }
886 case Instruction::ZExt: {
887 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000888 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
889 uint64_t NotIn = ~SrcTy->getBitMask();
890 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000891
Reid Spencera94d3942007-01-19 21:13:56 +0000892 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000893 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 // The top bits are known to be zero.
896 KnownZero |= NewBits;
897 return;
898 }
899 case Instruction::SExt: {
900 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000901 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
902 uint64_t NotIn = ~SrcTy->getBitMask();
903 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000904
Reid Spencera94d3942007-01-19 21:13:56 +0000905 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000908
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000909 // If the sign bit of the input is known set or clear, then we know the
910 // top bits of the result.
911 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
912 if (KnownZero & InSignBit) { // Input sign bit known zero
913 KnownZero |= NewBits;
914 KnownOne &= ~NewBits;
915 } else if (KnownOne & InSignBit) { // Input sign bit known set
916 KnownOne |= NewBits;
917 KnownZero &= ~NewBits;
918 } else { // Input sign bit unknown
919 KnownZero &= ~NewBits;
920 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000921 }
922 return;
923 }
924 case Instruction::Shl:
925 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000926 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
927 uint64_t ShiftAmt = SA->getZExtValue();
928 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000929 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
930 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000931 KnownZero <<= ShiftAmt;
932 KnownOne <<= ShiftAmt;
933 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000934 return;
935 }
936 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000937 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000938 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000939 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000940 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000941 uint64_t ShiftAmt = SA->getZExtValue();
942 uint64_t HighBits = (1ULL << ShiftAmt)-1;
943 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000944
Reid Spencerfdff9382006-11-08 06:47:33 +0000945 // Unsigned shift right.
946 Mask <<= ShiftAmt;
947 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
948 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
949 KnownZero >>= ShiftAmt;
950 KnownOne >>= ShiftAmt;
951 KnownZero |= HighBits; // high bits known zero.
952 return;
953 }
954 break;
955 case Instruction::AShr:
956 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
957 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
958 // Compute the new bits that are at the top now.
959 uint64_t ShiftAmt = SA->getZExtValue();
960 uint64_t HighBits = (1ULL << ShiftAmt)-1;
961 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
962
963 // Signed shift right.
964 Mask <<= ShiftAmt;
965 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
966 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
967 KnownZero >>= ShiftAmt;
968 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000969
Reid Spencerfdff9382006-11-08 06:47:33 +0000970 // Handle the sign bits.
971 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
972 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000973
Reid Spencerfdff9382006-11-08 06:47:33 +0000974 if (KnownZero & SignBit) { // New bits are known zero.
975 KnownZero |= HighBits;
976 } else if (KnownOne & SignBit) { // New bits are known one.
977 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000978 }
979 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000980 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000981 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000982 }
Chris Lattner92a68652006-02-07 08:05:22 +0000983}
984
985/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
986/// this predicate to simplify operations downstream. Mask is known to be zero
987/// for bits that V cannot have.
988static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000989 uint64_t KnownZero, KnownOne;
990 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
992 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000993}
994
Chris Lattnerd1bce952007-03-13 14:27:42 +0000995#if 0
Reid Spencerbb5741f2007-03-08 01:52:58 +0000996/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
997/// this predicate to simplify operations downstream. Mask is known to be zero
998/// for bits that V cannot have.
999static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +00001000 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +00001001 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1002 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1003 return (KnownZero & Mask) == Mask;
1004}
Chris Lattnerd1bce952007-03-13 14:27:42 +00001005#endif
Reid Spencerbb5741f2007-03-08 01:52:58 +00001006
Chris Lattner0157e7f2006-02-11 09:31:47 +00001007/// ShrinkDemandedConstant - Check to see if the specified operand of the
1008/// specified instruction is a constant integer. If so, check to see if there
1009/// are any bits set in the constant that are not demanded. If so, shrink the
1010/// constant and return true.
1011static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1012 uint64_t Demanded) {
1013 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1014 if (!OpC) return false;
1015
1016 // If there are no bits set that aren't demanded, nothing to do.
1017 if ((~Demanded & OpC->getZExtValue()) == 0)
1018 return false;
1019
1020 // This is producing any bits that are not needed, shrink the RHS.
1021 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001022 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001023 return true;
1024}
1025
Reid Spencerd9281782007-03-12 17:15:10 +00001026/// ShrinkDemandedConstant - Check to see if the specified operand of the
1027/// specified instruction is a constant integer. If so, check to see if there
1028/// are any bits set in the constant that are not demanded. If so, shrink the
1029/// constant and return true.
1030static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1031 APInt Demanded) {
1032 assert(I && "No instruction?");
1033 assert(OpNo < I->getNumOperands() && "Operand index too large");
1034
1035 // If the operand is not a constant integer, nothing to do.
1036 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1037 if (!OpC) return false;
1038
1039 // If there are no bits set that aren't demanded, nothing to do.
1040 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1041 if ((~Demanded & OpC->getValue()) == 0)
1042 return false;
1043
1044 // This instruction is producing bits that are not demanded. Shrink the RHS.
1045 Demanded &= OpC->getValue();
1046 I->setOperand(OpNo, ConstantInt::get(Demanded));
1047 return true;
1048}
1049
Chris Lattneree0f2802006-02-12 02:07:56 +00001050// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1051// set of known zero and one bits, compute the maximum and minimum values that
1052// could have the specified known zero and known one bits, returning them in
1053// min/max.
1054static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1055 uint64_t KnownZero,
1056 uint64_t KnownOne,
1057 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001058 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001059 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1060
1061 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1062
1063 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1064 // bit if it is unknown.
1065 Min = KnownOne;
1066 Max = KnownOne|UnknownBits;
1067
1068 if (SignBit & UnknownBits) { // Sign bit is unknown
1069 Min |= SignBit;
1070 Max &= ~SignBit;
1071 }
1072
1073 // Sign extend the min/max values.
1074 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1075 Min = (Min << ShAmt) >> ShAmt;
1076 Max = (Max << ShAmt) >> ShAmt;
1077}
1078
1079// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1080// a set of known zero and one bits, compute the maximum and minimum values that
1081// could have the specified known zero and known one bits, returning them in
1082// min/max.
1083static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1084 uint64_t KnownZero,
1085 uint64_t KnownOne,
1086 uint64_t &Min,
1087 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001088 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001089 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1090
1091 // The minimum value is when the unknown bits are all zeros.
1092 Min = KnownOne;
1093 // The maximum value is when the unknown bits are all ones.
1094 Max = KnownOne|UnknownBits;
1095}
Chris Lattner0157e7f2006-02-11 09:31:47 +00001096
1097
1098/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1099/// DemandedMask bits of the result of V are ever used downstream. If we can
1100/// use this information to simplify V, do so and return true. Otherwise,
1101/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1102/// the expression (used to simplify the caller). The KnownZero/One bits may
1103/// only be accurate for those bits in the DemandedMask.
1104bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1105 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +00001106 unsigned Depth) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001107 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng75b871f2007-01-11 12:24:14 +00001108 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +00001109 // We know all of the bits for a constant!
1110 KnownOne = CI->getZExtValue() & DemandedMask;
1111 KnownZero = ~KnownOne & DemandedMask;
1112 return false;
1113 }
1114
1115 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001116 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001117 if (Depth != 0) { // Not at the root.
1118 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1119 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +00001120 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001121 }
Chris Lattner2590e512006-02-07 06:56:34 +00001122 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001123 // just set the DemandedMask to all bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001124 DemandedMask = VTy->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001125 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001126 if (V != UndefValue::get(VTy))
1127 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner92a68652006-02-07 08:05:22 +00001128 return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001129 } else if (Depth == 6) { // Limit search depth.
1130 return false;
1131 }
1132
1133 Instruction *I = dyn_cast<Instruction>(V);
1134 if (!I) return false; // Only analyze instructions.
1135
Chris Lattnerab2f9132007-03-04 23:16:36 +00001136 DemandedMask &= VTy->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +00001137
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001138 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001139 switch (I->getOpcode()) {
1140 default: break;
1141 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001142 // If either the LHS or the RHS are Zero, the result is zero.
1143 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1144 KnownZero, KnownOne, Depth+1))
1145 return true;
1146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1147
1148 // If something is known zero on the RHS, the bits aren't demanded on the
1149 // LHS.
1150 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1151 KnownZero2, KnownOne2, Depth+1))
1152 return true;
1153 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1154
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001155 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001156 // These bits cannot contribute to the result of the 'and'.
1157 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1158 return UpdateValueUsesWith(I, I->getOperand(0));
1159 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1160 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001161
1162 // If all of the demanded bits in the inputs are known zeros, return zero.
1163 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001164 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001165
Chris Lattner0157e7f2006-02-11 09:31:47 +00001166 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001167 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001168 return UpdateValueUsesWith(I, I);
1169
1170 // Output known-1 bits are only known if set in both the LHS & RHS.
1171 KnownOne &= KnownOne2;
1172 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1173 KnownZero |= KnownZero2;
1174 break;
1175 case Instruction::Or:
1176 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1177 KnownZero, KnownOne, Depth+1))
1178 return true;
1179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1181 KnownZero2, KnownOne2, Depth+1))
1182 return true;
1183 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1184
1185 // If all of the demanded bits are known zero on one side, return the other.
1186 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +00001187 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001188 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +00001189 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001190 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001191
1192 // If all of the potentially set bits on one side are known to be set on
1193 // the other side, just use the 'other' side.
1194 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1195 (DemandedMask & (~KnownZero)))
1196 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +00001197 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1198 (DemandedMask & (~KnownZero2)))
1199 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001200
1201 // If the RHS is a constant, see if we can simplify it.
1202 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1203 return UpdateValueUsesWith(I, I);
1204
1205 // Output known-0 bits are only known if clear in both the LHS & RHS.
1206 KnownZero &= KnownZero2;
1207 // Output known-1 are known to be set if set in either the LHS | RHS.
1208 KnownOne |= KnownOne2;
1209 break;
1210 case Instruction::Xor: {
1211 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1212 KnownZero, KnownOne, Depth+1))
1213 return true;
1214 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1215 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1216 KnownZero2, KnownOne2, Depth+1))
1217 return true;
1218 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1219
1220 // If all of the demanded bits are known zero on one side, return the other.
1221 // These bits cannot contribute to the result of the 'xor'.
1222 if ((DemandedMask & KnownZero) == DemandedMask)
1223 return UpdateValueUsesWith(I, I->getOperand(0));
1224 if ((DemandedMask & KnownZero2) == DemandedMask)
1225 return UpdateValueUsesWith(I, I->getOperand(1));
1226
1227 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1228 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1229 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1230 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1231
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001232 // If all of the demanded bits are known to be zero on one side or the
1233 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001234 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001235 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1236 Instruction *Or =
1237 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1238 I->getName());
1239 InsertNewInstBefore(Or, *I);
1240 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001241 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001242
Chris Lattner5b2edb12006-02-12 08:02:11 +00001243 // If all of the demanded bits on one side are known, and all of the set
1244 // bits on that side are also known to be set on the other side, turn this
1245 // into an AND, as we know the bits will be cleared.
1246 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1247 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1248 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001249 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +00001250 Instruction *And =
1251 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1252 InsertNewInstBefore(And, *I);
1253 return UpdateValueUsesWith(I, And);
1254 }
1255 }
1256
Chris Lattner0157e7f2006-02-11 09:31:47 +00001257 // If the RHS is a constant, see if we can simplify it.
1258 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1259 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1260 return UpdateValueUsesWith(I, I);
1261
1262 KnownZero = KnownZeroOut;
1263 KnownOne = KnownOneOut;
1264 break;
1265 }
1266 case Instruction::Select:
1267 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1268 KnownZero, KnownOne, Depth+1))
1269 return true;
1270 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1271 KnownZero2, KnownOne2, Depth+1))
1272 return true;
1273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1274 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1275
1276 // If the operands are constants, see if we can simplify them.
1277 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1278 return UpdateValueUsesWith(I, I);
1279 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1280 return UpdateValueUsesWith(I, I);
1281
1282 // Only known if known in both the LHS and RHS.
1283 KnownOne &= KnownOne2;
1284 KnownZero &= KnownZero2;
1285 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001286 case Instruction::Trunc:
1287 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1288 KnownZero, KnownOne, Depth+1))
1289 return true;
1290 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1291 break;
1292 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001293 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001294 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001295
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001296 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1297 KnownZero, KnownOne, Depth+1))
1298 return true;
1299 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1300 break;
1301 case Instruction::ZExt: {
1302 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001303 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1304 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001305 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001306
Reid Spencera94d3942007-01-19 21:13:56 +00001307 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1309 KnownZero, KnownOne, Depth+1))
1310 return true;
1311 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1312 // The top bits are known to be zero.
1313 KnownZero |= NewBits;
1314 break;
1315 }
1316 case Instruction::SExt: {
1317 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001318 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1319 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001320 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001321
1322 // Get the sign bit for the source type
1323 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001324 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001325
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001326 // If any of the sign extended bits are demanded, we know that the sign
1327 // bit is demanded.
1328 if (NewBits & DemandedMask)
1329 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001330
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001331 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1332 KnownZero, KnownOne, Depth+1))
1333 return true;
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001335
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001336 // If the sign bit of the input is known set or clear, then we know the
1337 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001338
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001339 // If the input sign bit is known zero, or if the NewBits are not demanded
1340 // convert this into a zero extension.
1341 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1342 // Convert to ZExt cast
Chris Lattnerab2f9132007-03-04 23:16:36 +00001343 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001344 return UpdateValueUsesWith(I, NewCast);
1345 } else if (KnownOne & InSignBit) { // Input sign bit known set
1346 KnownOne |= NewBits;
1347 KnownZero &= ~NewBits;
1348 } else { // Input sign bit unknown
1349 KnownZero &= ~NewBits;
1350 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001351 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001352 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001353 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001354 case Instruction::Add:
1355 // If there is a constant on the RHS, there are a variety of xformations
1356 // we can do.
1357 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358 // If null, this should be simplified elsewhere. Some of the xforms here
1359 // won't work if the RHS is zero.
1360 if (RHS->isNullValue())
1361 break;
1362
1363 // Figure out what the input bits are. If the top bits of the and result
1364 // are not demanded, then the add doesn't demand them from its input
1365 // either.
1366
1367 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001368 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001369 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1370
1371 // If the top bit of the output is demanded, demand everything from the
1372 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001373 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001374
1375 // Find information about known zero/one bits in the input.
1376 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1377 KnownZero2, KnownOne2, Depth+1))
1378 return true;
1379
1380 // If the RHS of the add has bits set that can't affect the input, reduce
1381 // the constant.
1382 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1383 return UpdateValueUsesWith(I, I);
1384
1385 // Avoid excess work.
1386 if (KnownZero2 == 0 && KnownOne2 == 0)
1387 break;
1388
1389 // Turn it into OR if input bits are zero.
1390 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1391 Instruction *Or =
1392 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1393 I->getName());
1394 InsertNewInstBefore(Or, *I);
1395 return UpdateValueUsesWith(I, Or);
1396 }
1397
1398 // We can say something about the output known-zero and known-one bits,
1399 // depending on potential carries from the input constant and the
1400 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1401 // bits set and the RHS constant is 0x01001, then we know we have a known
1402 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1403
1404 // To compute this, we first compute the potential carry bits. These are
1405 // the bits which may be modified. I'm not aware of a better way to do
1406 // this scan.
1407 uint64_t RHSVal = RHS->getZExtValue();
1408
1409 bool CarryIn = false;
1410 uint64_t CarryBits = 0;
1411 uint64_t CurBit = 1;
1412 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1413 // Record the current carry in.
1414 if (CarryIn) CarryBits |= CurBit;
1415
1416 bool CarryOut;
1417
1418 // This bit has a carry out unless it is "zero + zero" or
1419 // "zero + anything" with no carry in.
1420 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1421 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1422 } else if (!CarryIn &&
1423 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1424 CarryOut = false; // 0 + anything has no carry out if no carry in.
1425 } else {
1426 // Otherwise, we have to assume we have a carry out.
1427 CarryOut = true;
1428 }
1429
1430 // This stage's carry out becomes the next stage's carry-in.
1431 CarryIn = CarryOut;
1432 }
1433
1434 // Now that we know which bits have carries, compute the known-1/0 sets.
1435
1436 // Bits are known one if they are known zero in one operand and one in the
1437 // other, and there is no input carry.
1438 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1439
1440 // Bits are known zero if they are known zero in both operands and there
1441 // is no input carry.
1442 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner5fdded12007-03-05 00:02:29 +00001443 } else {
1444 // If the high-bits of this ADD are not demanded, then it does not demand
1445 // the high bits of its LHS or RHS.
1446 if ((DemandedMask & VTy->getSignBit()) == 0) {
1447 // Right fill the mask of bits for this ADD to demand the most
1448 // significant bit and all those below it.
1449 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1450 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1451 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1452 KnownZero2, KnownOne2, Depth+1))
1453 return true;
1454 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1455 KnownZero2, KnownOne2, Depth+1))
1456 return true;
1457 }
1458 }
1459 break;
1460 case Instruction::Sub:
1461 // If the high-bits of this SUB are not demanded, then it does not demand
1462 // the high bits of its LHS or RHS.
1463 if ((DemandedMask & VTy->getSignBit()) == 0) {
1464 // Right fill the mask of bits for this SUB to demand the most
1465 // significant bit and all those below it.
1466 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1467 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1469 KnownZero2, KnownOne2, Depth+1))
1470 return true;
1471 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1472 KnownZero2, KnownOne2, Depth+1))
1473 return true;
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001474 }
1475 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001476 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001477 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1478 uint64_t ShiftAmt = SA->getZExtValue();
1479 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001480 KnownZero, KnownOne, Depth+1))
1481 return true;
1482 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001483 KnownZero <<= ShiftAmt;
1484 KnownOne <<= ShiftAmt;
1485 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001486 }
Chris Lattner2590e512006-02-07 06:56:34 +00001487 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001488 case Instruction::LShr:
1489 // For a logical shift right
1490 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1491 unsigned ShiftAmt = SA->getZExtValue();
1492
1493 // Compute the new bits that are at the top now.
1494 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001495 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1496 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001497 // Unsigned shift right.
1498 if (SimplifyDemandedBits(I->getOperand(0),
1499 (DemandedMask << ShiftAmt) & TypeMask,
1500 KnownZero, KnownOne, Depth+1))
1501 return true;
1502 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1503 KnownZero &= TypeMask;
1504 KnownOne &= TypeMask;
1505 KnownZero >>= ShiftAmt;
1506 KnownOne >>= ShiftAmt;
1507 KnownZero |= HighBits; // high bits known zero.
1508 }
1509 break;
1510 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001511 // If this is an arithmetic shift right and only the low-bit is set, we can
1512 // always convert this into a logical shr, even if the shift amount is
1513 // variable. The low bit of the shift cannot be an input sign bit unless
1514 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001515 if (DemandedMask == 1) {
1516 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001517 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001518 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001519 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001520 return UpdateValueUsesWith(I, NewVal);
1521 }
1522
Reid Spencere0fc4df2006-10-20 07:07:24 +00001523 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1524 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001525
1526 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001527 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001528 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1529 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001530 // Signed shift right.
1531 if (SimplifyDemandedBits(I->getOperand(0),
1532 (DemandedMask << ShiftAmt) & TypeMask,
1533 KnownZero, KnownOne, Depth+1))
1534 return true;
1535 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1536 KnownZero &= TypeMask;
1537 KnownOne &= TypeMask;
1538 KnownZero >>= ShiftAmt;
1539 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001540
Reid Spencerfdff9382006-11-08 06:47:33 +00001541 // Handle the sign bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001542 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00001543 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001544
Reid Spencerfdff9382006-11-08 06:47:33 +00001545 // If the input sign bit is known to be zero, or if none of the top bits
1546 // are demanded, turn this into an unsigned shift right.
1547 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1548 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001549 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001550 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001551 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1552 return UpdateValueUsesWith(I, NewVal);
1553 } else if (KnownOne & SignBit) { // New bits are known one.
1554 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001555 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001556 }
Chris Lattner2590e512006-02-07 06:56:34 +00001557 break;
1558 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001559
1560 // If the client is only demanding bits that we know, return the known
1561 // constant.
1562 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001563 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001564 return false;
1565}
1566
Reid Spencer1791f232007-03-12 17:25:59 +00001567/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1568/// value based on the demanded bits. When this function is called, it is known
1569/// that only the bits set in DemandedMask of the result of V are ever used
1570/// downstream. Consequently, depending on the mask and V, it may be possible
1571/// to replace V with a constant or one of its operands. In such cases, this
1572/// function does the replacement and returns true. In all other cases, it
1573/// returns false after analyzing the expression and setting KnownOne and known
1574/// to be one in the expression. KnownZero contains all the bits that are known
1575/// to be zero in the expression. These are provided to potentially allow the
1576/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1577/// the expression. KnownOne and KnownZero always follow the invariant that
1578/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1579/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1580/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1581/// and KnownOne must all be the same.
1582bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1583 APInt& KnownZero, APInt& KnownOne,
1584 unsigned Depth) {
1585 assert(V != 0 && "Null pointer of Value???");
1586 assert(Depth <= 6 && "Limit Search Depth");
1587 uint32_t BitWidth = DemandedMask.getBitWidth();
1588 const IntegerType *VTy = cast<IntegerType>(V->getType());
1589 assert(VTy->getBitWidth() == BitWidth &&
1590 KnownZero.getBitWidth() == BitWidth &&
1591 KnownOne.getBitWidth() == BitWidth &&
1592 "Value *V, DemandedMask, KnownZero and KnownOne \
1593 must have same BitWidth");
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1595 // We know all of the bits for a constant!
1596 KnownOne = CI->getValue() & DemandedMask;
1597 KnownZero = ~KnownOne & DemandedMask;
1598 return false;
1599 }
1600
1601 //KnownZero.clear();
1602 //KnownOne.clear();
1603 if (!V->hasOneUse()) { // Other users may use these bits.
1604 if (Depth != 0) { // Not at the root.
1605 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1606 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1607 return false;
1608 }
1609 // If this is the root being simplified, allow it to have multiple uses,
1610 // just set the DemandedMask to all bits.
1611 DemandedMask = APInt::getAllOnesValue(BitWidth);
1612 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1613 if (V != UndefValue::get(VTy))
1614 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1615 return false;
1616 } else if (Depth == 6) { // Limit search depth.
1617 return false;
1618 }
1619
1620 Instruction *I = dyn_cast<Instruction>(V);
1621 if (!I) return false; // Only analyze instructions.
1622
1623 DemandedMask &= APInt::getAllOnesValue(BitWidth);
1624
1625 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1626 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1627 switch (I->getOpcode()) {
1628 default: break;
1629 case Instruction::And:
1630 // If either the LHS or the RHS are Zero, the result is zero.
1631 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1632 RHSKnownZero, RHSKnownOne, Depth+1))
1633 return true;
1634 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1635 "Bits known to be one AND zero?");
1636
1637 // If something is known zero on the RHS, the bits aren't demanded on the
1638 // LHS.
1639 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1643 "Bits known to be one AND zero?");
1644
1645 // If all of the demanded bits are known 1 on one side, return the other.
1646 // These bits cannot contribute to the result of the 'and'.
1647 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1648 (DemandedMask & ~LHSKnownZero))
1649 return UpdateValueUsesWith(I, I->getOperand(0));
1650 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1651 (DemandedMask & ~RHSKnownZero))
1652 return UpdateValueUsesWith(I, I->getOperand(1));
1653
1654 // If all of the demanded bits in the inputs are known zeros, return zero.
1655 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1656 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1657
1658 // If the RHS is a constant, see if we can simplify it.
1659 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1660 return UpdateValueUsesWith(I, I);
1661
1662 // Output known-1 bits are only known if set in both the LHS & RHS.
1663 RHSKnownOne &= LHSKnownOne;
1664 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1665 RHSKnownZero |= LHSKnownZero;
1666 break;
1667 case Instruction::Or:
1668 // If either the LHS or the RHS are One, the result is One.
1669 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1670 RHSKnownZero, RHSKnownOne, Depth+1))
1671 return true;
1672 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1673 "Bits known to be one AND zero?");
1674 // If something is known one on the RHS, the bits aren't demanded on the
1675 // LHS.
1676 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1677 LHSKnownZero, LHSKnownOne, Depth+1))
1678 return true;
1679 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1680 "Bits known to be one AND zero?");
1681
1682 // If all of the demanded bits are known zero on one side, return the other.
1683 // These bits cannot contribute to the result of the 'or'.
1684 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1685 (DemandedMask & ~LHSKnownOne))
1686 return UpdateValueUsesWith(I, I->getOperand(0));
1687 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1688 (DemandedMask & ~RHSKnownOne))
1689 return UpdateValueUsesWith(I, I->getOperand(1));
1690
1691 // If all of the potentially set bits on one side are known to be set on
1692 // the other side, just use the 'other' side.
1693 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1694 (DemandedMask & (~RHSKnownZero)))
1695 return UpdateValueUsesWith(I, I->getOperand(0));
1696 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1697 (DemandedMask & (~LHSKnownZero)))
1698 return UpdateValueUsesWith(I, I->getOperand(1));
1699
1700 // If the RHS is a constant, see if we can simplify it.
1701 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1702 return UpdateValueUsesWith(I, I);
1703
1704 // Output known-0 bits are only known if clear in both the LHS & RHS.
1705 RHSKnownZero &= LHSKnownZero;
1706 // Output known-1 are known to be set if set in either the LHS | RHS.
1707 RHSKnownOne |= LHSKnownOne;
1708 break;
1709 case Instruction::Xor: {
1710 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1711 RHSKnownZero, RHSKnownOne, Depth+1))
1712 return true;
1713 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1714 "Bits known to be one AND zero?");
1715 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1716 LHSKnownZero, LHSKnownOne, Depth+1))
1717 return true;
1718 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1719 "Bits known to be one AND zero?");
1720
1721 // If all of the demanded bits are known zero on one side, return the other.
1722 // These bits cannot contribute to the result of the 'xor'.
1723 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1724 return UpdateValueUsesWith(I, I->getOperand(0));
1725 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1726 return UpdateValueUsesWith(I, I->getOperand(1));
1727
1728 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1729 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1730 (RHSKnownOne & LHSKnownOne);
1731 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1732 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1733 (RHSKnownOne & LHSKnownZero);
1734
1735 // If all of the demanded bits are known to be zero on one side or the
1736 // other, turn this into an *inclusive* or.
1737 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1738 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1739 Instruction *Or =
1740 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1741 I->getName());
1742 InsertNewInstBefore(Or, *I);
1743 return UpdateValueUsesWith(I, Or);
1744 }
1745
1746 // If all of the demanded bits on one side are known, and all of the set
1747 // bits on that side are also known to be set on the other side, turn this
1748 // into an AND, as we know the bits will be cleared.
1749 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1750 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1751 // all known
1752 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1753 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1754 Instruction *And =
1755 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1756 InsertNewInstBefore(And, *I);
1757 return UpdateValueUsesWith(I, And);
1758 }
1759 }
1760
1761 // If the RHS is a constant, see if we can simplify it.
1762 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1763 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1764 return UpdateValueUsesWith(I, I);
1765
1766 RHSKnownZero = KnownZeroOut;
1767 RHSKnownOne = KnownOneOut;
1768 break;
1769 }
1770 case Instruction::Select:
1771 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1772 RHSKnownZero, RHSKnownOne, Depth+1))
1773 return true;
1774 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1775 LHSKnownZero, LHSKnownOne, Depth+1))
1776 return true;
1777 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1778 "Bits known to be one AND zero?");
1779 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1780 "Bits known to be one AND zero?");
1781
1782 // If the operands are constants, see if we can simplify them.
1783 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1784 return UpdateValueUsesWith(I, I);
1785 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1786 return UpdateValueUsesWith(I, I);
1787
1788 // Only known if known in both the LHS and RHS.
1789 RHSKnownOne &= LHSKnownOne;
1790 RHSKnownZero &= LHSKnownZero;
1791 break;
1792 case Instruction::Trunc: {
1793 uint32_t truncBf =
1794 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1795 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1796 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1797 return true;
1798 DemandedMask.trunc(BitWidth);
1799 RHSKnownZero.trunc(BitWidth);
1800 RHSKnownOne.trunc(BitWidth);
1801 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1802 "Bits known to be one AND zero?");
1803 break;
1804 }
1805 case Instruction::BitCast:
1806 if (!I->getOperand(0)->getType()->isInteger())
1807 return false;
1808
1809 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1810 RHSKnownZero, RHSKnownOne, Depth+1))
1811 return true;
1812 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1813 "Bits known to be one AND zero?");
1814 break;
1815 case Instruction::ZExt: {
1816 // Compute the bits in the result that are not present in the input.
1817 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1818 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1819
1820 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1821 uint32_t zextBf = SrcTy->getBitWidth();
1822 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1823 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1824 return true;
1825 DemandedMask.zext(BitWidth);
1826 RHSKnownZero.zext(BitWidth);
1827 RHSKnownOne.zext(BitWidth);
1828 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1829 "Bits known to be one AND zero?");
1830 // The top bits are known to be zero.
1831 RHSKnownZero |= NewBits;
1832 break;
1833 }
1834 case Instruction::SExt: {
1835 // Compute the bits in the result that are not present in the input.
1836 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1837 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1838
1839 // Get the sign bit for the source type
1840 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1841 InSignBit.zext(BitWidth);
1842 APInt InputDemandedBits = DemandedMask &
1843 SrcTy->getMask().zext(BitWidth);
1844
1845 // If any of the sign extended bits are demanded, we know that the sign
1846 // bit is demanded.
1847 if ((NewBits & DemandedMask) != 0)
1848 InputDemandedBits |= InSignBit;
1849
1850 uint32_t sextBf = SrcTy->getBitWidth();
1851 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1852 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1853 return true;
1854 InputDemandedBits.zext(BitWidth);
1855 RHSKnownZero.zext(BitWidth);
1856 RHSKnownOne.zext(BitWidth);
1857 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1858 "Bits known to be one AND zero?");
1859
1860 // If the sign bit of the input is known set or clear, then we know the
1861 // top bits of the result.
1862
1863 // If the input sign bit is known zero, or if the NewBits are not demanded
1864 // convert this into a zero extension.
1865 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1866 {
1867 // Convert to ZExt cast
1868 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1869 return UpdateValueUsesWith(I, NewCast);
1870 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1871 RHSKnownOne |= NewBits;
1872 RHSKnownZero &= ~NewBits;
1873 } else { // Input sign bit unknown
1874 RHSKnownZero &= ~NewBits;
1875 RHSKnownOne &= ~NewBits;
1876 }
1877 break;
1878 }
1879 case Instruction::Add: {
1880 // Figure out what the input bits are. If the top bits of the and result
1881 // are not demanded, then the add doesn't demand them from its input
1882 // either.
1883 unsigned NLZ = DemandedMask.countLeadingZeros();
1884
1885 // If there is a constant on the RHS, there are a variety of xformations
1886 // we can do.
1887 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1888 // If null, this should be simplified elsewhere. Some of the xforms here
1889 // won't work if the RHS is zero.
1890 if (RHS->isZero())
1891 break;
1892
1893 // If the top bit of the output is demanded, demand everything from the
1894 // input. Otherwise, we demand all the input bits except NLZ top bits.
1895 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1896
1897 // Find information about known zero/one bits in the input.
1898 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1899 LHSKnownZero, LHSKnownOne, Depth+1))
1900 return true;
1901
1902 // If the RHS of the add has bits set that can't affect the input, reduce
1903 // the constant.
1904 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1905 return UpdateValueUsesWith(I, I);
1906
1907 // Avoid excess work.
1908 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1909 break;
1910
1911 // Turn it into OR if input bits are zero.
1912 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1913 Instruction *Or =
1914 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1915 I->getName());
1916 InsertNewInstBefore(Or, *I);
1917 return UpdateValueUsesWith(I, Or);
1918 }
1919
1920 // We can say something about the output known-zero and known-one bits,
1921 // depending on potential carries from the input constant and the
1922 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1923 // bits set and the RHS constant is 0x01001, then we know we have a known
1924 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1925
1926 // To compute this, we first compute the potential carry bits. These are
1927 // the bits which may be modified. I'm not aware of a better way to do
1928 // this scan.
1929 APInt RHSVal(RHS->getValue());
1930
1931 bool CarryIn = false;
1932 APInt CarryBits(BitWidth, 0);
1933 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1934 *RHSRawVal = RHSVal.getRawData();
1935 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1936 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1937 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1938 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1939 if (AddVal < RHSRawVal[i])
1940 CarryIn = true;
1941 else
1942 CarryIn = false;
1943 CarryBits.setWordToValue(i, WordCarryBits);
1944 }
1945
1946 // Now that we know which bits have carries, compute the known-1/0 sets.
1947
1948 // Bits are known one if they are known zero in one operand and one in the
1949 // other, and there is no input carry.
1950 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1951 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1952
1953 // Bits are known zero if they are known zero in both operands and there
1954 // is no input carry.
1955 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1956 } else {
1957 // If the high-bits of this ADD are not demanded, then it does not demand
1958 // the high bits of its LHS or RHS.
1959 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1960 // Right fill the mask of bits for this ADD to demand the most
1961 // significant bit and all those below it.
1962 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1963 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1964 LHSKnownZero, LHSKnownOne, Depth+1))
1965 return true;
1966 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1967 LHSKnownZero, LHSKnownOne, Depth+1))
1968 return true;
1969 }
1970 }
1971 break;
1972 }
1973 case Instruction::Sub:
1974 // If the high-bits of this SUB are not demanded, then it does not demand
1975 // the high bits of its LHS or RHS.
1976 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1977 // Right fill the mask of bits for this SUB to demand the most
1978 // significant bit and all those below it.
1979 unsigned NLZ = DemandedMask.countLeadingZeros();
1980 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1981 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1982 LHSKnownZero, LHSKnownOne, Depth+1))
1983 return true;
1984 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1985 LHSKnownZero, LHSKnownOne, Depth+1))
1986 return true;
1987 }
1988 break;
1989 case Instruction::Shl:
1990 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1991 uint64_t ShiftAmt = SA->getZExtValue();
1992 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1993 RHSKnownZero, RHSKnownOne, Depth+1))
1994 return true;
1995 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1996 "Bits known to be one AND zero?");
1997 RHSKnownZero <<= ShiftAmt;
1998 RHSKnownOne <<= ShiftAmt;
1999 // low bits known zero.
Zhou Shengebe634e2007-03-13 06:40:59 +00002000 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00002001 }
2002 break;
2003 case Instruction::LShr:
2004 // For a logical shift right
2005 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2006 unsigned ShiftAmt = SA->getZExtValue();
2007
2008 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2009 // Unsigned shift right.
2010 if (SimplifyDemandedBits(I->getOperand(0),
2011 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2012 RHSKnownZero, RHSKnownOne, Depth+1))
2013 return true;
2014 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2015 "Bits known to be one AND zero?");
2016 // Compute the new bits that are at the top now.
Zhou Shengebe634e2007-03-13 06:40:59 +00002017 APInt HighBits(APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth).shl(
Reid Spencer1791f232007-03-12 17:25:59 +00002018 BitWidth - ShiftAmt));
2019 RHSKnownZero &= TypeMask;
2020 RHSKnownOne &= TypeMask;
2021 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2022 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2023 RHSKnownZero |= HighBits; // high bits known zero.
2024 }
2025 break;
2026 case Instruction::AShr:
2027 // If this is an arithmetic shift right and only the low-bit is set, we can
2028 // always convert this into a logical shr, even if the shift amount is
2029 // variable. The low bit of the shift cannot be an input sign bit unless
2030 // the shift amount is >= the size of the datatype, which is undefined.
2031 if (DemandedMask == 1) {
2032 // Perform the logical shift right.
2033 Value *NewVal = BinaryOperator::createLShr(
2034 I->getOperand(0), I->getOperand(1), I->getName());
2035 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2036 return UpdateValueUsesWith(I, NewVal);
2037 }
2038
2039 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2040 unsigned ShiftAmt = SA->getZExtValue();
2041
2042 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2043 // Signed shift right.
2044 if (SimplifyDemandedBits(I->getOperand(0),
2045 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2046 RHSKnownZero, RHSKnownOne, Depth+1))
2047 return true;
2048 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2049 "Bits known to be one AND zero?");
2050 // Compute the new bits that are at the top now.
Zhou Shengebe634e2007-03-13 06:40:59 +00002051 APInt HighBits(APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth).shl(
Reid Spencer1791f232007-03-12 17:25:59 +00002052 BitWidth - ShiftAmt));
2053 RHSKnownZero &= TypeMask;
2054 RHSKnownOne &= TypeMask;
2055 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2056 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2057
2058 // Handle the sign bits.
2059 APInt SignBit(APInt::getSignBit(BitWidth));
2060 // Adjust to where it is now in the mask.
2061 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
2062
2063 // If the input sign bit is known to be zero, or if none of the top bits
2064 // are demanded, turn this into an unsigned shift right.
2065 if ((RHSKnownZero & SignBit) != 0 ||
2066 (HighBits & ~DemandedMask) == HighBits) {
2067 // Perform the logical shift right.
2068 Value *NewVal = BinaryOperator::createLShr(
2069 I->getOperand(0), SA, I->getName());
2070 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2071 return UpdateValueUsesWith(I, NewVal);
2072 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2073 RHSKnownOne |= HighBits;
2074 }
2075 }
2076 break;
2077 }
2078
2079 // If the client is only demanding bits that we know, return the known
2080 // constant.
2081 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2082 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2083 return false;
2084}
2085
Chris Lattner2deeaea2006-10-05 06:55:50 +00002086
2087/// SimplifyDemandedVectorElts - The specified value producecs a vector with
2088/// 64 or fewer elements. DemandedElts contains the set of elements that are
2089/// actually used by the caller. This method analyzes which elements of the
2090/// operand are undef and returns that information in UndefElts.
2091///
2092/// If the information about demanded elements can be used to simplify the
2093/// operation, the operation is simplified, then the resultant value is
2094/// returned. This returns null if no change was made.
2095Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2096 uint64_t &UndefElts,
2097 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002098 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002099 assert(VWidth <= 64 && "Vector too wide to analyze!");
2100 uint64_t EltMask = ~0ULL >> (64-VWidth);
2101 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2102 "Invalid DemandedElts!");
2103
2104 if (isa<UndefValue>(V)) {
2105 // If the entire vector is undefined, just return this info.
2106 UndefElts = EltMask;
2107 return 0;
2108 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2109 UndefElts = EltMask;
2110 return UndefValue::get(V->getType());
2111 }
2112
2113 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002114 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2115 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002116 Constant *Undef = UndefValue::get(EltTy);
2117
2118 std::vector<Constant*> Elts;
2119 for (unsigned i = 0; i != VWidth; ++i)
2120 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
2121 Elts.push_back(Undef);
2122 UndefElts |= (1ULL << i);
2123 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
2124 Elts.push_back(Undef);
2125 UndefElts |= (1ULL << i);
2126 } else { // Otherwise, defined.
2127 Elts.push_back(CP->getOperand(i));
2128 }
2129
2130 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002131 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00002132 return NewCP != CP ? NewCP : 0;
2133 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002134 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00002135 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002136 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002137 Constant *Zero = Constant::getNullValue(EltTy);
2138 Constant *Undef = UndefValue::get(EltTy);
2139 std::vector<Constant*> Elts;
2140 for (unsigned i = 0; i != VWidth; ++i)
2141 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2142 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002143 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00002144 }
2145
2146 if (!V->hasOneUse()) { // Other users may use these bits.
2147 if (Depth != 0) { // Not at the root.
2148 // TODO: Just compute the UndefElts information recursively.
2149 return false;
2150 }
2151 return false;
2152 } else if (Depth == 10) { // Limit search depth.
2153 return false;
2154 }
2155
2156 Instruction *I = dyn_cast<Instruction>(V);
2157 if (!I) return false; // Only analyze instructions.
2158
2159 bool MadeChange = false;
2160 uint64_t UndefElts2;
2161 Value *TmpV;
2162 switch (I->getOpcode()) {
2163 default: break;
2164
2165 case Instruction::InsertElement: {
2166 // If this is a variable index, we don't know which element it overwrites.
2167 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002168 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00002169 if (Idx == 0) {
2170 // Note that we can't propagate undef elt info, because we don't know
2171 // which elt is getting updated.
2172 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2173 UndefElts2, Depth+1);
2174 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2175 break;
2176 }
2177
2178 // If this is inserting an element that isn't demanded, remove this
2179 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002180 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002181 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2182 return AddSoonDeadInstToWorklist(*I, 0);
2183
2184 // Otherwise, the element inserted overwrites whatever was there, so the
2185 // input demanded set is simpler than the output set.
2186 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2187 DemandedElts & ~(1ULL << IdxNo),
2188 UndefElts, Depth+1);
2189 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2190
2191 // The inserted element is defined.
2192 UndefElts |= 1ULL << IdxNo;
2193 break;
2194 }
2195
2196 case Instruction::And:
2197 case Instruction::Or:
2198 case Instruction::Xor:
2199 case Instruction::Add:
2200 case Instruction::Sub:
2201 case Instruction::Mul:
2202 // div/rem demand all inputs, because they don't want divide by zero.
2203 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2204 UndefElts, Depth+1);
2205 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2206 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2207 UndefElts2, Depth+1);
2208 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2209
2210 // Output elements are undefined if both are undefined. Consider things
2211 // like undef&0. The result is known zero, not undef.
2212 UndefElts &= UndefElts2;
2213 break;
2214
2215 case Instruction::Call: {
2216 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2217 if (!II) break;
2218 switch (II->getIntrinsicID()) {
2219 default: break;
2220
2221 // Binary vector operations that work column-wise. A dest element is a
2222 // function of the corresponding input elements from the two inputs.
2223 case Intrinsic::x86_sse_sub_ss:
2224 case Intrinsic::x86_sse_mul_ss:
2225 case Intrinsic::x86_sse_min_ss:
2226 case Intrinsic::x86_sse_max_ss:
2227 case Intrinsic::x86_sse2_sub_sd:
2228 case Intrinsic::x86_sse2_mul_sd:
2229 case Intrinsic::x86_sse2_min_sd:
2230 case Intrinsic::x86_sse2_max_sd:
2231 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2232 UndefElts, Depth+1);
2233 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2234 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2235 UndefElts2, Depth+1);
2236 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2237
2238 // If only the low elt is demanded and this is a scalarizable intrinsic,
2239 // scalarize it now.
2240 if (DemandedElts == 1) {
2241 switch (II->getIntrinsicID()) {
2242 default: break;
2243 case Intrinsic::x86_sse_sub_ss:
2244 case Intrinsic::x86_sse_mul_ss:
2245 case Intrinsic::x86_sse2_sub_sd:
2246 case Intrinsic::x86_sse2_mul_sd:
2247 // TODO: Lower MIN/MAX/ABS/etc
2248 Value *LHS = II->getOperand(1);
2249 Value *RHS = II->getOperand(2);
2250 // Extract the element as scalars.
2251 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2252 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2253
2254 switch (II->getIntrinsicID()) {
2255 default: assert(0 && "Case stmts out of sync!");
2256 case Intrinsic::x86_sse_sub_ss:
2257 case Intrinsic::x86_sse2_sub_sd:
2258 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2259 II->getName()), *II);
2260 break;
2261 case Intrinsic::x86_sse_mul_ss:
2262 case Intrinsic::x86_sse2_mul_sd:
2263 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2264 II->getName()), *II);
2265 break;
2266 }
2267
2268 Instruction *New =
2269 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2270 II->getName());
2271 InsertNewInstBefore(New, *II);
2272 AddSoonDeadInstToWorklist(*II, 0);
2273 return New;
2274 }
2275 }
2276
2277 // Output elements are undefined if both are undefined. Consider things
2278 // like undef&0. The result is known zero, not undef.
2279 UndefElts &= UndefElts2;
2280 break;
2281 }
2282 break;
2283 }
2284 }
2285 return MadeChange ? I : 0;
2286}
2287
Reid Spencer266e42b2006-12-23 06:05:41 +00002288/// @returns true if the specified compare instruction is
2289/// true when both operands are equal...
2290/// @brief Determine if the ICmpInst returns true if both operands are equal
2291static bool isTrueWhenEqual(ICmpInst &ICI) {
2292 ICmpInst::Predicate pred = ICI.getPredicate();
2293 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2294 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2295 pred == ICmpInst::ICMP_SLE;
2296}
2297
Chris Lattnerb8b97502003-08-13 19:01:45 +00002298/// AssociativeOpt - Perform an optimization on an associative operator. This
2299/// function is designed to check a chain of associative operators for a
2300/// potential to apply a certain optimization. Since the optimization may be
2301/// applicable if the expression was reassociated, this checks the chain, then
2302/// reassociates the expression as necessary to expose the optimization
2303/// opportunity. This makes use of a special Functor, which must define
2304/// 'shouldApply' and 'apply' methods.
2305///
2306template<typename Functor>
2307Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2308 unsigned Opcode = Root.getOpcode();
2309 Value *LHS = Root.getOperand(0);
2310
2311 // Quick check, see if the immediate LHS matches...
2312 if (F.shouldApply(LHS))
2313 return F.apply(Root);
2314
2315 // Otherwise, if the LHS is not of the same opcode as the root, return.
2316 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002317 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002318 // Should we apply this transform to the RHS?
2319 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2320
2321 // If not to the RHS, check to see if we should apply to the LHS...
2322 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2323 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2324 ShouldApply = true;
2325 }
2326
2327 // If the functor wants to apply the optimization to the RHS of LHSI,
2328 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2329 if (ShouldApply) {
2330 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002331
Chris Lattnerb8b97502003-08-13 19:01:45 +00002332 // Now all of the instructions are in the current basic block, go ahead
2333 // and perform the reassociation.
2334 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2335
2336 // First move the selected RHS to the LHS of the root...
2337 Root.setOperand(0, LHSI->getOperand(1));
2338
2339 // Make what used to be the LHS of the root be the user of the root...
2340 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00002341 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00002342 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2343 return 0;
2344 }
Chris Lattner284d3b02004-04-16 18:08:07 +00002345 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00002346 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00002347 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2348 BasicBlock::iterator ARI = &Root; ++ARI;
2349 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2350 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00002351
2352 // Now propagate the ExtraOperand down the chain of instructions until we
2353 // get to LHSI.
2354 while (TmpLHSI != LHSI) {
2355 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00002356 // Move the instruction to immediately before the chain we are
2357 // constructing to avoid breaking dominance properties.
2358 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2359 BB->getInstList().insert(ARI, NextLHSI);
2360 ARI = NextLHSI;
2361
Chris Lattnerb8b97502003-08-13 19:01:45 +00002362 Value *NextOp = NextLHSI->getOperand(1);
2363 NextLHSI->setOperand(1, ExtraOperand);
2364 TmpLHSI = NextLHSI;
2365 ExtraOperand = NextOp;
2366 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002367
Chris Lattnerb8b97502003-08-13 19:01:45 +00002368 // Now that the instructions are reassociated, have the functor perform
2369 // the transformation...
2370 return F.apply(Root);
2371 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002372
Chris Lattnerb8b97502003-08-13 19:01:45 +00002373 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2374 }
2375 return 0;
2376}
2377
2378
2379// AddRHS - Implements: X + X --> X << 1
2380struct AddRHS {
2381 Value *RHS;
2382 AddRHS(Value *rhs) : RHS(rhs) {}
2383 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2384 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00002385 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00002386 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002387 }
2388};
2389
2390// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2391// iff C1&C2 == 0
2392struct AddMaskingAnd {
2393 Constant *C2;
2394 AddMaskingAnd(Constant *c) : C2(c) {}
2395 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00002396 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002397 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002398 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00002399 }
2400 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002401 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002402 }
2403};
2404
Chris Lattner86102b82005-01-01 16:22:27 +00002405static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00002406 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002407 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002408 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002409 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002410
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002411 return IC->InsertNewInstBefore(CastInst::create(
2412 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00002413 }
2414
Chris Lattner183b3362004-04-09 19:05:30 +00002415 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00002416 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2417 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002418
Chris Lattner183b3362004-04-09 19:05:30 +00002419 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2420 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00002421 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2422 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00002423 }
2424
2425 Value *Op0 = SO, *Op1 = ConstOperand;
2426 if (!ConstIsRHS)
2427 std::swap(Op0, Op1);
2428 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00002429 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2430 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00002431 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2432 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2433 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002434 else {
Chris Lattner183b3362004-04-09 19:05:30 +00002435 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002436 abort();
2437 }
Chris Lattner86102b82005-01-01 16:22:27 +00002438 return IC->InsertNewInstBefore(New, I);
2439}
2440
2441// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2442// constant as the other operand, try to fold the binary operator into the
2443// select arguments. This also works for Cast instructions, which obviously do
2444// not have a second operand.
2445static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2446 InstCombiner *IC) {
2447 // Don't modify shared select instructions
2448 if (!SI->hasOneUse()) return 0;
2449 Value *TV = SI->getOperand(1);
2450 Value *FV = SI->getOperand(2);
2451
2452 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00002453 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00002454 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00002455
Chris Lattner86102b82005-01-01 16:22:27 +00002456 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2457 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2458
2459 return new SelectInst(SI->getCondition(), SelectTrueVal,
2460 SelectFalseVal);
2461 }
2462 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00002463}
2464
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002465
2466/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2467/// node as operand #0, see if we can fold the instruction into the PHI (which
2468/// is only possible if all operands to the PHI are constants).
2469Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2470 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00002471 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00002472 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002473
Chris Lattner04689872006-09-09 22:02:56 +00002474 // Check to see if all of the operands of the PHI are constants. If there is
2475 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002476 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00002477 BasicBlock *NonConstBB = 0;
2478 for (unsigned i = 0; i != NumPHIValues; ++i)
2479 if (!isa<Constant>(PN->getIncomingValue(i))) {
2480 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002481 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00002482 NonConstBB = PN->getIncomingBlock(i);
2483
2484 // If the incoming non-constant value is in I's block, we have an infinite
2485 // loop.
2486 if (NonConstBB == I.getParent())
2487 return 0;
2488 }
2489
2490 // If there is exactly one non-constant value, we can insert a copy of the
2491 // operation in that block. However, if this is a critical edge, we would be
2492 // inserting the computation one some other paths (e.g. inside a loop). Only
2493 // do this if the pred block is unconditionally branching into the phi block.
2494 if (NonConstBB) {
2495 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2496 if (!BI || !BI->isUnconditional()) return 0;
2497 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002498
2499 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002500 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00002501 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002502 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002503 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002504
2505 // Next, add all of the operands to the PHI.
2506 if (I.getNumOperands() == 2) {
2507 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00002508 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002509 Value *InV;
2510 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002511 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2512 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2513 else
2514 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00002515 } else {
2516 assert(PN->getIncomingBlock(i) == NonConstBB);
2517 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2518 InV = BinaryOperator::create(BO->getOpcode(),
2519 PN->getIncomingValue(i), C, "phitmp",
2520 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00002521 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2522 InV = CmpInst::create(CI->getOpcode(),
2523 CI->getPredicate(),
2524 PN->getIncomingValue(i), C, "phitmp",
2525 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00002526 else
2527 assert(0 && "Unknown binop!");
2528
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002529 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002530 }
2531 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002532 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002533 } else {
2534 CastInst *CI = cast<CastInst>(&I);
2535 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00002536 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002537 Value *InV;
2538 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002539 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00002540 } else {
2541 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002542 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2543 I.getType(), "phitmp",
2544 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002545 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002546 }
2547 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002548 }
2549 }
2550 return ReplaceInstUsesWith(I, NewPN);
2551}
2552
Chris Lattner113f4f42002-06-25 16:13:24 +00002553Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002554 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002555 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002556
Chris Lattnercf4a9962004-04-10 22:01:55 +00002557 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00002558 // X + undef -> undef
2559 if (isa<UndefValue>(RHS))
2560 return ReplaceInstUsesWith(I, RHS);
2561
Chris Lattnercf4a9962004-04-10 22:01:55 +00002562 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002563 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002564 if (RHSC->isNullValue())
2565 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002566 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2567 if (CFP->isExactlyValue(-0.0))
2568 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002569 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002570
Chris Lattnercf4a9962004-04-10 22:01:55 +00002571 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002572 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00002573 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00002574 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002575 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002576
2577 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2578 // (X & 254)+1 -> (X&254)|1
2579 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002580 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00002581 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002582 KnownZero, KnownOne))
2583 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00002584 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002585
2586 if (isa<PHINode>(LHS))
2587 if (Instruction *NV = FoldOpIntoPhi(I))
2588 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002589
Chris Lattner330628a2006-01-06 17:59:59 +00002590 ConstantInt *XorRHS = 0;
2591 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002592 if (isa<ConstantInt>(RHSC) &&
2593 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002594 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2595 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2596 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2597
2598 uint64_t C0080Val = 1ULL << 31;
2599 int64_t CFF80Val = -C0080Val;
2600 unsigned Size = 32;
2601 do {
2602 if (TySizeBits > Size) {
2603 bool Found = false;
2604 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2605 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2606 if (RHSSExt == CFF80Val) {
2607 if (XorRHS->getZExtValue() == C0080Val)
2608 Found = true;
2609 } else if (RHSZExt == C0080Val) {
2610 if (XorRHS->getSExtValue() == CFF80Val)
2611 Found = true;
2612 }
2613 if (Found) {
2614 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002615 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002616 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00002617 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002618 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002619 Size = 0; // Not a sign ext, but can't be any others either.
2620 goto FoundSExt;
2621 }
2622 }
2623 Size >>= 1;
2624 C0080Val >>= Size;
2625 CFF80Val >>= Size;
2626 } while (Size >= 8);
2627
2628FoundSExt:
2629 const Type *MiddleType = 0;
2630 switch (Size) {
2631 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00002632 case 32: MiddleType = Type::Int32Ty; break;
2633 case 16: MiddleType = Type::Int16Ty; break;
2634 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002635 }
2636 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002637 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002638 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002639 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002640 }
2641 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002642 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002643
Chris Lattnerb8b97502003-08-13 19:01:45 +00002644 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002645 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002646 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002647
2648 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2649 if (RHSI->getOpcode() == Instruction::Sub)
2650 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2651 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2652 }
2653 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2654 if (LHSI->getOpcode() == Instruction::Sub)
2655 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2656 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2657 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002658 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002659
Chris Lattner147e9752002-05-08 22:46:53 +00002660 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002661 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002662 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002663
2664 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002665 if (!isa<Constant>(RHS))
2666 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002667 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002668
Misha Brukmanb1c93172005-04-21 23:48:37 +00002669
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002670 ConstantInt *C2;
2671 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2672 if (X == RHS) // X*C + X --> X * (C+1)
2673 return BinaryOperator::createMul(RHS, AddOne(C2));
2674
2675 // X*C1 + X*C2 --> X * (C1+C2)
2676 ConstantInt *C1;
2677 if (X == dyn_castFoldableMul(RHS, C1))
2678 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002679 }
2680
2681 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002682 if (dyn_castFoldableMul(RHS, C2) == LHS)
2683 return BinaryOperator::createMul(LHS, AddOne(C2));
2684
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002685 // X + ~X --> -1 since ~X = -X-1
2686 if (dyn_castNotVal(LHS) == RHS ||
2687 dyn_castNotVal(RHS) == LHS)
2688 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2689
Chris Lattner57c8d992003-02-18 19:57:07 +00002690
Chris Lattnerb8b97502003-08-13 19:01:45 +00002691 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002692 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002693 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2694 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002695
Chris Lattnerb9cde762003-10-02 15:11:26 +00002696 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002697 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002698 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2699 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2700 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00002701 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00002702
Chris Lattnerbff91d92004-10-08 05:07:56 +00002703 // (X & FF00) + xx00 -> (X+xx00) & FF00
2704 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2705 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2706 if (Anded == CRHS) {
2707 // See if all bits from the first bit set in the Add RHS up are included
2708 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002709 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002710
2711 // Form a mask of all bits from the lowest bit added through the top.
2712 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00002713 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002714
2715 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002716 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002717
Chris Lattnerbff91d92004-10-08 05:07:56 +00002718 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2719 // Okay, the xform is safe. Insert the new add pronto.
2720 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2721 LHS->getName()), I);
2722 return BinaryOperator::createAnd(NewAdd, C2);
2723 }
2724 }
2725 }
2726
Chris Lattnerd4252a72004-07-30 07:50:03 +00002727 // Try to fold constant add into select arguments.
2728 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002729 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002730 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002731 }
2732
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002733 // add (cast *A to intptrtype) B ->
2734 // cast (GEP (cast *A to sbyte*) B) ->
2735 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002736 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002737 CastInst *CI = dyn_cast<CastInst>(LHS);
2738 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002739 if (!CI) {
2740 CI = dyn_cast<CastInst>(RHS);
2741 Other = LHS;
2742 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002743 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002744 (CI->getType()->getPrimitiveSizeInBits() ==
2745 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002746 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002747 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002748 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002749 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002750 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002751 }
2752 }
2753
Chris Lattner113f4f42002-06-25 16:13:24 +00002754 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002755}
2756
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002757// isSignBit - Return true if the value represented by the constant only has the
2758// highest order bit set.
2759static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002760 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00002761 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002762}
2763
Chris Lattner113f4f42002-06-25 16:13:24 +00002764Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002765 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002766
Chris Lattnere6794492002-08-12 21:17:25 +00002767 if (Op0 == Op1) // sub X, X -> 0
2768 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002769
Chris Lattnere6794492002-08-12 21:17:25 +00002770 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002771 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002772 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002773
Chris Lattner81a7a232004-10-16 18:11:37 +00002774 if (isa<UndefValue>(Op0))
2775 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2776 if (isa<UndefValue>(Op1))
2777 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2778
Chris Lattner8f2f5982003-11-05 01:06:05 +00002779 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2780 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002781 if (C->isAllOnesValue())
2782 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002783
Chris Lattner8f2f5982003-11-05 01:06:05 +00002784 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002785 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002786 if (match(Op1, m_Not(m_Value(X))))
2787 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002788 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00002789 // -(X >>u 31) -> (X >>s 31)
2790 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002791 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002792 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002793 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002794 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002795 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002796 if (CU->getZExtValue() ==
2797 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002798 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002799 return BinaryOperator::create(Instruction::AShr,
2800 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002801 }
2802 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002803 }
2804 else if (SI->getOpcode() == Instruction::AShr) {
2805 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2806 // Check to see if we are shifting out everything but the sign bit.
2807 if (CU->getZExtValue() ==
2808 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002809 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002810 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002811 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002812 }
2813 }
2814 }
Chris Lattner022167f2004-03-13 00:11:49 +00002815 }
Chris Lattner183b3362004-04-09 19:05:30 +00002816
2817 // Try to fold constant sub into select arguments.
2818 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002819 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002820 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002821
2822 if (isa<PHINode>(Op0))
2823 if (Instruction *NV = FoldOpIntoPhi(I))
2824 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002825 }
2826
Chris Lattnera9be4492005-04-07 16:15:25 +00002827 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2828 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002829 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002830 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002831 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002832 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002833 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002834 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2835 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2836 // C1-(X+C2) --> (C1-C2)-X
2837 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2838 Op1I->getOperand(0));
2839 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002840 }
2841
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002842 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002843 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2844 // is not used by anyone else...
2845 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002846 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002847 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002848 // Swap the two operands of the subexpr...
2849 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2850 Op1I->setOperand(0, IIOp1);
2851 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002852
Chris Lattner3082c5a2003-02-18 19:28:33 +00002853 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002854 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002855 }
2856
2857 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2858 //
2859 if (Op1I->getOpcode() == Instruction::And &&
2860 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2861 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2862
Chris Lattner396dbfe2004-06-09 05:08:07 +00002863 Value *NewNot =
2864 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002865 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002866 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002867
Reid Spencer3c514952006-10-16 23:08:08 +00002868 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002869 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002870 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002871 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002872 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002873 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002874 ConstantExpr::getNeg(DivRHS));
2875
Chris Lattner57c8d992003-02-18 19:57:07 +00002876 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002877 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002878 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002879 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002880 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002881 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002882 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002883 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002884 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002885
Chris Lattner7a002fe2006-12-02 00:13:08 +00002886 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002887 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2888 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002889 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2890 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2891 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2892 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002893 } else if (Op0I->getOpcode() == Instruction::Sub) {
2894 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2895 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002896 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002897
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002898 ConstantInt *C1;
2899 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2900 if (X == Op1) { // X*C - X --> X * (C-1)
2901 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2902 return BinaryOperator::createMul(Op1, CP1);
2903 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002904
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002905 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2906 if (X == dyn_castFoldableMul(Op1, C2))
2907 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2908 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002909 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002910}
2911
Reid Spencer266e42b2006-12-23 06:05:41 +00002912/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002913/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002914static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2915 switch (pred) {
2916 case ICmpInst::ICMP_SLT:
2917 // True if LHS s< RHS and RHS == 0
2918 return RHS->isNullValue();
2919 case ICmpInst::ICMP_SLE:
2920 // True if LHS s<= RHS and RHS == -1
2921 return RHS->isAllOnesValue();
2922 case ICmpInst::ICMP_UGE:
2923 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2924 return RHS->getZExtValue() == (1ULL <<
2925 (RHS->getType()->getPrimitiveSizeInBits()-1));
2926 case ICmpInst::ICMP_UGT:
2927 // True if LHS u> RHS and RHS == high-bit-mask - 1
2928 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002929 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002930 default:
2931 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002932 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002933}
2934
Chris Lattner113f4f42002-06-25 16:13:24 +00002935Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002936 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002937 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002938
Chris Lattner81a7a232004-10-16 18:11:37 +00002939 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2940 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2941
Chris Lattnere6794492002-08-12 21:17:25 +00002942 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002943 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2944 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002945
2946 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002947 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002948 if (SI->getOpcode() == Instruction::Shl)
2949 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002950 return BinaryOperator::createMul(SI->getOperand(0),
2951 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002952
Chris Lattnercce81be2003-09-11 22:24:54 +00002953 if (CI->isNullValue())
2954 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2955 if (CI->equalsInt(1)) // X * 1 == X
2956 return ReplaceInstUsesWith(I, Op0);
2957 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002958 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002959
Reid Spencere0fc4df2006-10-20 07:07:24 +00002960 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002961 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2962 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002963 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002964 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002965 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002966 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002967 if (Op1F->isNullValue())
2968 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002969
Chris Lattner3082c5a2003-02-18 19:28:33 +00002970 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2971 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2972 if (Op1F->getValue() == 1.0)
2973 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2974 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002975
2976 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2977 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2978 isa<ConstantInt>(Op0I->getOperand(1))) {
2979 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2980 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2981 Op1, "tmp");
2982 InsertNewInstBefore(Add, I);
2983 Value *C1C2 = ConstantExpr::getMul(Op1,
2984 cast<Constant>(Op0I->getOperand(1)));
2985 return BinaryOperator::createAdd(Add, C1C2);
2986
2987 }
Chris Lattner183b3362004-04-09 19:05:30 +00002988
2989 // Try to fold constant mul into select arguments.
2990 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002991 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002992 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002993
2994 if (isa<PHINode>(Op0))
2995 if (Instruction *NV = FoldOpIntoPhi(I))
2996 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002997 }
2998
Chris Lattner934a64cf2003-03-10 23:23:04 +00002999 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3000 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003001 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00003002
Chris Lattner2635b522004-02-23 05:39:21 +00003003 // If one of the operands of the multiply is a cast from a boolean value, then
3004 // we know the bool is either zero or one, so this is a 'masking' multiply.
3005 // See if we can simplify things based on how the boolean was originally
3006 // formed.
3007 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00003008 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00003009 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00003010 BoolCast = CI;
3011 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00003012 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00003013 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00003014 BoolCast = CI;
3015 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003016 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00003017 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3018 const Type *SCOpTy = SCIOp0->getType();
3019
Reid Spencer266e42b2006-12-23 06:05:41 +00003020 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00003021 // multiply into a shift/and combination.
3022 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00003023 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00003024 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00003025 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003026 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00003027 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00003028 InsertNewInstBefore(
3029 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00003030 BoolCast->getOperand(0)->getName()+
3031 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00003032
3033 // If the multiply type is not the same as the source type, sign extend
3034 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003035 if (I.getType() != V->getType()) {
3036 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3037 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3038 Instruction::CastOps opcode =
3039 (SrcBits == DstBits ? Instruction::BitCast :
3040 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3041 V = InsertCastBefore(opcode, V, I.getType(), I);
3042 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003043
Chris Lattner2635b522004-02-23 05:39:21 +00003044 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003045 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00003046 }
3047 }
3048 }
3049
Chris Lattner113f4f42002-06-25 16:13:24 +00003050 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00003051}
3052
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003053/// This function implements the transforms on div instructions that work
3054/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3055/// used by the visitors to those instructions.
3056/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003057Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00003059
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003060 // undef / X -> 0
3061 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003063
3064 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003065 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003066 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003067
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003068 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00003069 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3070 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003071 // same basic block, then we replace the select with Y, and the condition
3072 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00003073 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003074 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00003075 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3076 if (ST->isNullValue()) {
3077 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3078 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003079 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00003080 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3081 I.setOperand(1, SI->getOperand(2));
3082 else
3083 UpdateValueUsesWith(SI, SI->getOperand(2));
3084 return &I;
3085 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003086
Chris Lattnerd79dc792006-09-09 20:26:32 +00003087 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3088 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3089 if (ST->isNullValue()) {
3090 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3091 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003092 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00003093 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3094 I.setOperand(1, SI->getOperand(1));
3095 else
3096 UpdateValueUsesWith(SI, SI->getOperand(1));
3097 return &I;
3098 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003099 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003100
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003101 return 0;
3102}
Misha Brukmanb1c93172005-04-21 23:48:37 +00003103
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003104/// This function implements the transforms common to both integer division
3105/// instructions (udiv and sdiv). It is called by the visitors to those integer
3106/// division instructions.
3107/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003108Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3110
3111 if (Instruction *Common = commonDivTransforms(I))
3112 return Common;
3113
3114 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3115 // div X, 1 == X
3116 if (RHS->equalsInt(1))
3117 return ReplaceInstUsesWith(I, Op0);
3118
3119 // (X / C1) / C2 -> X / (C1*C2)
3120 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3121 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3122 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3123 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3124 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00003125 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003126
3127 if (!RHS->isNullValue()) { // avoid X udiv 0
3128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3130 return R;
3131 if (isa<PHINode>(Op0))
3132 if (Instruction *NV = FoldOpIntoPhi(I))
3133 return NV;
3134 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003135 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003136
Chris Lattner3082c5a2003-02-18 19:28:33 +00003137 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003138 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00003139 if (LHS->equalsInt(0))
3140 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3141
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003142 return 0;
3143}
3144
3145Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3146 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3147
3148 // Handle the integer div common cases
3149 if (Instruction *Common = commonIDivTransforms(I))
3150 return Common;
3151
3152 // X udiv C^2 -> X >> C
3153 // Check to see if this is an unsigned division with an exact power of 2,
3154 // if so, convert to a right shift.
3155 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3156 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
3157 if (isPowerOf2_64(Val)) {
3158 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00003159 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00003160 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003161 }
3162 }
3163
3164 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00003165 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003166 if (RHSI->getOpcode() == Instruction::Shl &&
3167 isa<ConstantInt>(RHSI->getOperand(0))) {
3168 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3169 if (isPowerOf2_64(C1)) {
3170 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003171 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003172 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003173 Constant *C2V = ConstantInt::get(NTy, C2);
3174 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00003175 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00003176 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00003177 }
3178 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00003179 }
3180
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003181 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3182 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00003183 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003184 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00003185 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3186 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3187 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3188 // Compute the shift amounts
3189 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3190 // Construct the "on true" case of the select
3191 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3192 Instruction *TSI = BinaryOperator::createLShr(
3193 Op0, TC, SI->getName()+".t");
3194 TSI = InsertNewInstBefore(TSI, I);
3195
3196 // Construct the "on false" case of the select
3197 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3198 Instruction *FSI = BinaryOperator::createLShr(
3199 Op0, FC, SI->getName()+".f");
3200 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003201
Reid Spencer3939b1a2007-03-05 23:36:13 +00003202 // construct the select instruction and return it.
3203 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003204 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00003205 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003206 return 0;
3207}
3208
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003209Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3210 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3211
3212 // Handle the integer div common cases
3213 if (Instruction *Common = commonIDivTransforms(I))
3214 return Common;
3215
3216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3217 // sdiv X, -1 == -X
3218 if (RHS->isAllOnesValue())
3219 return BinaryOperator::createNeg(Op0);
3220
3221 // -X/C -> X/-C
3222 if (Value *LHSNeg = dyn_castNegVal(Op0))
3223 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3224 }
3225
3226 // If the sign bits of both operands are zero (i.e. we can prove they are
3227 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00003228 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003229 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3230 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3231 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3232 }
3233 }
3234
3235 return 0;
3236}
3237
3238Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3239 return commonDivTransforms(I);
3240}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003241
Chris Lattner85dda9a2006-03-02 06:50:58 +00003242/// GetFactor - If we can prove that the specified value is at least a multiple
3243/// of some factor, return that factor.
3244static Constant *GetFactor(Value *V) {
3245 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3246 return CI;
3247
3248 // Unless we can be tricky, we know this is a multiple of 1.
3249 Constant *Result = ConstantInt::get(V->getType(), 1);
3250
3251 Instruction *I = dyn_cast<Instruction>(V);
3252 if (!I) return Result;
3253
3254 if (I->getOpcode() == Instruction::Mul) {
3255 // Handle multiplies by a constant, etc.
3256 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3257 GetFactor(I->getOperand(1)));
3258 } else if (I->getOpcode() == Instruction::Shl) {
3259 // (X<<C) -> X * (1 << C)
3260 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3261 ShRHS = ConstantExpr::getShl(Result, ShRHS);
3262 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3263 }
3264 } else if (I->getOpcode() == Instruction::And) {
3265 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3266 // X & 0xFFF0 is known to be a multiple of 16.
3267 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3268 if (Zeros != V->getType()->getPrimitiveSizeInBits())
3269 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00003270 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00003271 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003272 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00003273 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003274 if (!CI->isIntegerCast())
3275 return Result;
3276 Value *Op = CI->getOperand(0);
3277 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00003278 }
3279 return Result;
3280}
3281
Reid Spencer7eb55b32006-11-02 01:53:59 +00003282/// This function implements the transforms on rem instructions that work
3283/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3284/// is used by the visitors to those instructions.
3285/// @brief Transforms common to all three rem instructions
3286Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003287 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003288
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003289 // 0 % X == 0, we don't need to preserve faults!
3290 if (Constant *LHS = dyn_cast<Constant>(Op0))
3291 if (LHS->isNullValue())
3292 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3293
3294 if (isa<UndefValue>(Op0)) // undef % X -> 0
3295 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3296 if (isa<UndefValue>(Op1))
3297 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00003298
3299 // Handle cases involving: rem X, (select Cond, Y, Z)
3300 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3301 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3302 // the same basic block, then we replace the select with Y, and the
3303 // condition of the select with false (if the cond value is in the same
3304 // BB). If the select has uses other than the div, this allows them to be
3305 // simplified also.
3306 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3307 if (ST->isNullValue()) {
3308 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3309 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003310 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003311 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3312 I.setOperand(1, SI->getOperand(2));
3313 else
3314 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00003315 return &I;
3316 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003317 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3318 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3319 if (ST->isNullValue()) {
3320 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3321 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003322 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003323 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3324 I.setOperand(1, SI->getOperand(1));
3325 else
3326 UpdateValueUsesWith(SI, SI->getOperand(1));
3327 return &I;
3328 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00003329 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00003330
Reid Spencer7eb55b32006-11-02 01:53:59 +00003331 return 0;
3332}
3333
3334/// This function implements the transforms common to both integer remainder
3335/// instructions (urem and srem). It is called by the visitors to those integer
3336/// remainder instructions.
3337/// @brief Common integer remainder transforms
3338Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3339 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3340
3341 if (Instruction *common = commonRemTransforms(I))
3342 return common;
3343
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003344 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003345 // X % 0 == undef, we don't need to preserve faults!
3346 if (RHS->equalsInt(0))
3347 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3348
Chris Lattner3082c5a2003-02-18 19:28:33 +00003349 if (RHS->equalsInt(1)) // X % 1 == 0
3350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3351
Chris Lattnerb70f1412006-02-28 05:49:21 +00003352 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3353 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3354 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3355 return R;
3356 } else if (isa<PHINode>(Op0I)) {
3357 if (Instruction *NV = FoldOpIntoPhi(I))
3358 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003359 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003360 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
3361 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00003362 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00003363 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003364 }
3365
Reid Spencer7eb55b32006-11-02 01:53:59 +00003366 return 0;
3367}
3368
3369Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3370 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3371
3372 if (Instruction *common = commonIRemTransforms(I))
3373 return common;
3374
3375 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3376 // X urem C^2 -> X and C
3377 // Check to see if this is an unsigned remainder with an exact power of 2,
3378 // if so, convert to a bitwise and.
3379 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3380 if (isPowerOf2_64(C->getZExtValue()))
3381 return BinaryOperator::createAnd(Op0, SubOne(C));
3382 }
3383
Chris Lattner2e90b732006-02-05 07:54:04 +00003384 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003385 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3386 if (RHSI->getOpcode() == Instruction::Shl &&
3387 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003388 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00003389 if (isPowerOf2_64(C1)) {
3390 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3391 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3392 "tmp"), I);
3393 return BinaryOperator::createAnd(Op0, Add);
3394 }
3395 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003396 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003397
Reid Spencer7eb55b32006-11-02 01:53:59 +00003398 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3399 // where C1&C2 are powers of two.
3400 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3401 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3402 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3403 // STO == 0 and SFO == 0 handled above.
3404 if (isPowerOf2_64(STO->getZExtValue()) &&
3405 isPowerOf2_64(SFO->getZExtValue())) {
3406 Value *TrueAnd = InsertNewInstBefore(
3407 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3408 Value *FalseAnd = InsertNewInstBefore(
3409 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3410 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3411 }
3412 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003413 }
3414
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003415 return 0;
3416}
3417
Reid Spencer7eb55b32006-11-02 01:53:59 +00003418Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3420
3421 if (Instruction *common = commonIRemTransforms(I))
3422 return common;
3423
3424 if (Value *RHSNeg = dyn_castNegVal(Op1))
3425 if (!isa<ConstantInt>(RHSNeg) ||
3426 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3427 // X % -Y -> X % Y
3428 AddUsesToWorkList(I);
3429 I.setOperand(1, RHSNeg);
3430 return &I;
3431 }
3432
3433 // If the top bits of both operands are zero (i.e. we can prove they are
3434 // unsigned inputs), turn this into a urem.
3435 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3436 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3437 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3438 return BinaryOperator::createURem(Op0, Op1, I.getName());
3439 }
3440
3441 return 0;
3442}
3443
3444Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003445 return commonRemTransforms(I);
3446}
3447
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003448// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00003449static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3450 if (isSigned) {
3451 // Calculate 0111111111..11111
3452 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3453 int64_t Val = INT64_MAX; // All ones
3454 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
3455 return C->getSExtValue() == Val-1;
3456 }
Reid Spencera94d3942007-01-19 21:13:56 +00003457 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003458}
3459
3460// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00003461static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3462 if (isSigned) {
3463 // Calculate 1111111111000000000000
3464 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3465 int64_t Val = -1; // All ones
3466 Val <<= TypeBits-1; // Shift over to the right spot
3467 return C->getSExtValue() == Val+1;
3468 }
3469 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003470}
3471
Chris Lattner35167c32004-06-09 07:59:58 +00003472// isOneBitSet - Return true if there is exactly one bit set in the specified
3473// constant.
3474static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003475 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00003476 return V && (V & (V-1)) == 0;
3477}
3478
Chris Lattner8fc5af42004-09-23 21:46:38 +00003479#if 0 // Currently unused
3480// isLowOnes - Return true if the constant is of the form 0+1+.
3481static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003482 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003483
3484 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003485 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003486
3487 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3488 return U && V && (U & V) == 0;
3489}
3490#endif
3491
3492// isHighOnes - Return true if the constant is of the form 1+0+.
3493// This is the same as lowones(~X).
3494static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003495 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00003496 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00003497
3498 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003499 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003500
3501 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3502 return U && V && (U & V) == 0;
3503}
3504
Reid Spencer266e42b2006-12-23 06:05:41 +00003505/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003506/// are carefully arranged to allow folding of expressions such as:
3507///
3508/// (A < B) | (A > B) --> (A != B)
3509///
Reid Spencer266e42b2006-12-23 06:05:41 +00003510/// Note that this is only valid if the first and second predicates have the
3511/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003512///
Reid Spencer266e42b2006-12-23 06:05:41 +00003513/// Three bits are used to represent the condition, as follows:
3514/// 0 A > B
3515/// 1 A == B
3516/// 2 A < B
3517///
3518/// <=> Value Definition
3519/// 000 0 Always false
3520/// 001 1 A > B
3521/// 010 2 A == B
3522/// 011 3 A >= B
3523/// 100 4 A < B
3524/// 101 5 A != B
3525/// 110 6 A <= B
3526/// 111 7 Always true
3527///
3528static unsigned getICmpCode(const ICmpInst *ICI) {
3529 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003530 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003531 case ICmpInst::ICMP_UGT: return 1; // 001
3532 case ICmpInst::ICMP_SGT: return 1; // 001
3533 case ICmpInst::ICMP_EQ: return 2; // 010
3534 case ICmpInst::ICMP_UGE: return 3; // 011
3535 case ICmpInst::ICMP_SGE: return 3; // 011
3536 case ICmpInst::ICMP_ULT: return 4; // 100
3537 case ICmpInst::ICMP_SLT: return 4; // 100
3538 case ICmpInst::ICMP_NE: return 5; // 101
3539 case ICmpInst::ICMP_ULE: return 6; // 110
3540 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003541 // True -> 7
3542 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00003543 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003544 return 0;
3545 }
3546}
3547
Reid Spencer266e42b2006-12-23 06:05:41 +00003548/// getICmpValue - This is the complement of getICmpCode, which turns an
3549/// opcode and two operands into either a constant true or false, or a brand
3550/// new /// ICmp instruction. The sign is passed in to determine which kind
3551/// of predicate to use in new icmp instructions.
3552static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3553 switch (code) {
3554 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00003555 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003556 case 1:
3557 if (sign)
3558 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3559 else
3560 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3561 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3562 case 3:
3563 if (sign)
3564 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3565 else
3566 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3567 case 4:
3568 if (sign)
3569 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3570 else
3571 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3572 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3573 case 6:
3574 if (sign)
3575 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3576 else
3577 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003578 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003579 }
3580}
3581
Reid Spencer266e42b2006-12-23 06:05:41 +00003582static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3583 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3584 (ICmpInst::isSignedPredicate(p1) &&
3585 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3586 (ICmpInst::isSignedPredicate(p2) &&
3587 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3588}
3589
3590namespace {
3591// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3592struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003593 InstCombiner &IC;
3594 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003595 ICmpInst::Predicate pred;
3596 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3597 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3598 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003599 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003600 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3601 if (PredicatesFoldable(pred, ICI->getPredicate()))
3602 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3603 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003604 return false;
3605 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003606 Instruction *apply(Instruction &Log) const {
3607 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3608 if (ICI->getOperand(0) != LHS) {
3609 assert(ICI->getOperand(1) == LHS);
3610 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003611 }
3612
Chris Lattnerd1bce952007-03-13 14:27:42 +00003613 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003614 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00003615 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003616 unsigned Code;
3617 switch (Log.getOpcode()) {
3618 case Instruction::And: Code = LHSCode & RHSCode; break;
3619 case Instruction::Or: Code = LHSCode | RHSCode; break;
3620 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003621 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003622 }
3623
Chris Lattnerd1bce952007-03-13 14:27:42 +00003624 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3625 ICmpInst::isSignedPredicate(ICI->getPredicate());
3626
3627 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003628 if (Instruction *I = dyn_cast<Instruction>(RV))
3629 return I;
3630 // Otherwise, it's a constant boolean value...
3631 return IC.ReplaceInstUsesWith(Log, RV);
3632 }
3633};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003634} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003635
Chris Lattnerba1cb382003-09-19 17:17:26 +00003636// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3637// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003638// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003639Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003640 ConstantInt *OpRHS,
3641 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003642 BinaryOperator &TheAnd) {
3643 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003644 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003645 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003646 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003647
Chris Lattnerba1cb382003-09-19 17:17:26 +00003648 switch (Op->getOpcode()) {
3649 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003650 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003651 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00003652 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003653 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003654 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003655 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003656 }
3657 break;
3658 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003659 if (Together == AndRHS) // (X | C) & C --> C
3660 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003661
Chris Lattner86102b82005-01-01 16:22:27 +00003662 if (Op->hasOneUse() && Together != OpRHS) {
3663 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00003664 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003665 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003666 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00003667 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003668 }
3669 break;
3670 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003671 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003672 // Adding a one to a single bit bit-field should be turned into an XOR
3673 // of the bit. First thing to check is to see if this AND is with a
3674 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003675 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003676
3677 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00003678 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003679
3680 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003681 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003682 // Ok, at this point, we know that we are masking the result of the
3683 // ADD down to exactly one bit. If the constant we are adding has
3684 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003685 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003686
Chris Lattnerba1cb382003-09-19 17:17:26 +00003687 // Check to see if any bits below the one bit set in AndRHSV are set.
3688 if ((AddRHS & (AndRHSV-1)) == 0) {
3689 // If not, the only thing that can effect the output of the AND is
3690 // the bit specified by AndRHSV. If that bit is set, the effect of
3691 // the XOR is to toggle the bit. If it is clear, then the ADD has
3692 // no effect.
3693 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3694 TheAnd.setOperand(0, X);
3695 return &TheAnd;
3696 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003697 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003698 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003699 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003700 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003701 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003702 }
3703 }
3704 }
3705 }
3706 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003707
3708 case Instruction::Shl: {
3709 // We know that the AND will not produce any of the bits shifted in, so if
3710 // the anded constant includes them, clear them now!
3711 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003712 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00003713 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3714 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003715
Chris Lattner7e794272004-09-24 15:21:34 +00003716 if (CI == ShlMask) { // Masking out bits that the shift already masks
3717 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3718 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003719 TheAnd.setOperand(1, CI);
3720 return &TheAnd;
3721 }
3722 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003723 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003724 case Instruction::LShr:
3725 {
Chris Lattner2da29172003-09-19 19:05:02 +00003726 // We know that the AND will not produce any of the bits shifted in, so if
3727 // the anded constant includes them, clear them now! This only applies to
3728 // unsigned shifts, because a signed shr may bring in set bits!
3729 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003730 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003731 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3732 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003733
Reid Spencerfdff9382006-11-08 06:47:33 +00003734 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3735 return ReplaceInstUsesWith(TheAnd, Op);
3736 } else if (CI != AndRHS) {
3737 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3738 return &TheAnd;
3739 }
3740 break;
3741 }
3742 case Instruction::AShr:
3743 // Signed shr.
3744 // See if this is shifting in some sign extension, then masking it out
3745 // with an and.
3746 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003747 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003748 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003749 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3750 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003751 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003752 // Make the argument unsigned.
3753 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003754 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003755 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003756 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003757 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003758 }
Chris Lattner2da29172003-09-19 19:05:02 +00003759 }
3760 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003761 }
3762 return 0;
3763}
3764
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003765
Chris Lattner6862fbd2004-09-29 17:40:11 +00003766/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3767/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003768/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3769/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003770/// insert new instructions.
3771Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003772 bool isSigned, bool Inside,
3773 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003774 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003775 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003776 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003777
Chris Lattner6862fbd2004-09-29 17:40:11 +00003778 if (Inside) {
3779 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003780 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003781
Reid Spencer266e42b2006-12-23 06:05:41 +00003782 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003783 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003784 ICmpInst::Predicate pred = (isSigned ?
3785 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3786 return new ICmpInst(pred, V, Hi);
3787 }
3788
3789 // Emit V-Lo <u Hi-Lo
3790 Constant *NegLo = ConstantExpr::getNeg(Lo);
3791 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003792 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003793 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3794 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003795 }
3796
3797 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003798 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003799
Reid Spencer266e42b2006-12-23 06:05:41 +00003800 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003801 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003802 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003803 ICmpInst::Predicate pred = (isSigned ?
3804 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3805 return new ICmpInst(pred, V, Hi);
3806 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003807
Reid Spencer266e42b2006-12-23 06:05:41 +00003808 // Emit V-Lo > Hi-1-Lo
3809 Constant *NegLo = ConstantExpr::getNeg(Lo);
3810 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003811 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003812 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3813 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003814}
3815
Chris Lattnerb4b25302005-09-18 07:22:02 +00003816// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3817// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3818// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3819// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003820static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003821 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003822 if (!isShiftedMask_64(V)) return false;
3823
3824 // look for the first zero bit after the run of ones
3825 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3826 // look for the first non-zero bit
3827 ME = 64-CountLeadingZeros_64(V);
3828 return true;
3829}
3830
3831
3832
3833/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3834/// where isSub determines whether the operator is a sub. If we can fold one of
3835/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003836///
3837/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3838/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3839/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3840///
3841/// return (A +/- B).
3842///
3843Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003844 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003845 Instruction &I) {
3846 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3847 if (!LHSI || LHSI->getNumOperands() != 2 ||
3848 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3849
3850 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3851
3852 switch (LHSI->getOpcode()) {
3853 default: return 0;
3854 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003855 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3856 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003857 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003858 break;
3859
3860 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3861 // part, we don't need any explicit masks to take them out of A. If that
3862 // is all N is, ignore it.
3863 unsigned MB, ME;
3864 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003865 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003866 Mask >>= 64-MB+1;
3867 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003868 break;
3869 }
3870 }
Chris Lattneraf517572005-09-18 04:24:45 +00003871 return 0;
3872 case Instruction::Or:
3873 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003874 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003875 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003876 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003877 break;
3878 return 0;
3879 }
3880
3881 Instruction *New;
3882 if (isSub)
3883 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3884 else
3885 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3886 return InsertNewInstBefore(New, I);
3887}
3888
Chris Lattner113f4f42002-06-25 16:13:24 +00003889Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003890 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003892
Chris Lattner81a7a232004-10-16 18:11:37 +00003893 if (isa<UndefValue>(Op1)) // X & undef -> 0
3894 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3895
Chris Lattner86102b82005-01-01 16:22:27 +00003896 // and X, X = X
3897 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003898 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003899
Chris Lattner5b2edb12006-02-12 08:02:11 +00003900 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003901 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003902 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003903 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003904 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003905 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003906 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003907 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003908 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003909 if (CP->isAllOnesValue())
3910 return ReplaceInstUsesWith(I, I.getOperand(0));
3911 }
3912 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003913
Zhou Sheng75b871f2007-01-11 12:24:14 +00003914 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003915 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003916 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003917 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003918
Chris Lattnerba1cb382003-09-19 17:17:26 +00003919 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003920 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003921 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003922 Value *Op0LHS = Op0I->getOperand(0);
3923 Value *Op0RHS = Op0I->getOperand(1);
3924 switch (Op0I->getOpcode()) {
3925 case Instruction::Xor:
3926 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003927 // If the mask is only needed on one incoming arm, push it up.
3928 if (Op0I->hasOneUse()) {
3929 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3930 // Not masking anything out for the LHS, move to RHS.
3931 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3932 Op0RHS->getName()+".masked");
3933 InsertNewInstBefore(NewRHS, I);
3934 return BinaryOperator::create(
3935 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003936 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003937 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003938 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3939 // Not masking anything out for the RHS, move to LHS.
3940 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3941 Op0LHS->getName()+".masked");
3942 InsertNewInstBefore(NewLHS, I);
3943 return BinaryOperator::create(
3944 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3945 }
3946 }
3947
Chris Lattner86102b82005-01-01 16:22:27 +00003948 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003949 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003950 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3951 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3952 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3953 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3954 return BinaryOperator::createAnd(V, AndRHS);
3955 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3956 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003957 break;
3958
3959 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003960 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3961 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3962 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3963 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3964 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003965 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003966 }
3967
Chris Lattner16464b32003-07-23 19:25:52 +00003968 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003969 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003970 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003971 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003972 // If this is an integer truncation or change from signed-to-unsigned, and
3973 // if the source is an and/or with immediate, transform it. This
3974 // frequently occurs for bitfield accesses.
3975 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003976 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003977 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003978 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003979 if (CastOp->getOpcode() == Instruction::And) {
3980 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003981 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3982 // This will fold the two constants together, which may allow
3983 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003984 Instruction *NewCast = CastInst::createTruncOrBitCast(
3985 CastOp->getOperand(0), I.getType(),
3986 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003987 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003988 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003989 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003990 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003991 return BinaryOperator::createAnd(NewCast, C3);
3992 } else if (CastOp->getOpcode() == Instruction::Or) {
3993 // Change: and (cast (or X, C1) to T), C2
3994 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003995 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003996 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3997 return ReplaceInstUsesWith(I, AndRHS);
3998 }
3999 }
Chris Lattner33217db2003-07-23 19:36:21 +00004000 }
Chris Lattner183b3362004-04-09 19:05:30 +00004001
4002 // Try to fold constant and into select arguments.
4003 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004004 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004005 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004006 if (isa<PHINode>(Op0))
4007 if (Instruction *NV = FoldOpIntoPhi(I))
4008 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00004009 }
4010
Chris Lattnerbb74e222003-03-10 23:06:50 +00004011 Value *Op0NotVal = dyn_castNotVal(Op0);
4012 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004013
Chris Lattner023a4832004-06-18 06:07:51 +00004014 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4016
Misha Brukman9c003d82004-07-30 12:50:08 +00004017 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00004018 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004019 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4020 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00004021 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004022 return BinaryOperator::createNot(Or);
4023 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004024
4025 {
4026 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00004027 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4028 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4029 return ReplaceInstUsesWith(I, Op1);
4030 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4031 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4032 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004033
4034 if (Op0->hasOneUse() &&
4035 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4036 if (A == Op1) { // (A^B)&A -> A&(A^B)
4037 I.swapOperands(); // Simplify below
4038 std::swap(Op0, Op1);
4039 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4040 cast<BinaryOperator>(Op0)->swapOperands();
4041 I.swapOperands(); // Simplify below
4042 std::swap(Op0, Op1);
4043 }
4044 }
4045 if (Op1->hasOneUse() &&
4046 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4047 if (B == Op0) { // B&(A^B) -> B&(B^A)
4048 cast<BinaryOperator>(Op1)->swapOperands();
4049 std::swap(A, B);
4050 }
4051 if (A == Op0) { // A&(A^B) -> A & ~B
4052 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4053 InsertNewInstBefore(NotB, I);
4054 return BinaryOperator::createAnd(A, NotB);
4055 }
4056 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004057 }
4058
Reid Spencer266e42b2006-12-23 06:05:41 +00004059 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4060 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4061 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004062 return R;
4063
Chris Lattner623826c2004-09-28 21:48:02 +00004064 Value *LHSVal, *RHSVal;
4065 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004066 ICmpInst::Predicate LHSCC, RHSCC;
4067 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4068 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4069 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4070 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4071 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4072 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4073 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4074 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00004075 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004076 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4077 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4078 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4079 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00004080 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00004081 std::swap(LHS, RHS);
4082 std::swap(LHSCst, RHSCst);
4083 std::swap(LHSCC, RHSCC);
4084 }
4085
Reid Spencer266e42b2006-12-23 06:05:41 +00004086 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00004087 // comparing a value against two constants and and'ing the result
4088 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004089 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4090 // (from the FoldICmpLogical check above), that the two constants
4091 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00004092 assert(LHSCst != RHSCst && "Compares not folded above?");
4093
4094 switch (LHSCC) {
4095 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004096 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00004097 switch (RHSCC) {
4098 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004099 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4100 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4101 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004102 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004103 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4104 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4105 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00004106 return ReplaceInstUsesWith(I, LHS);
4107 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004108 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00004109 switch (RHSCC) {
4110 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004111 case ICmpInst::ICMP_ULT:
4112 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4113 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4114 break; // (X != 13 & X u< 15) -> no change
4115 case ICmpInst::ICMP_SLT:
4116 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4117 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4118 break; // (X != 13 & X s< 15) -> no change
4119 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4120 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4121 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00004122 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004123 case ICmpInst::ICMP_NE:
4124 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00004125 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4126 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4127 LHSVal->getName()+".off");
4128 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00004129 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4130 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00004131 }
4132 break; // (X != 13 & X != 15) -> no change
4133 }
4134 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004135 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00004136 switch (RHSCC) {
4137 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004138 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4139 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004140 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004141 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4142 break;
4143 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4144 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00004145 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004146 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4147 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004148 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004149 break;
4150 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00004151 switch (RHSCC) {
4152 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004153 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4154 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004155 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004156 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4157 break;
4158 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4159 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00004160 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004161 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4162 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004163 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004164 break;
4165 case ICmpInst::ICMP_UGT:
4166 switch (RHSCC) {
4167 default: assert(0 && "Unknown integer condition code!");
4168 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4169 return ReplaceInstUsesWith(I, LHS);
4170 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4171 return ReplaceInstUsesWith(I, RHS);
4172 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4173 break;
4174 case ICmpInst::ICMP_NE:
4175 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4176 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4177 break; // (X u> 13 & X != 15) -> no change
4178 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4179 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4180 true, I);
4181 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4182 break;
4183 }
4184 break;
4185 case ICmpInst::ICMP_SGT:
4186 switch (RHSCC) {
4187 default: assert(0 && "Unknown integer condition code!");
4188 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
4189 return ReplaceInstUsesWith(I, LHS);
4190 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4191 return ReplaceInstUsesWith(I, RHS);
4192 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4193 break;
4194 case ICmpInst::ICMP_NE:
4195 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4196 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4197 break; // (X s> 13 & X != 15) -> no change
4198 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4199 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4200 true, I);
4201 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4202 break;
4203 }
4204 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004205 }
4206 }
4207 }
4208
Chris Lattner3af10532006-05-05 06:39:07 +00004209 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004210 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4211 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4212 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4213 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004214 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004215 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004216 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4217 I.getType(), TD) &&
4218 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4219 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004220 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4221 Op1C->getOperand(0),
4222 I.getName());
4223 InsertNewInstBefore(NewOp, I);
4224 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4225 }
Chris Lattner3af10532006-05-05 06:39:07 +00004226 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004227
4228 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004229 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4230 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4231 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004232 SI0->getOperand(1) == SI1->getOperand(1) &&
4233 (SI0->hasOneUse() || SI1->hasOneUse())) {
4234 Instruction *NewOp =
4235 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4236 SI1->getOperand(0),
4237 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004238 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4239 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004240 }
Chris Lattner3af10532006-05-05 06:39:07 +00004241 }
4242
Chris Lattner113f4f42002-06-25 16:13:24 +00004243 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004244}
4245
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004246/// CollectBSwapParts - Look to see if the specified value defines a single byte
4247/// in the result. If it does, and if the specified byte hasn't been filled in
4248/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004249static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004250 Instruction *I = dyn_cast<Instruction>(V);
4251 if (I == 0) return true;
4252
4253 // If this is an or instruction, it is an inner node of the bswap.
4254 if (I->getOpcode() == Instruction::Or)
4255 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4256 CollectBSwapParts(I->getOperand(1), ByteValues);
4257
4258 // If this is a shift by a constant int, and it is "24", then its operand
4259 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00004260 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004261 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00004262 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004263 8*(ByteValues.size()-1))
4264 return true;
4265
4266 unsigned DestNo;
4267 if (I->getOpcode() == Instruction::Shl) {
4268 // X << 24 defines the top byte with the lowest of the input bytes.
4269 DestNo = ByteValues.size()-1;
4270 } else {
4271 // X >>u 24 defines the low byte with the highest of the input bytes.
4272 DestNo = 0;
4273 }
4274
4275 // If the destination byte value is already defined, the values are or'd
4276 // together, which isn't a bswap (unless it's an or of the same bits).
4277 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4278 return true;
4279 ByteValues[DestNo] = I->getOperand(0);
4280 return false;
4281 }
4282
4283 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4284 // don't have this.
4285 Value *Shift = 0, *ShiftLHS = 0;
4286 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4287 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4288 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4289 return true;
4290 Instruction *SI = cast<Instruction>(Shift);
4291
4292 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004293 if (ShiftAmt->getZExtValue() & 7 ||
4294 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004295 return true;
4296
4297 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4298 unsigned DestByte;
4299 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004300 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004301 break;
4302 // Unknown mask for bswap.
4303 if (DestByte == ByteValues.size()) return true;
4304
Reid Spencere0fc4df2006-10-20 07:07:24 +00004305 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004306 unsigned SrcByte;
4307 if (SI->getOpcode() == Instruction::Shl)
4308 SrcByte = DestByte - ShiftBytes;
4309 else
4310 SrcByte = DestByte + ShiftBytes;
4311
4312 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4313 if (SrcByte != ByteValues.size()-DestByte-1)
4314 return true;
4315
4316 // If the destination byte value is already defined, the values are or'd
4317 // together, which isn't a bswap (unless it's an or of the same bits).
4318 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4319 return true;
4320 ByteValues[DestByte] = SI->getOperand(0);
4321 return false;
4322}
4323
4324/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4325/// If so, insert the new bswap intrinsic and return it.
4326Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00004327 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00004328 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004329 return 0;
4330
4331 /// ByteValues - For each byte of the result, we keep track of which value
4332 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004333 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00004334 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004335
4336 // Try to find all the pieces corresponding to the bswap.
4337 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4338 CollectBSwapParts(I.getOperand(1), ByteValues))
4339 return 0;
4340
4341 // Check to see if all of the bytes come from the same value.
4342 Value *V = ByteValues[0];
4343 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4344
4345 // Check to make sure that all of the bytes come from the same value.
4346 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4347 if (ByteValues[i] != V)
4348 return 0;
4349
4350 // If they do then *success* we can turn this into a bswap. Figure out what
4351 // bswap to make it into.
4352 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00004353 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00004354 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004355 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00004356 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004357 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00004358 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004359 FnName = "llvm.bswap.i64";
4360 else
4361 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00004362 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004363 return new CallInst(F, V);
4364}
4365
4366
Chris Lattner113f4f42002-06-25 16:13:24 +00004367Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004368 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004369 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004370
Chris Lattner81a7a232004-10-16 18:11:37 +00004371 if (isa<UndefValue>(Op1))
4372 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004373 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004374
Chris Lattner5b2edb12006-02-12 08:02:11 +00004375 // or X, X = X
4376 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004377 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004378
Chris Lattner5b2edb12006-02-12 08:02:11 +00004379 // See if we can simplify any instructions used by the instruction whose sole
4380 // purpose is to compute bits we don't care about.
4381 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004382 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00004383 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004384 KnownZero, KnownOne))
4385 return &I;
4386
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004387 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004388 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004389 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004390 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4391 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004392 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004393 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004394 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004395 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4396 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004397
Chris Lattnerd4252a72004-07-30 07:50:03 +00004398 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4399 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004400 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004401 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004402 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004403 return BinaryOperator::createXor(Or,
4404 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004405 }
Chris Lattner183b3362004-04-09 19:05:30 +00004406
4407 // Try to fold constant and into select arguments.
4408 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004409 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004410 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004411 if (isa<PHINode>(Op0))
4412 if (Instruction *NV = FoldOpIntoPhi(I))
4413 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004414 }
4415
Chris Lattner330628a2006-01-06 17:59:59 +00004416 Value *A = 0, *B = 0;
4417 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004418
4419 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4420 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4421 return ReplaceInstUsesWith(I, Op1);
4422 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4423 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4424 return ReplaceInstUsesWith(I, Op0);
4425
Chris Lattnerb7845d62006-07-10 20:25:24 +00004426 // (A | B) | C and A | (B | C) -> bswap if possible.
4427 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004428 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00004429 match(Op1, m_Or(m_Value(), m_Value())) ||
4430 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4431 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004432 if (Instruction *BSwap = MatchBSwap(I))
4433 return BSwap;
4434 }
4435
Chris Lattnerb62f5082005-05-09 04:58:36 +00004436 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4437 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004438 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004439 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4440 InsertNewInstBefore(NOr, I);
4441 NOr->takeName(Op0);
4442 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004443 }
4444
4445 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4446 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004447 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004448 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4449 InsertNewInstBefore(NOr, I);
4450 NOr->takeName(Op0);
4451 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004452 }
4453
Chris Lattner15212982005-09-18 03:42:07 +00004454 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00004455 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00004456 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4457
4458 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
4459 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4460
4461
Chris Lattner01f56c62005-09-18 06:02:59 +00004462 // If we have: ((V + N) & C1) | (V & C2)
4463 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4464 // replace with V+N.
4465 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004466 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00004467 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00004468 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4469 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004470 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004471 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004472 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004473 return ReplaceInstUsesWith(I, A);
4474 }
4475 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004476 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00004477 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4478 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004479 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004480 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004481 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004482 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00004483 }
4484 }
4485 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004486
4487 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004488 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4489 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4490 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004491 SI0->getOperand(1) == SI1->getOperand(1) &&
4492 (SI0->hasOneUse() || SI1->hasOneUse())) {
4493 Instruction *NewOp =
4494 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4495 SI1->getOperand(0),
4496 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004497 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4498 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004499 }
4500 }
Chris Lattner812aab72003-08-12 19:11:07 +00004501
Chris Lattnerd4252a72004-07-30 07:50:03 +00004502 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4503 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00004504 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004505 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004506 } else {
4507 A = 0;
4508 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004509 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00004510 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4511 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00004512 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004513 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004514
Misha Brukman9c003d82004-07-30 12:50:08 +00004515 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004516 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4517 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4518 I.getName()+".demorgan"), I);
4519 return BinaryOperator::createNot(And);
4520 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004521 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004522
Reid Spencer266e42b2006-12-23 06:05:41 +00004523 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4524 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4525 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004526 return R;
4527
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004528 Value *LHSVal, *RHSVal;
4529 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 ICmpInst::Predicate LHSCC, RHSCC;
4531 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4532 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4533 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4534 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4535 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4536 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4537 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4538 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004539 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4541 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4542 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4543 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00004544 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004545 std::swap(LHS, RHS);
4546 std::swap(LHSCst, RHSCst);
4547 std::swap(LHSCC, RHSCC);
4548 }
4549
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004551 // comparing a value against two constants and or'ing the result
4552 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004553 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4554 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004555 // equal.
4556 assert(LHSCst != RHSCst && "Compares not folded above?");
4557
4558 switch (LHSCC) {
4559 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004560 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004561 switch (RHSCC) {
4562 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004563 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004564 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4565 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4566 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4567 LHSVal->getName()+".off");
4568 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004569 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00004570 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004571 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004572 break; // (X == 13 | X == 15) -> no change
4573 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4574 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00004575 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004576 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4578 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004579 return ReplaceInstUsesWith(I, RHS);
4580 }
4581 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004582 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004583 switch (RHSCC) {
4584 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004585 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4586 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4587 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004588 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004589 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4590 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4591 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004592 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004593 }
4594 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004595 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004596 switch (RHSCC) {
4597 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004598 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004599 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004600 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4601 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4602 false, I);
4603 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4604 break;
4605 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4606 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004607 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004608 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4609 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004610 }
4611 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004612 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004613 switch (RHSCC) {
4614 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004615 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4616 break;
4617 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4618 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4619 false, I);
4620 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4621 break;
4622 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4623 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4624 return ReplaceInstUsesWith(I, RHS);
4625 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4626 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004627 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004628 break;
4629 case ICmpInst::ICMP_UGT:
4630 switch (RHSCC) {
4631 default: assert(0 && "Unknown integer condition code!");
4632 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4633 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4634 return ReplaceInstUsesWith(I, LHS);
4635 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4636 break;
4637 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4638 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004639 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004640 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4641 break;
4642 }
4643 break;
4644 case ICmpInst::ICMP_SGT:
4645 switch (RHSCC) {
4646 default: assert(0 && "Unknown integer condition code!");
4647 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4648 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4649 return ReplaceInstUsesWith(I, LHS);
4650 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4651 break;
4652 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4653 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004654 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004655 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4656 break;
4657 }
4658 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004659 }
4660 }
4661 }
Chris Lattner3af10532006-05-05 06:39:07 +00004662
4663 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004664 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004665 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004666 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4667 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004668 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004669 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004670 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4671 I.getType(), TD) &&
4672 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4673 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004674 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4675 Op1C->getOperand(0),
4676 I.getName());
4677 InsertNewInstBefore(NewOp, I);
4678 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4679 }
Chris Lattner3af10532006-05-05 06:39:07 +00004680 }
Chris Lattner3af10532006-05-05 06:39:07 +00004681
Chris Lattner15212982005-09-18 03:42:07 +00004682
Chris Lattner113f4f42002-06-25 16:13:24 +00004683 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004684}
4685
Chris Lattnerc2076352004-02-16 01:20:27 +00004686// XorSelf - Implements: X ^ X --> 0
4687struct XorSelf {
4688 Value *RHS;
4689 XorSelf(Value *rhs) : RHS(rhs) {}
4690 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4691 Instruction *apply(BinaryOperator &Xor) const {
4692 return &Xor;
4693 }
4694};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004695
4696
Chris Lattner113f4f42002-06-25 16:13:24 +00004697Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004698 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004699 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004700
Chris Lattner81a7a232004-10-16 18:11:37 +00004701 if (isa<UndefValue>(Op1))
4702 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4703
Chris Lattnerc2076352004-02-16 01:20:27 +00004704 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4705 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4706 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004707 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004708 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004709
4710 // See if we can simplify any instructions used by the instruction whose sole
4711 // purpose is to compute bits we don't care about.
4712 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004713 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00004714 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004715 KnownZero, KnownOne))
4716 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004717
Zhou Sheng75b871f2007-01-11 12:24:14 +00004718 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004719 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4720 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004721 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004722 return new ICmpInst(ICI->getInversePredicate(),
4723 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004724
Reid Spencer266e42b2006-12-23 06:05:41 +00004725 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004726 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004727 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4728 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004729 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4730 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004731 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004732 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004733 }
Chris Lattner023a4832004-06-18 06:07:51 +00004734
4735 // ~(~X & Y) --> (X | ~Y)
4736 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4737 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4738 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4739 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004740 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004741 Op0I->getOperand(1)->getName()+".not");
4742 InsertNewInstBefore(NotY, I);
4743 return BinaryOperator::createOr(Op0NotVal, NotY);
4744 }
4745 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004746
Chris Lattner97638592003-07-23 21:37:07 +00004747 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004748 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004749 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004750 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004751 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4752 return BinaryOperator::createSub(
4753 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004754 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004755 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004756 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004757 } else if (Op0I->getOpcode() == Instruction::Or) {
4758 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4759 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4760 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4761 // Anything in both C1 and C2 is known to be zero, remove it from
4762 // NewRHS.
4763 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4764 NewRHS = ConstantExpr::getAnd(NewRHS,
4765 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004766 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004767 I.setOperand(0, Op0I->getOperand(0));
4768 I.setOperand(1, NewRHS);
4769 return &I;
4770 }
Chris Lattner97638592003-07-23 21:37:07 +00004771 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004772 }
Chris Lattner183b3362004-04-09 19:05:30 +00004773
4774 // Try to fold constant and into select arguments.
4775 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004776 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004777 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004778 if (isa<PHINode>(Op0))
4779 if (Instruction *NV = FoldOpIntoPhi(I))
4780 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004781 }
4782
Chris Lattnerbb74e222003-03-10 23:06:50 +00004783 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004784 if (X == Op1)
4785 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004786 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004787
Chris Lattnerbb74e222003-03-10 23:06:50 +00004788 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004789 if (X == Op0)
4790 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004791 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004792
Chris Lattnerdcd07922006-04-01 08:03:55 +00004793 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00004794 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004795 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004796 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004797 I.swapOperands();
4798 std::swap(Op0, Op1);
4799 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004800 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004801 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004802 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004803 } else if (Op1I->getOpcode() == Instruction::Xor) {
4804 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4805 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4806 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4807 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004808 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4809 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4810 Op1I->swapOperands();
4811 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4812 I.swapOperands(); // Simplified below.
4813 std::swap(Op0, Op1);
4814 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004815 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004816
Chris Lattnerdcd07922006-04-01 08:03:55 +00004817 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004818 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004819 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004820 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004821 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004822 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4823 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004824 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004825 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004826 } else if (Op0I->getOpcode() == Instruction::Xor) {
4827 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4828 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4829 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4830 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004831 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4832 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4833 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004834 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4835 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004836 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4837 InsertNewInstBefore(N, I);
4838 return BinaryOperator::createAnd(N, Op1);
4839 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004840 }
4841
Reid Spencer266e42b2006-12-23 06:05:41 +00004842 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4843 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4844 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004845 return R;
4846
Chris Lattner3af10532006-05-05 06:39:07 +00004847 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004848 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004849 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004850 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4851 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004852 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004853 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004854 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4855 I.getType(), TD) &&
4856 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4857 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004858 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4859 Op1C->getOperand(0),
4860 I.getName());
4861 InsertNewInstBefore(NewOp, I);
4862 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4863 }
Chris Lattner3af10532006-05-05 06:39:07 +00004864 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004865
4866 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004867 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4868 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4869 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004870 SI0->getOperand(1) == SI1->getOperand(1) &&
4871 (SI0->hasOneUse() || SI1->hasOneUse())) {
4872 Instruction *NewOp =
4873 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4874 SI1->getOperand(0),
4875 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004876 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4877 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004878 }
4879 }
Chris Lattner3af10532006-05-05 06:39:07 +00004880
Chris Lattner113f4f42002-06-25 16:13:24 +00004881 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004882}
4883
Chris Lattner6862fbd2004-09-29 17:40:11 +00004884static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004885 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004886}
4887
4888/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4889/// overflowed for this type.
4890static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4891 ConstantInt *In2) {
4892 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4893
Reid Spencerc635f472006-12-31 05:48:39 +00004894 return cast<ConstantInt>(Result)->getZExtValue() <
4895 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004896}
4897
Chris Lattner0798af32005-01-13 20:14:25 +00004898/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4899/// code necessary to compute the offset from the base pointer (without adding
4900/// in the base pointer). Return the result as a signed integer of intptr size.
4901static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4902 TargetData &TD = IC.getTargetData();
4903 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004904 const Type *IntPtrTy = TD.getIntPtrType();
4905 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004906
4907 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004908 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004909
Chris Lattner0798af32005-01-13 20:14:25 +00004910 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4911 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004912 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004913 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004914 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4915 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004916 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004917 Scale = ConstantExpr::getMul(OpC, Scale);
4918 if (Constant *RC = dyn_cast<Constant>(Result))
4919 Result = ConstantExpr::getAdd(RC, Scale);
4920 else {
4921 // Emit an add instruction.
4922 Result = IC.InsertNewInstBefore(
4923 BinaryOperator::createAdd(Result, Scale,
4924 GEP->getName()+".offs"), I);
4925 }
4926 }
4927 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004928 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004929 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004930 Op->getName()+".c"), I);
4931 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004932 // We'll let instcombine(mul) convert this to a shl if possible.
4933 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4934 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004935
4936 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004937 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004938 GEP->getName()+".offs"), I);
4939 }
4940 }
4941 return Result;
4942}
4943
Reid Spencer266e42b2006-12-23 06:05:41 +00004944/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004945/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004946Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4947 ICmpInst::Predicate Cond,
4948 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004949 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004950
4951 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4952 if (isa<PointerType>(CI->getOperand(0)->getType()))
4953 RHS = CI->getOperand(0);
4954
Chris Lattner0798af32005-01-13 20:14:25 +00004955 Value *PtrBase = GEPLHS->getOperand(0);
4956 if (PtrBase == RHS) {
4957 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004958 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4959 // each index is zero or not.
4960 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004961 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004962 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4963 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004964 bool EmitIt = true;
4965 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4966 if (isa<UndefValue>(C)) // undef index -> undef.
4967 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4968 if (C->isNullValue())
4969 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004970 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4971 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004972 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004973 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004974 ConstantInt::get(Type::Int1Ty,
4975 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004976 }
4977
4978 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004979 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004980 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004981 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4982 if (InVal == 0)
4983 InVal = Comp;
4984 else {
4985 InVal = InsertNewInstBefore(InVal, I);
4986 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004987 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004988 InVal = BinaryOperator::createOr(InVal, Comp);
4989 else // True if all are equal
4990 InVal = BinaryOperator::createAnd(InVal, Comp);
4991 }
4992 }
4993 }
4994
4995 if (InVal)
4996 return InVal;
4997 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004998 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004999 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5000 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00005001 }
Chris Lattner0798af32005-01-13 20:14:25 +00005002
Reid Spencer266e42b2006-12-23 06:05:41 +00005003 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005004 // the result to fold to a constant!
5005 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5006 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5007 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005008 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5009 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005010 }
5011 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005012 // If the base pointers are different, but the indices are the same, just
5013 // compare the base pointer.
5014 if (PtrBase != GEPRHS->getOperand(0)) {
5015 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005016 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005017 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005018 if (IndicesTheSame)
5019 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5020 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5021 IndicesTheSame = false;
5022 break;
5023 }
5024
5025 // If all indices are the same, just compare the base pointers.
5026 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00005027 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5028 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005029
5030 // Otherwise, the base pointers are different and the indices are
5031 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005032 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005033 }
Chris Lattner0798af32005-01-13 20:14:25 +00005034
Chris Lattner81e84172005-01-13 22:25:21 +00005035 // If one of the GEPs has all zero indices, recurse.
5036 bool AllZeros = true;
5037 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5038 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5039 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5040 AllZeros = false;
5041 break;
5042 }
5043 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005044 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5045 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005046
5047 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005048 AllZeros = true;
5049 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5050 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5051 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5052 AllZeros = false;
5053 break;
5054 }
5055 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005056 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005057
Chris Lattner4fa89822005-01-14 00:20:05 +00005058 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5059 // If the GEPs only differ by one index, compare it.
5060 unsigned NumDifferences = 0; // Keep track of # differences.
5061 unsigned DiffOperand = 0; // The operand that differs.
5062 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5063 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005064 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5065 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005066 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005067 NumDifferences = 2;
5068 break;
5069 } else {
5070 if (NumDifferences++) break;
5071 DiffOperand = i;
5072 }
5073 }
5074
5075 if (NumDifferences == 0) // SAME GEP?
5076 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00005077 ConstantInt::get(Type::Int1Ty,
5078 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00005079 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005080 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5081 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005082 // Make sure we do a signed comparison here.
5083 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005084 }
5085 }
5086
Reid Spencer266e42b2006-12-23 06:05:41 +00005087 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005088 // the result to fold to a constant!
5089 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5090 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5091 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5092 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5093 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005094 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005095 }
5096 }
5097 return 0;
5098}
5099
Reid Spencer266e42b2006-12-23 06:05:41 +00005100Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5101 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005103
Chris Lattner6ee923f2007-01-14 19:42:17 +00005104 // Fold trivial predicates.
5105 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5106 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5107 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5108 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5109
5110 // Simplify 'fcmp pred X, X'
5111 if (Op0 == Op1) {
5112 switch (I.getPredicate()) {
5113 default: assert(0 && "Unknown predicate!");
5114 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5115 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5116 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5117 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5118 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5119 case FCmpInst::FCMP_OLT: // True if ordered and less than
5120 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5121 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5122
5123 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5124 case FCmpInst::FCMP_ULT: // True if unordered or less than
5125 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5126 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5127 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5128 I.setPredicate(FCmpInst::FCMP_UNO);
5129 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5130 return &I;
5131
5132 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5133 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5134 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5135 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5136 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5137 I.setPredicate(FCmpInst::FCMP_ORD);
5138 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5139 return &I;
5140 }
5141 }
5142
Reid Spencer266e42b2006-12-23 06:05:41 +00005143 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005144 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005145
Reid Spencer266e42b2006-12-23 06:05:41 +00005146 // Handle fcmp with constant RHS
5147 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5148 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5149 switch (LHSI->getOpcode()) {
5150 case Instruction::PHI:
5151 if (Instruction *NV = FoldOpIntoPhi(I))
5152 return NV;
5153 break;
5154 case Instruction::Select:
5155 // If either operand of the select is a constant, we can fold the
5156 // comparison into the select arms, which will cause one to be
5157 // constant folded and the select turned into a bitwise or.
5158 Value *Op1 = 0, *Op2 = 0;
5159 if (LHSI->hasOneUse()) {
5160 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5161 // Fold the known value into the constant operand.
5162 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5163 // Insert a new FCmp of the other select operand.
5164 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5165 LHSI->getOperand(2), RHSC,
5166 I.getName()), I);
5167 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5168 // Fold the known value into the constant operand.
5169 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5170 // Insert a new FCmp of the other select operand.
5171 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5172 LHSI->getOperand(1), RHSC,
5173 I.getName()), I);
5174 }
5175 }
5176
5177 if (Op1)
5178 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5179 break;
5180 }
5181 }
5182
5183 return Changed ? &I : 0;
5184}
5185
5186Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5187 bool Changed = SimplifyCompare(I);
5188 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5189 const Type *Ty = Op0->getType();
5190
5191 // icmp X, X
5192 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00005193 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5194 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005195
5196 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005197 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00005198
5199 // icmp of GlobalValues can never equal each other as long as they aren't
5200 // external weak linkage type.
5201 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5202 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5203 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00005204 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5205 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005206
5207 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005208 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005209 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5210 isa<ConstantPointerNull>(Op0)) &&
5211 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00005212 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00005213 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5214 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005215
Reid Spencer266e42b2006-12-23 06:05:41 +00005216 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00005217 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005218 switch (I.getPredicate()) {
5219 default: assert(0 && "Invalid icmp instruction!");
5220 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005221 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005222 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00005223 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005224 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005225 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00005226 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005227
Reid Spencer266e42b2006-12-23 06:05:41 +00005228 case ICmpInst::ICMP_UGT:
5229 case ICmpInst::ICMP_SGT:
5230 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00005231 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005232 case ICmpInst::ICMP_ULT:
5233 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00005234 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5235 InsertNewInstBefore(Not, I);
5236 return BinaryOperator::createAnd(Not, Op1);
5237 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005238 case ICmpInst::ICMP_UGE:
5239 case ICmpInst::ICMP_SGE:
5240 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00005241 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005242 case ICmpInst::ICMP_ULE:
5243 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00005244 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5245 InsertNewInstBefore(Not, I);
5246 return BinaryOperator::createOr(Not, Op1);
5247 }
5248 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005249 }
5250
Chris Lattner2dd01742004-06-09 04:24:29 +00005251 // See if we are doing a comparison between a constant and an instruction that
5252 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005253 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005254 switch (I.getPredicate()) {
5255 default: break;
5256 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5257 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005258 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005259 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5260 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5261 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5262 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5263 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005264
Reid Spencer266e42b2006-12-23 06:05:41 +00005265 case ICmpInst::ICMP_SLT:
5266 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005267 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005268 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5269 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5270 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5271 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5272 break;
5273
5274 case ICmpInst::ICMP_UGT:
5275 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005276 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005277 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5278 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5279 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5280 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5281 break;
5282
5283 case ICmpInst::ICMP_SGT:
5284 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005285 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005286 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5287 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5288 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5289 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5290 break;
5291
5292 case ICmpInst::ICMP_ULE:
5293 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005294 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005295 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5296 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5297 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5298 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5299 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005300
Reid Spencer266e42b2006-12-23 06:05:41 +00005301 case ICmpInst::ICMP_SLE:
5302 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005303 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005304 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5305 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5306 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5307 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5308 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005309
Reid Spencer266e42b2006-12-23 06:05:41 +00005310 case ICmpInst::ICMP_UGE:
5311 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005312 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005313 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5314 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5315 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5316 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5317 break;
5318
5319 case ICmpInst::ICMP_SGE:
5320 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005321 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005322 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5323 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5324 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5325 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5326 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005327 }
5328
Reid Spencer266e42b2006-12-23 06:05:41 +00005329 // If we still have a icmp le or icmp ge instruction, turn it into the
5330 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00005331 // already been handled above, this requires little checking.
5332 //
Reid Spencer266e42b2006-12-23 06:05:41 +00005333 if (I.getPredicate() == ICmpInst::ICMP_ULE)
5334 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5335 if (I.getPredicate() == ICmpInst::ICMP_SLE)
5336 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5337 if (I.getPredicate() == ICmpInst::ICMP_UGE)
5338 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5339 if (I.getPredicate() == ICmpInst::ICMP_SGE)
5340 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00005341
5342 // See if we can fold the comparison based on bits known to be zero or one
5343 // in the input.
5344 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005345 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00005346 KnownZero, KnownOne, 0))
5347 return &I;
5348
5349 // Given the known and unknown bits, compute a range that the LHS could be
5350 // in.
5351 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005352 // Compute the Min, Max and RHS values based on the known bits. For the
5353 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00005354 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
5355 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00005356 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5357 SRHSVal = CI->getSExtValue();
5358 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
5359 SMax);
5360 } else {
5361 URHSVal = CI->getZExtValue();
5362 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
5363 UMax);
5364 }
5365 switch (I.getPredicate()) { // LE/GE have been folded already.
5366 default: assert(0 && "Unknown icmp opcode!");
5367 case ICmpInst::ICMP_EQ:
5368 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005369 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005370 break;
5371 case ICmpInst::ICMP_NE:
5372 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005373 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005374 break;
5375 case ICmpInst::ICMP_ULT:
5376 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005377 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005378 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005379 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005380 break;
5381 case ICmpInst::ICMP_UGT:
5382 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005383 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005384 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005385 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005386 break;
5387 case ICmpInst::ICMP_SLT:
5388 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005389 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005390 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005391 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005392 break;
5393 case ICmpInst::ICMP_SGT:
5394 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005395 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005396 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005397 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005398 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00005399 }
5400 }
5401
Reid Spencer266e42b2006-12-23 06:05:41 +00005402 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005403 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00005404 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00005405 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005406 switch (LHSI->getOpcode()) {
5407 case Instruction::And:
5408 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5409 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00005410 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5411
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00005413 // and/compare to be the input width without changing the value
5414 // produced, eliminating a cast.
5415 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5416 // We can do this transformation if either the AND constant does not
5417 // have its sign bit set or if it is an equality comparison.
5418 // Extending a relational comparison when we're checking the sign
5419 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005420 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00005421 (I.isEquality() ||
5422 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
5423 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
5424 ConstantInt *NewCST;
5425 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00005426 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
5427 AndCST->getZExtValue());
5428 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
5429 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00005430 Instruction *NewAnd =
5431 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
5432 LHSI->getName());
5433 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005434 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00005435 }
5436 }
5437
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005438 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5439 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5440 // happens a LOT in code produced by the C front-end, for bitfield
5441 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00005442 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5443 if (Shift && !Shift->isShift())
5444 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00005445
Reid Spencere0fc4df2006-10-20 07:07:24 +00005446 ConstantInt *ShAmt;
5447 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00005448 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5449 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005450
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005451 // We can fold this as long as we can't shift unknown bits
5452 // into the mask. This can only happen with signed shift
5453 // rights, as they sign-extend.
5454 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005455 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005456 if (!CanFold) {
5457 // To test for the bad case of the signed shr, see if any
5458 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005459 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00005460 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5461
Reid Spencer2341c222007-02-02 02:16:23 +00005462 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005463 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00005464 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
5465 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005466 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5467 CanFold = true;
5468 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005469
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005470 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00005471 Constant *NewCst;
5472 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00005473 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005474 else
5475 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005476
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005477 // Check to see if we are shifting out any of the bits being
5478 // compared.
5479 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5480 // If we shifted bits out, the fold is not going to work out.
5481 // As a special case, check to see if this means that the
5482 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00005483 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005484 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005485 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005486 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005487 } else {
5488 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005489 Constant *NewAndCST;
5490 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00005491 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005492 else
5493 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5494 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00005495 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005496 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005497 AddUsesToWorkList(I);
5498 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00005499 }
5500 }
Chris Lattner35167c32004-06-09 07:59:58 +00005501 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005502
5503 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5504 // preferable because it allows the C<<Y expression to be hoisted out
5505 // of a loop if Y is invariant and X is not.
5506 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00005507 I.isEquality() && !Shift->isArithmeticShift() &&
5508 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005509 // Compute C << Y.
5510 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00005511 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005512 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00005513 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005514 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00005515 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00005516 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00005517 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005518 }
5519 InsertNewInstBefore(cast<Instruction>(NS), I);
5520
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005521 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00005522 Instruction *NewAnd = BinaryOperator::createAnd(
5523 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005524 InsertNewInstBefore(NewAnd, I);
5525
5526 I.setOperand(0, NewAnd);
5527 return &I;
5528 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005529 }
5530 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005531
Reid Spencer266e42b2006-12-23 06:05:41 +00005532 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005533 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005534 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005535 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5536
5537 // Check that the shift amount is in range. If not, don't perform
5538 // undefined shifts. When the shift is visited it will be
5539 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005540 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005541 break;
5542
Chris Lattner272d5ca2004-09-28 18:22:15 +00005543 // If we are comparing against bits always shifted out, the
5544 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005545 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00005546 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00005547 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005548 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005549 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00005550 return ReplaceInstUsesWith(I, Cst);
5551 }
5552
5553 if (LHSI->hasOneUse()) {
5554 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005555 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005556 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00005557 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005558
Chris Lattner272d5ca2004-09-28 18:22:15 +00005559 Instruction *AndI =
5560 BinaryOperator::createAnd(LHSI->getOperand(0),
5561 Mask, LHSI->getName()+".mask");
5562 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005563 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00005564 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00005565 }
5566 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00005567 }
5568 break;
5569
Reid Spencer266e42b2006-12-23 06:05:41 +00005570 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00005571 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00005572 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005573 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005574 // Check that the shift amount is in range. If not, don't perform
5575 // undefined shifts. When the shift is visited it will be
5576 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00005577 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005578 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005579 break;
5580
Chris Lattner1023b872004-09-27 16:18:50 +00005581 // If we are comparing against bits always shifted out, the
5582 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00005583 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00005584 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00005585 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5586 ShAmt);
5587 else
5588 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5589 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005590
Chris Lattner1023b872004-09-27 16:18:50 +00005591 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005592 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005593 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00005594 return ReplaceInstUsesWith(I, Cst);
5595 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005596
Chris Lattner1023b872004-09-27 16:18:50 +00005597 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005598 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005599
Chris Lattner1023b872004-09-27 16:18:50 +00005600 // Otherwise strength reduce the shift into an and.
5601 uint64_t Val = ~0ULL; // All ones.
5602 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00005603 Val &= ~0ULL >> (64-TypeBits);
5604 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005605
Chris Lattner1023b872004-09-27 16:18:50 +00005606 Instruction *AndI =
5607 BinaryOperator::createAnd(LHSI->getOperand(0),
5608 Mask, LHSI->getName()+".mask");
5609 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005610 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00005611 ConstantExpr::getShl(CI, ShAmt));
5612 }
Chris Lattner1023b872004-09-27 16:18:50 +00005613 }
5614 }
5615 break;
Chris Lattner7e794272004-09-24 15:21:34 +00005616
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005617 case Instruction::SDiv:
5618 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00005619 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005620 // Fold this div into the comparison, producing a range check.
5621 // Determine, based on the divide type, what the range is being
5622 // checked. If there is an overflow on the low or high side, remember
5623 // it, otherwise compute the range [low, hi) bounding the new value.
5624 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005625 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005626 // FIXME: If the operand types don't match the type of the divide
5627 // then don't attempt this transform. The code below doesn't have the
5628 // logic to deal with a signed divide and an unsigned compare (and
5629 // vice versa). This is because (x /s C1) <s C2 produces different
5630 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5631 // (x /u C1) <u C2. Simply casting the operands and result won't
5632 // work. :( The if statement below tests that condition and bails
5633 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00005634 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5635 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005636 break;
5637
5638 // Initialize the variables that will indicate the nature of the
5639 // range check.
5640 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005641 ConstantInt *LoBound = 0, *HiBound = 0;
5642
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005643 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5644 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5645 // C2 (CI). By solving for X we can turn this into a range check
5646 // instead of computing a divide.
5647 ConstantInt *Prod =
5648 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00005649
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005650 // Determine if the product overflows by seeing if the product is
5651 // not equal to the divide. Make sure we do the same kind of divide
5652 // as in the LHS instruction that we're folding.
5653 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00005654 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005655 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5656
Reid Spencer266e42b2006-12-23 06:05:41 +00005657 // Get the ICmp opcode
5658 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00005659
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005660 if (DivRHS->isNullValue()) {
5661 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00005662 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00005663 LoBound = Prod;
5664 LoOverflow = ProdOV;
5665 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005666 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005667 if (CI->isNullValue()) { // (X / pos) op 0
5668 // Can't overflow.
5669 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5670 HiBound = DivRHS;
5671 } else if (isPositive(CI)) { // (X / pos) op pos
5672 LoBound = Prod;
5673 LoOverflow = ProdOV;
5674 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5675 } else { // (X / pos) op neg
5676 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5677 LoOverflow = AddWithOverflow(LoBound, Prod,
5678 cast<ConstantInt>(DivRHSH));
5679 HiBound = Prod;
5680 HiOverflow = ProdOV;
5681 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005682 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005683 if (CI->isNullValue()) { // (X / neg) op 0
5684 LoBound = AddOne(DivRHS);
5685 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005686 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005687 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00005688 } else if (isPositive(CI)) { // (X / neg) op pos
5689 HiOverflow = LoOverflow = ProdOV;
5690 if (!LoOverflow)
5691 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5692 HiBound = AddOne(Prod);
5693 } else { // (X / neg) op neg
5694 LoBound = Prod;
5695 LoOverflow = HiOverflow = ProdOV;
5696 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5697 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005698
Chris Lattnera92af962004-10-11 19:40:04 +00005699 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005700 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005701 }
5702
5703 if (LoBound) {
5704 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005705 switch (predicate) {
5706 default: assert(0 && "Unhandled icmp opcode!");
5707 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005708 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005709 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005710 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005711 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5712 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005713 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005714 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5715 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005716 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005717 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5718 true, I);
5719 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005720 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005721 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005722 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005723 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5724 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005725 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005726 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5727 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005728 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005729 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5730 false, I);
5731 case ICmpInst::ICMP_ULT:
5732 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005733 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005734 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005735 return new ICmpInst(predicate, X, LoBound);
5736 case ICmpInst::ICMP_UGT:
5737 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005738 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005740 if (predicate == ICmpInst::ICMP_UGT)
5741 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5742 else
5743 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005744 }
5745 }
5746 }
5747 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005748 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005749
Reid Spencer266e42b2006-12-23 06:05:41 +00005750 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005751 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005752 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005753
Reid Spencere0fc4df2006-10-20 07:07:24 +00005754 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5755 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005756 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5757 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005758 case Instruction::SRem:
5759 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5760 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5761 BO->hasOneUse()) {
5762 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5763 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005764 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5765 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005766 return new ICmpInst(I.getPredicate(), NewRem,
5767 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005768 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005769 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005770 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005771 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005772 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5773 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005774 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005775 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5776 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005777 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005778 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5779 // efficiently invertible, or if the add has just this one use.
5780 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005781
Chris Lattnerc992add2003-08-13 05:33:12 +00005782 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005783 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005784 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005785 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005786 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005787 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005788 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005789 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005790 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005791 }
5792 }
5793 break;
5794 case Instruction::Xor:
5795 // For the xor case, we can xor two constants together, eliminating
5796 // the explicit xor.
5797 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005798 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5799 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005800
5801 // FALLTHROUGH
5802 case Instruction::Sub:
5803 // Replace (([sub|xor] A, B) != 0) with (A != B)
5804 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005805 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5806 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005807 break;
5808
5809 case Instruction::Or:
5810 // If bits are being or'd in that are not present in the constant we
5811 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005812 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005813 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005814 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005815 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5816 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005817 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005818 break;
5819
5820 case Instruction::And:
5821 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005822 // If bits are being compared against that are and'd out, then the
5823 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005824 if (!ConstantExpr::getAnd(CI,
5825 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005826 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5827 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005828
Chris Lattner35167c32004-06-09 07:59:58 +00005829 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005830 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005831 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5832 ICmpInst::ICMP_NE, Op0,
5833 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005834
Reid Spencer266e42b2006-12-23 06:05:41 +00005835 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005836 if (isSignBit(BOC)) {
5837 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005838 Constant *Zero = Constant::getNullValue(X->getType());
5839 ICmpInst::Predicate pred = isICMP_NE ?
5840 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5841 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005842 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005843
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005844 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005845 if (CI->isNullValue() && isHighOnes(BOC)) {
5846 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005847 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005848 ICmpInst::Predicate pred = isICMP_NE ?
5849 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5850 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005851 }
5852
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005853 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005854 default: break;
5855 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005856 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5857 // Handle set{eq|ne} <intrinsic>, intcst.
5858 switch (II->getIntrinsicID()) {
5859 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005860 case Intrinsic::bswap_i16:
5861 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005862 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005863 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005864 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005865 ByteSwap_16(CI->getZExtValue())));
5866 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005867 case Intrinsic::bswap_i32:
5868 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005869 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005870 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005871 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005872 ByteSwap_32(CI->getZExtValue())));
5873 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005874 case Intrinsic::bswap_i64:
5875 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005876 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005877 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005878 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005879 ByteSwap_64(CI->getZExtValue())));
5880 return &I;
5881 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005882 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005883 } else { // Not a ICMP_EQ/ICMP_NE
5884 // If the LHS is a cast from an integral value of the same size, then
5885 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005886 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5887 Value *CastOp = Cast->getOperand(0);
5888 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005889 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005890 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005891 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005892 // If this is an unsigned comparison, try to make the comparison use
5893 // smaller constant values.
5894 switch (I.getPredicate()) {
5895 default: break;
5896 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5897 ConstantInt *CUI = cast<ConstantInt>(CI);
5898 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5899 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer24f1a0e2007-03-01 19:33:52 +00005900 ConstantInt::get(SrcTy, -1ULL));
Reid Spencer266e42b2006-12-23 06:05:41 +00005901 break;
5902 }
5903 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5904 ConstantInt *CUI = cast<ConstantInt>(CI);
5905 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5906 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5907 Constant::getNullValue(SrcTy));
5908 break;
5909 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005910 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005911
Chris Lattner2b55ea32004-02-23 07:16:20 +00005912 }
5913 }
Chris Lattnere967b342003-06-04 05:10:11 +00005914 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005915 }
5916
Reid Spencer266e42b2006-12-23 06:05:41 +00005917 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005918 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5919 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5920 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005921 case Instruction::GetElementPtr:
5922 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005923 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005924 bool isAllZeros = true;
5925 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5926 if (!isa<Constant>(LHSI->getOperand(i)) ||
5927 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5928 isAllZeros = false;
5929 break;
5930 }
5931 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005932 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005933 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5934 }
5935 break;
5936
Chris Lattner77c32c32005-04-23 15:31:55 +00005937 case Instruction::PHI:
5938 if (Instruction *NV = FoldOpIntoPhi(I))
5939 return NV;
5940 break;
5941 case Instruction::Select:
5942 // If either operand of the select is a constant, we can fold the
5943 // comparison into the select arms, which will cause one to be
5944 // constant folded and the select turned into a bitwise or.
5945 Value *Op1 = 0, *Op2 = 0;
5946 if (LHSI->hasOneUse()) {
5947 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5948 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005949 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5950 // Insert a new ICmp of the other select operand.
5951 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5952 LHSI->getOperand(2), RHSC,
5953 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005954 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5955 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005956 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5957 // Insert a new ICmp of the other select operand.
5958 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5959 LHSI->getOperand(1), RHSC,
5960 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005961 }
5962 }
Jeff Cohen82639852005-04-23 21:38:35 +00005963
Chris Lattner77c32c32005-04-23 15:31:55 +00005964 if (Op1)
5965 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5966 break;
5967 }
5968 }
5969
Reid Spencer266e42b2006-12-23 06:05:41 +00005970 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005971 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005972 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005973 return NI;
5974 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005975 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5976 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005977 return NI;
5978
Reid Spencer266e42b2006-12-23 06:05:41 +00005979 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005980 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5981 // now.
5982 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5983 if (isa<PointerType>(Op0->getType()) &&
5984 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005985 // We keep moving the cast from the left operand over to the right
5986 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005987 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005988
Chris Lattner64d87b02007-01-06 01:45:59 +00005989 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5990 // so eliminate it as well.
5991 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5992 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005993
Chris Lattner16930792003-11-03 04:25:02 +00005994 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005995 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005996 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005997 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005998 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005999 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00006000 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00006001 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006002 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00006003 }
Chris Lattner64d87b02007-01-06 01:45:59 +00006004 }
6005
6006 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006007 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00006008 // This comes up when you have code like
6009 // int X = A < B;
6010 // if (X) ...
6011 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006012 // with a constant or another cast from the same type.
6013 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006014 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006015 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00006016 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006017
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006018 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006019 Value *A, *B, *C, *D;
6020 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6021 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6022 Value *OtherVal = A == Op1 ? B : A;
6023 return new ICmpInst(I.getPredicate(), OtherVal,
6024 Constant::getNullValue(A->getType()));
6025 }
6026
6027 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6028 // A^c1 == C^c2 --> A == C^(c1^c2)
6029 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6030 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6031 if (Op1->hasOneUse()) {
6032 Constant *NC = ConstantExpr::getXor(C1, C2);
6033 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6034 return new ICmpInst(I.getPredicate(), A,
6035 InsertNewInstBefore(Xor, I));
6036 }
6037
6038 // A^B == A^D -> B == D
6039 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6040 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6041 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6042 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6043 }
6044 }
6045
6046 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6047 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006048 // A == (A^B) -> B == 0
6049 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00006050 return new ICmpInst(I.getPredicate(), OtherVal,
6051 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006052 }
6053 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006054 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006055 return new ICmpInst(I.getPredicate(), B,
6056 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006057 }
6058 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006059 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006060 return new ICmpInst(I.getPredicate(), B,
6061 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006062 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006063
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006064 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6065 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6066 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6067 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6068 Value *X = 0, *Y = 0, *Z = 0;
6069
6070 if (A == C) {
6071 X = B; Y = D; Z = A;
6072 } else if (A == D) {
6073 X = B; Y = C; Z = A;
6074 } else if (B == C) {
6075 X = A; Y = D; Z = B;
6076 } else if (B == D) {
6077 X = A; Y = C; Z = B;
6078 }
6079
6080 if (X) { // Build (X^Y) & Z
6081 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6082 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6083 I.setOperand(0, Op1);
6084 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6085 return &I;
6086 }
6087 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006088 }
Chris Lattner113f4f42002-06-25 16:13:24 +00006089 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006090}
6091
Reid Spencer266e42b2006-12-23 06:05:41 +00006092// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006093// We only handle extending casts so far.
6094//
Reid Spencer266e42b2006-12-23 06:05:41 +00006095Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6096 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006097 Value *LHSCIOp = LHSCI->getOperand(0);
6098 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00006099 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006100 Value *RHSCIOp;
6101
Reid Spencer266e42b2006-12-23 06:05:41 +00006102 // We only handle extension cast instructions, so far. Enforce this.
6103 if (LHSCI->getOpcode() != Instruction::ZExt &&
6104 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00006105 return 0;
6106
Reid Spencer266e42b2006-12-23 06:05:41 +00006107 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6108 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006109
Reid Spencer266e42b2006-12-23 06:05:41 +00006110 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006111 // Not an extension from the same type?
6112 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006113 if (RHSCIOp->getType() != LHSCIOp->getType())
6114 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00006115
6116 // If the signedness of the two compares doesn't agree (i.e. one is a sext
6117 // and the other is a zext), then we can't handle this.
6118 if (CI->getOpcode() != LHSCI->getOpcode())
6119 return 0;
6120
6121 // Likewise, if the signedness of the [sz]exts and the compare don't match,
6122 // then we can't handle this.
6123 if (isSignedExt != isSignedCmp && !ICI.isEquality())
6124 return 0;
6125
6126 // Okay, just insert a compare of the reduced operands now!
6127 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00006128 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006129
Reid Spencer266e42b2006-12-23 06:05:41 +00006130 // If we aren't dealing with a constant on the RHS, exit early
6131 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6132 if (!CI)
6133 return 0;
6134
6135 // Compute the constant that would happen if we truncated to SrcTy then
6136 // reextended to DestTy.
6137 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6138 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6139
6140 // If the re-extended constant didn't change...
6141 if (Res2 == CI) {
6142 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6143 // For example, we might have:
6144 // %A = sext short %X to uint
6145 // %B = icmp ugt uint %A, 1330
6146 // It is incorrect to transform this into
6147 // %B = icmp ugt short %X, 1330
6148 // because %A may have negative value.
6149 //
6150 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6151 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00006152 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00006153 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6154 else
6155 return 0;
6156 }
6157
6158 // The re-extended constant changed so the constant cannot be represented
6159 // in the shorter type. Consequently, we cannot emit a simple comparison.
6160
6161 // First, handle some easy cases. We know the result cannot be equal at this
6162 // point so handle the ICI.isEquality() cases
6163 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006164 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00006165 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006166 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00006167
6168 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6169 // should have been folded away previously and not enter in here.
6170 Value *Result;
6171 if (isSignedCmp) {
6172 // We're performing a signed comparison.
6173 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006174 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00006175 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00006176 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006177 } else {
6178 // We're performing an unsigned comparison.
6179 if (isSignedExt) {
6180 // We're performing an unsigned comp with a sign extended value.
6181 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00006182 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00006183 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6184 NegOne, ICI.getName()), ICI);
6185 } else {
6186 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006187 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006188 }
6189 }
6190
6191 // Finally, return the value computed.
6192 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6193 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6194 return ReplaceInstUsesWith(ICI, Result);
6195 } else {
6196 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6197 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6198 "ICmp should be folded!");
6199 if (Constant *CI = dyn_cast<Constant>(Result))
6200 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6201 else
6202 return BinaryOperator::createNot(Result);
6203 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006204}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006205
Reid Spencer2341c222007-02-02 02:16:23 +00006206Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6207 return commonShiftTransforms(I);
6208}
6209
6210Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6211 return commonShiftTransforms(I);
6212}
6213
6214Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6215 return commonShiftTransforms(I);
6216}
6217
6218Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6219 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00006220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006221
6222 // shl X, 0 == X and shr X, 0 == X
6223 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00006224 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00006225 Op0 == Constant::getNullValue(Op0->getType()))
6226 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006227
Reid Spencer266e42b2006-12-23 06:05:41 +00006228 if (isa<UndefValue>(Op0)) {
6229 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00006230 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006231 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6233 }
6234 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006235 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6236 return ReplaceInstUsesWith(I, Op0);
6237 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006238 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00006239 }
6240
Chris Lattnerd4dee402006-11-10 23:38:52 +00006241 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6242 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00006243 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00006244 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006245 return ReplaceInstUsesWith(I, CSI);
6246
Chris Lattner183b3362004-04-09 19:05:30 +00006247 // Try to fold constant and into select arguments.
6248 if (isa<Constant>(Op0))
6249 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00006250 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00006251 return R;
6252
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00006253 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006254 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00006255 if (MaskedValueIsZero(Op0,
6256 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006257 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00006258 }
6259 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006260
Reid Spencere0fc4df2006-10-20 07:07:24 +00006261 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00006262 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6263 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00006264 return 0;
6265}
6266
Reid Spencere0fc4df2006-10-20 07:07:24 +00006267Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00006268 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006269 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00006270
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006271 // See if we can simplify any instructions used by the instruction whose sole
6272 // purpose is to compute bits we don't care about.
6273 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006274 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006275 KnownZero, KnownOne))
6276 return &I;
6277
Chris Lattner14553932006-01-06 07:12:35 +00006278 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6279 // of a signed value.
6280 //
6281 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006282 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006283 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00006284 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6285 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006286 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00006287 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00006288 }
Chris Lattner14553932006-01-06 07:12:35 +00006289 }
6290
6291 // ((X*C1) << C2) == (X * (C1 << C2))
6292 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6293 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6294 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6295 return BinaryOperator::createMul(BO->getOperand(0),
6296 ConstantExpr::getShl(BOOp, Op1));
6297
6298 // Try to fold constant and into select arguments.
6299 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6300 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6301 return R;
6302 if (isa<PHINode>(Op0))
6303 if (Instruction *NV = FoldOpIntoPhi(I))
6304 return NV;
6305
6306 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00006307 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6308 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6309 Value *V1, *V2;
6310 ConstantInt *CC;
6311 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006312 default: break;
6313 case Instruction::Add:
6314 case Instruction::And:
6315 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00006316 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006317 // These operators commute.
6318 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006319 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6320 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00006321 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006322 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00006323 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00006324 Op0BO->getName());
6325 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006326 Instruction *X =
6327 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6328 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006329 InsertNewInstBefore(X, I); // (X + (Y << C))
6330 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00006331 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00006332 return BinaryOperator::createAnd(X, C2);
6333 }
Chris Lattner14553932006-01-06 07:12:35 +00006334
Chris Lattner797dee72005-09-18 06:30:59 +00006335 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00006336 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006337 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00006338 match(Op0BOOp1,
6339 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006340 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6341 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006342 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006343 Op0BO->getOperand(0), Op1,
6344 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006345 InsertNewInstBefore(YS, I); // (Y << C)
6346 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006347 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006348 V1->getName()+".mask");
6349 InsertNewInstBefore(XM, I); // X & (CC << C)
6350
6351 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6352 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006353 }
Chris Lattner14553932006-01-06 07:12:35 +00006354
Reid Spencer2f34b982007-02-02 14:41:37 +00006355 // FALL THROUGH.
6356 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006357 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006358 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6359 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00006360 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006361 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006362 Op0BO->getOperand(1), Op1,
6363 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006364 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006365 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00006366 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006367 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006368 InsertNewInstBefore(X, I); // (X + (Y << C))
6369 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00006370 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00006371 return BinaryOperator::createAnd(X, C2);
6372 }
Chris Lattner14553932006-01-06 07:12:35 +00006373
Chris Lattner1df0e982006-05-31 21:14:00 +00006374 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006375 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6376 match(Op0BO->getOperand(0),
6377 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00006378 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006379 cast<BinaryOperator>(Op0BO->getOperand(0))
6380 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006381 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006382 Op0BO->getOperand(1), Op1,
6383 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006384 InsertNewInstBefore(YS, I); // (Y << C)
6385 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006386 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006387 V1->getName()+".mask");
6388 InsertNewInstBefore(XM, I); // X & (CC << C)
6389
Chris Lattner1df0e982006-05-31 21:14:00 +00006390 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00006391 }
Chris Lattner14553932006-01-06 07:12:35 +00006392
Chris Lattner27cb9db2005-09-18 05:12:10 +00006393 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00006394 }
Chris Lattner14553932006-01-06 07:12:35 +00006395 }
6396
6397
6398 // If the operand is an bitwise operator with a constant RHS, and the
6399 // shift is the only use, we can pull it out of the shift.
6400 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6401 bool isValid = true; // Valid only for And, Or, Xor
6402 bool highBitSet = false; // Transform if high bit of constant set?
6403
6404 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006405 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00006406 case Instruction::Add:
6407 isValid = isLeftShift;
6408 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006409 case Instruction::Or:
6410 case Instruction::Xor:
6411 highBitSet = false;
6412 break;
6413 case Instruction::And:
6414 highBitSet = true;
6415 break;
Chris Lattner14553932006-01-06 07:12:35 +00006416 }
6417
6418 // If this is a signed shift right, and the high bit is modified
6419 // by the logical operation, do not perform the transformation.
6420 // The highBitSet boolean indicates the value of the high bit of
6421 // the constant which would cause it to be modified for this
6422 // operation.
6423 //
Chris Lattner3e009e82007-02-05 00:57:54 +00006424 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006425 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00006426 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
6427 }
6428
6429 if (isValid) {
6430 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6431
6432 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006433 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00006434 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006435 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00006436
6437 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6438 NewRHS);
6439 }
6440 }
6441 }
6442 }
6443
Chris Lattnereb372a02006-01-06 07:52:12 +00006444 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00006445 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6446 if (ShiftOp && !ShiftOp->isShift())
6447 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00006448
Reid Spencere0fc4df2006-10-20 07:07:24 +00006449 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006450 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006451 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6452 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00006453 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6454 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6455 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00006456
Chris Lattner3e009e82007-02-05 00:57:54 +00006457 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6458 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
6459 AmtSum = I.getType()->getPrimitiveSizeInBits();
6460
6461 const IntegerType *Ty = cast<IntegerType>(I.getType());
6462
6463 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00006464 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00006465 return BinaryOperator::create(I.getOpcode(), X,
6466 ConstantInt::get(Ty, AmtSum));
6467 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6468 I.getOpcode() == Instruction::AShr) {
6469 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6470 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6471 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6472 I.getOpcode() == Instruction::LShr) {
6473 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6474 Instruction *Shift =
6475 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6476 InsertNewInstBefore(Shift, I);
6477
6478 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6479 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006480 }
6481
Chris Lattner3e009e82007-02-05 00:57:54 +00006482 // Okay, if we get here, one shift must be left, and the other shift must be
6483 // right. See if the amounts are equal.
6484 if (ShiftAmt1 == ShiftAmt2) {
6485 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6486 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00006487 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00006488 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6489 }
6490 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6491 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00006492 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00006493 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6494 }
6495 // We can simplify ((X << C) >>s C) into a trunc + sext.
6496 // NOTE: we could do this for any C, but that would make 'unusual' integer
6497 // types. For now, just stick to ones well-supported by the code
6498 // generators.
6499 const Type *SExtType = 0;
6500 switch (Ty->getBitWidth() - ShiftAmt1) {
6501 case 8 : SExtType = Type::Int8Ty; break;
6502 case 16: SExtType = Type::Int16Ty; break;
6503 case 32: SExtType = Type::Int32Ty; break;
6504 default: break;
6505 }
6506 if (SExtType) {
6507 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6508 InsertNewInstBefore(NewTrunc, I);
6509 return new SExtInst(NewTrunc, Ty);
6510 }
6511 // Otherwise, we can't handle it yet.
6512 } else if (ShiftAmt1 < ShiftAmt2) {
6513 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00006514
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006515 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006516 if (I.getOpcode() == Instruction::Shl) {
6517 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6518 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006519 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00006520 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006521 InsertNewInstBefore(Shift, I);
6522
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006523 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006524 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006525 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006526
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006527 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006528 if (I.getOpcode() == Instruction::LShr) {
6529 assert(ShiftOp->getOpcode() == Instruction::Shl);
6530 Instruction *Shift =
6531 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6532 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00006533
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006534 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006535 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006536 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006537
6538 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6539 } else {
6540 assert(ShiftAmt2 < ShiftAmt1);
6541 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6542
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006543 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006544 if (I.getOpcode() == Instruction::Shl) {
6545 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6546 ShiftOp->getOpcode() == Instruction::AShr);
6547 Instruction *Shift =
6548 BinaryOperator::create(ShiftOp->getOpcode(), X,
6549 ConstantInt::get(Ty, ShiftDiff));
6550 InsertNewInstBefore(Shift, I);
6551
6552 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6553 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6554 }
6555
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006556 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006557 if (I.getOpcode() == Instruction::LShr) {
6558 assert(ShiftOp->getOpcode() == Instruction::Shl);
6559 Instruction *Shift =
6560 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6561 InsertNewInstBefore(Shift, I);
6562
6563 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6564 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6565 }
6566
6567 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006568 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006569 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006570 return 0;
6571}
6572
Chris Lattner48a44f72002-05-02 17:06:02 +00006573
Chris Lattner8f663e82005-10-29 04:36:15 +00006574/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6575/// expression. If so, decompose it, returning some value X, such that Val is
6576/// X*Scale+Offset.
6577///
6578static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6579 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006580 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006581 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006582 Offset = CI->getZExtValue();
6583 Scale = 1;
6584 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006585 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6586 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006587 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006588 if (I->getOpcode() == Instruction::Shl) {
6589 // This is a value scaled by '1 << the shift amt'.
6590 Scale = 1U << CUI->getZExtValue();
6591 Offset = 0;
6592 return I->getOperand(0);
6593 } else if (I->getOpcode() == Instruction::Mul) {
6594 // This value is scaled by 'CUI'.
6595 Scale = CUI->getZExtValue();
6596 Offset = 0;
6597 return I->getOperand(0);
6598 } else if (I->getOpcode() == Instruction::Add) {
6599 // We have X+C. Check to see if we really have (X*C2)+C1,
6600 // where C1 is divisible by C2.
6601 unsigned SubScale;
6602 Value *SubVal =
6603 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6604 Offset += CUI->getZExtValue();
6605 if (SubScale > 1 && (Offset % SubScale == 0)) {
6606 Scale = SubScale;
6607 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006608 }
6609 }
6610 }
6611 }
6612 }
6613
6614 // Otherwise, we can't look past this.
6615 Scale = 1;
6616 Offset = 0;
6617 return Val;
6618}
6619
6620
Chris Lattner216be912005-10-24 06:03:58 +00006621/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6622/// try to eliminate the cast by moving the type information into the alloc.
6623Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6624 AllocationInst &AI) {
6625 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006626 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006627
Chris Lattnerac87beb2005-10-24 06:22:12 +00006628 // Remove any uses of AI that are dead.
6629 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006630
Chris Lattnerac87beb2005-10-24 06:22:12 +00006631 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6632 Instruction *User = cast<Instruction>(*UI++);
6633 if (isInstructionTriviallyDead(User)) {
6634 while (UI != E && *UI == User)
6635 ++UI; // If this instruction uses AI more than once, don't break UI.
6636
Chris Lattnerac87beb2005-10-24 06:22:12 +00006637 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006638 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006639 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006640 }
6641 }
6642
Chris Lattner216be912005-10-24 06:03:58 +00006643 // Get the type really allocated and the type casted to.
6644 const Type *AllocElTy = AI.getAllocatedType();
6645 const Type *CastElTy = PTy->getElementType();
6646 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006647
Chris Lattner945e4372007-02-14 05:52:17 +00006648 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6649 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006650 if (CastElTyAlign < AllocElTyAlign) return 0;
6651
Chris Lattner46705b22005-10-24 06:35:18 +00006652 // If the allocation has multiple uses, only promote it if we are strictly
6653 // increasing the alignment of the resultant allocation. If we keep it the
6654 // same, we open the door to infinite loops of various kinds.
6655 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6656
Chris Lattner216be912005-10-24 06:03:58 +00006657 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6658 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006659 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006660
Chris Lattner8270c332005-10-29 03:19:53 +00006661 // See if we can satisfy the modulus by pulling a scale out of the array
6662 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00006663 unsigned ArraySizeScale, ArrayOffset;
6664 Value *NumElements = // See if the array size is a decomposable linear expr.
6665 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6666
Chris Lattner8270c332005-10-29 03:19:53 +00006667 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6668 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006669 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6670 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006671
Chris Lattner8270c332005-10-29 03:19:53 +00006672 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6673 Value *Amt = 0;
6674 if (Scale == 1) {
6675 Amt = NumElements;
6676 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006677 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006678 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6679 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006680 Amt = ConstantExpr::getMul(
6681 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6682 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006683 else if (Scale != 1) {
6684 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6685 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006686 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006687 }
6688
Chris Lattner8f663e82005-10-29 04:36:15 +00006689 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006690 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006691 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6692 Amt = InsertNewInstBefore(Tmp, AI);
6693 }
6694
Chris Lattner216be912005-10-24 06:03:58 +00006695 AllocationInst *New;
6696 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006697 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006698 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006699 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006700 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006701 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006702
6703 // If the allocation has multiple uses, insert a cast and change all things
6704 // that used it to use the new cast. This will also hack on CI, but it will
6705 // die soon.
6706 if (!AI.hasOneUse()) {
6707 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006708 // New is the allocation instruction, pointer typed. AI is the original
6709 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6710 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006711 InsertNewInstBefore(NewCast, AI);
6712 AI.replaceAllUsesWith(NewCast);
6713 }
Chris Lattner216be912005-10-24 06:03:58 +00006714 return ReplaceInstUsesWith(CI, New);
6715}
6716
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006717/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006718/// and return it as type Ty without inserting any new casts and without
6719/// changing the computed value. This is used by code that tries to decide
6720/// whether promoting or shrinking integer operations to wider or smaller types
6721/// will allow us to eliminate a truncate or extend.
6722///
6723/// This is a truncation operation if Ty is smaller than V->getType(), or an
6724/// extension operation if Ty is larger.
6725static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006726 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006727 // We can always evaluate constants in another type.
6728 if (isa<ConstantInt>(V))
6729 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006730
6731 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006732 if (!I) return false;
6733
6734 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006735
6736 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006737 case Instruction::Add:
6738 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006739 case Instruction::And:
6740 case Instruction::Or:
6741 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006742 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006743 // These operators can all arbitrarily be extended or truncated.
6744 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6745 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006746
Chris Lattner960acb02006-11-29 07:18:39 +00006747 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006748 if (!I->hasOneUse()) return false;
6749 // If we are truncating the result of this SHL, and if it's a shift of a
6750 // constant amount, we can always perform a SHL in a smaller type.
6751 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6752 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6753 CI->getZExtValue() < Ty->getBitWidth())
6754 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6755 }
6756 break;
6757 case Instruction::LShr:
6758 if (!I->hasOneUse()) return false;
6759 // If this is a truncate of a logical shr, we can truncate it to a smaller
6760 // lshr iff we know that the bits we would otherwise be shifting in are
6761 // already zeros.
6762 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6763 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6764 MaskedValueIsZero(I->getOperand(0),
6765 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6766 CI->getZExtValue() < Ty->getBitWidth()) {
6767 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6768 }
6769 }
Chris Lattner960acb02006-11-29 07:18:39 +00006770 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006771 case Instruction::Trunc:
6772 case Instruction::ZExt:
6773 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006774 // If this is a cast from the destination type, we can trivially eliminate
6775 // it, and this will remove a cast overall.
6776 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006777 // If the first operand is itself a cast, and is eliminable, do not count
6778 // this as an eliminable cast. We would prefer to eliminate those two
6779 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006780 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006781 return true;
6782
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006783 ++NumCastsRemoved;
6784 return true;
6785 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006786 break;
6787 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006788 // TODO: Can handle more cases here.
6789 break;
6790 }
6791
6792 return false;
6793}
6794
6795/// EvaluateInDifferentType - Given an expression that
6796/// CanEvaluateInDifferentType returns true for, actually insert the code to
6797/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006798Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006799 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006800 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006801 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006802
6803 // Otherwise, it must be an instruction.
6804 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006805 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006806 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006807 case Instruction::Add:
6808 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006809 case Instruction::And:
6810 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006811 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006812 case Instruction::AShr:
6813 case Instruction::LShr:
6814 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006815 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006816 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6817 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6818 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006819 break;
6820 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006821 case Instruction::Trunc:
6822 case Instruction::ZExt:
6823 case Instruction::SExt:
6824 case Instruction::BitCast:
6825 // If the source type of the cast is the type we're trying for then we can
6826 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006827 if (I->getOperand(0)->getType() == Ty)
6828 return I->getOperand(0);
6829
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006830 // Some other kind of cast, which shouldn't happen, so just ..
6831 // FALL THROUGH
6832 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006833 // TODO: Can handle more cases here.
6834 assert(0 && "Unreachable!");
6835 break;
6836 }
6837
6838 return InsertNewInstBefore(Res, *I);
6839}
6840
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006841/// @brief Implement the transforms common to all CastInst visitors.
6842Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006843 Value *Src = CI.getOperand(0);
6844
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006845 // Casting undef to anything results in undef so might as just replace it and
6846 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006847 if (isa<UndefValue>(Src)) // cast undef -> undef
6848 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6849
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006850 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6851 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006852 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006853 if (Instruction::CastOps opc =
6854 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6855 // The first cast (CSrc) is eliminable so we need to fix up or replace
6856 // the second cast (CI). CSrc will then have a good chance of being dead.
6857 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006858 }
6859 }
Chris Lattner03841652004-05-25 04:29:21 +00006860
Chris Lattnerd0d51602003-06-21 23:12:02 +00006861 // If casting the result of a getelementptr instruction with no offset, turn
6862 // this into a cast of the original pointer!
6863 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006864 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006865 bool AllZeroOperands = true;
6866 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6867 if (!isa<Constant>(GEP->getOperand(i)) ||
6868 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6869 AllZeroOperands = false;
6870 break;
6871 }
6872 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006873 // Changing the cast operand is usually not a good idea but it is safe
6874 // here because the pointer operand is being replaced with another
6875 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006876 CI.setOperand(0, GEP->getOperand(0));
6877 return &CI;
6878 }
6879 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006880
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006881 // If we are casting a malloc or alloca to a pointer to a type of the same
6882 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006883 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006884 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6885 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006886
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006887 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006888 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6889 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6890 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006891
6892 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006893 if (isa<PHINode>(Src))
6894 if (Instruction *NV = FoldOpIntoPhi(CI))
6895 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006896
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006897 return 0;
6898}
6899
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006900/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6901/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006902/// cases.
6903/// @brief Implement the transforms common to CastInst with integer operands
6904Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6905 if (Instruction *Result = commonCastTransforms(CI))
6906 return Result;
6907
6908 Value *Src = CI.getOperand(0);
6909 const Type *SrcTy = Src->getType();
6910 const Type *DestTy = CI.getType();
6911 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6912 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6913
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006914 // See if we can simplify any instructions used by the LHS whose sole
6915 // purpose is to compute bits we don't care about.
6916 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006917 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006918 KnownZero, KnownOne))
6919 return &CI;
6920
6921 // If the source isn't an instruction or has more than one use then we
6922 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006923 Instruction *SrcI = dyn_cast<Instruction>(Src);
6924 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006925 return 0;
6926
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006927 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006928 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006929 if (!isa<BitCastInst>(CI) &&
6930 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6931 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006932 // If this cast is a truncate, evaluting in a different type always
6933 // eliminates the cast, so it is always a win. If this is a noop-cast
6934 // this just removes a noop cast which isn't pointful, but simplifies
6935 // the code. If this is a zero-extension, we need to do an AND to
6936 // maintain the clear top-part of the computation, so we require that
6937 // the input have eliminated at least one cast. If this is a sign
6938 // extension, we insert two new casts (to do the extension) so we
6939 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006940 bool DoXForm;
6941 switch (CI.getOpcode()) {
6942 default:
6943 // All the others use floating point so we shouldn't actually
6944 // get here because of the check above.
6945 assert(0 && "Unknown cast type");
6946 case Instruction::Trunc:
6947 DoXForm = true;
6948 break;
6949 case Instruction::ZExt:
6950 DoXForm = NumCastsRemoved >= 1;
6951 break;
6952 case Instruction::SExt:
6953 DoXForm = NumCastsRemoved >= 2;
6954 break;
6955 case Instruction::BitCast:
6956 DoXForm = false;
6957 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006958 }
6959
6960 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006961 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6962 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006963 assert(Res->getType() == DestTy);
6964 switch (CI.getOpcode()) {
6965 default: assert(0 && "Unknown cast type!");
6966 case Instruction::Trunc:
6967 case Instruction::BitCast:
6968 // Just replace this cast with the result.
6969 return ReplaceInstUsesWith(CI, Res);
6970 case Instruction::ZExt: {
6971 // We need to emit an AND to clear the high bits.
6972 assert(SrcBitSize < DestBitSize && "Not a zext?");
6973 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006974 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006975 if (DestBitSize < 64)
6976 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006977 return BinaryOperator::createAnd(Res, C);
6978 }
6979 case Instruction::SExt:
6980 // We need to emit a cast to truncate, then a cast to sext.
6981 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006982 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6983 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006984 }
6985 }
6986 }
6987
6988 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6989 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6990
6991 switch (SrcI->getOpcode()) {
6992 case Instruction::Add:
6993 case Instruction::Mul:
6994 case Instruction::And:
6995 case Instruction::Or:
6996 case Instruction::Xor:
6997 // If we are discarding information, or just changing the sign,
6998 // rewrite.
6999 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7000 // Don't insert two casts if they cannot be eliminated. We allow
7001 // two casts to be inserted if the sizes are the same. This could
7002 // only be converting signedness, which is a noop.
7003 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007004 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7005 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007006 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007007 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7008 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7009 return BinaryOperator::create(
7010 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007011 }
7012 }
7013
7014 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7015 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7016 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00007017 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007018 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007019 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007020 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7021 }
7022 break;
7023 case Instruction::SDiv:
7024 case Instruction::UDiv:
7025 case Instruction::SRem:
7026 case Instruction::URem:
7027 // If we are just changing the sign, rewrite.
7028 if (DestBitSize == SrcBitSize) {
7029 // Don't insert two casts if they cannot be eliminated. We allow
7030 // two casts to be inserted if the sizes are the same. This could
7031 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00007032 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7033 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007034 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7035 Op0, DestTy, SrcI);
7036 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7037 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007038 return BinaryOperator::create(
7039 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7040 }
7041 }
7042 break;
7043
7044 case Instruction::Shl:
7045 // Allow changing the sign of the source operand. Do not allow
7046 // changing the size of the shift, UNLESS the shift amount is a
7047 // constant. We must not change variable sized shifts to a smaller
7048 // size, because it is undefined to shift more bits out than exist
7049 // in the value.
7050 if (DestBitSize == SrcBitSize ||
7051 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007052 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7053 Instruction::BitCast : Instruction::Trunc);
7054 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00007055 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007056 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007057 }
7058 break;
7059 case Instruction::AShr:
7060 // If this is a signed shr, and if all bits shifted in are about to be
7061 // truncated off, turn it into an unsigned shr to allow greater
7062 // simplifications.
7063 if (DestBitSize < SrcBitSize &&
7064 isa<ConstantInt>(Op1)) {
7065 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7066 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7067 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00007068 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007069 }
7070 }
7071 break;
7072
Reid Spencer266e42b2006-12-23 06:05:41 +00007073 case Instruction::ICmp:
7074 // If we are just checking for a icmp eq of a single bit and casting it
7075 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007076 // cast to integer to avoid the comparison.
7077 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
7078 uint64_t Op1CV = Op1C->getZExtValue();
7079 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
7080 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7081 // cast (X == 1) to int --> X iff X has only the low bit set.
7082 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
7083 // cast (X != 0) to int --> X iff X has only the low bit set.
7084 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
7085 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
7086 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7087 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
7088 // If Op1C some other power of two, convert:
7089 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00007090 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007091 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00007092
7093 // This only works for EQ and NE
7094 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7095 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7096 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007097
7098 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00007099 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007100 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
7101 // (X&4) == 2 --> false
7102 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00007103 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007104 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007105 return ReplaceInstUsesWith(CI, Res);
7106 }
7107
7108 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
7109 Value *In = Op0;
7110 if (ShiftAmt) {
7111 // Perform a logical shr by shiftamt.
7112 // Insert the shift to put the result in the low bit.
7113 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007114 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00007115 ConstantInt::get(In->getType(), ShiftAmt),
7116 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007117 }
7118
Reid Spencer266e42b2006-12-23 06:05:41 +00007119 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007120 Constant *One = ConstantInt::get(In->getType(), 1);
7121 In = BinaryOperator::createXor(In, One, "tmp");
7122 InsertNewInstBefore(cast<Instruction>(In), CI);
7123 }
7124
7125 if (CI.getType() == In->getType())
7126 return ReplaceInstUsesWith(CI, In);
7127 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007128 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007129 }
7130 }
7131 }
7132 break;
7133 }
7134 return 0;
7135}
7136
7137Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007138 if (Instruction *Result = commonIntCastTransforms(CI))
7139 return Result;
7140
7141 Value *Src = CI.getOperand(0);
7142 const Type *Ty = CI.getType();
7143 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
7144
7145 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7146 switch (SrcI->getOpcode()) {
7147 default: break;
7148 case Instruction::LShr:
7149 // We can shrink lshr to something smaller if we know the bits shifted in
7150 // are already zeros.
7151 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7152 unsigned ShAmt = ShAmtV->getZExtValue();
7153
7154 // Get a mask for the bits shifting in.
7155 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00007156 Value* SrcIOp0 = SrcI->getOperand(0);
7157 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007158 if (ShAmt >= DestBitWidth) // All zeros.
7159 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7160
7161 // Okay, we can shrink this. Truncate the input, then return a new
7162 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00007163 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7164 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7165 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007166 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00007167 }
Chris Lattnerc209b582006-12-05 01:26:29 +00007168 } else { // This is a variable shr.
7169
7170 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7171 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7172 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00007173 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00007174 Value *One = ConstantInt::get(SrcI->getType(), 1);
7175
Reid Spencer2341c222007-02-02 02:16:23 +00007176 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007177 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00007178 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00007179 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7180 SrcI->getOperand(0),
7181 "tmp"), CI);
7182 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00007183 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00007184 }
Chris Lattnerd747f012006-11-29 07:04:07 +00007185 }
7186 break;
7187 }
7188 }
7189
7190 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007191}
7192
7193Instruction *InstCombiner::visitZExt(CastInst &CI) {
7194 // If one of the common conversion will work ..
7195 if (Instruction *Result = commonIntCastTransforms(CI))
7196 return Result;
7197
7198 Value *Src = CI.getOperand(0);
7199
7200 // If this is a cast of a cast
7201 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007202 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7203 // types and if the sizes are just right we can convert this into a logical
7204 // 'and' which will be much cheaper than the pair of casts.
7205 if (isa<TruncInst>(CSrc)) {
7206 // Get the sizes of the types involved
7207 Value *A = CSrc->getOperand(0);
7208 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7209 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7210 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7211 // If we're actually extending zero bits and the trunc is a no-op
7212 if (MidSize < DstSize && SrcSize == DstSize) {
7213 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00007214 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007215 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
7216 Instruction *And =
7217 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7218 // Unfortunately, if the type changed, we need to cast it back.
7219 if (And->getType() != CI.getType()) {
7220 And->setName(CSrc->getName()+".mask");
7221 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007222 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007223 }
7224 return And;
7225 }
7226 }
7227 }
7228
7229 return 0;
7230}
7231
7232Instruction *InstCombiner::visitSExt(CastInst &CI) {
7233 return commonIntCastTransforms(CI);
7234}
7235
7236Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7237 return commonCastTransforms(CI);
7238}
7239
7240Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7241 return commonCastTransforms(CI);
7242}
7243
7244Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007245 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007246}
7247
7248Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007249 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007250}
7251
7252Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7253 return commonCastTransforms(CI);
7254}
7255
7256Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7257 return commonCastTransforms(CI);
7258}
7259
7260Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007261 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007262}
7263
7264Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7265 return commonCastTransforms(CI);
7266}
7267
7268Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7269
7270 // If the operands are integer typed then apply the integer transforms,
7271 // otherwise just apply the common ones.
7272 Value *Src = CI.getOperand(0);
7273 const Type *SrcTy = Src->getType();
7274 const Type *DestTy = CI.getType();
7275
Chris Lattner03c49532007-01-15 02:27:26 +00007276 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007277 if (Instruction *Result = commonIntCastTransforms(CI))
7278 return Result;
7279 } else {
7280 if (Instruction *Result = commonCastTransforms(CI))
7281 return Result;
7282 }
7283
7284
7285 // Get rid of casts from one type to the same type. These are useless and can
7286 // be replaced by the operand.
7287 if (DestTy == Src->getType())
7288 return ReplaceInstUsesWith(CI, Src);
7289
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007290 // If the source and destination are pointers, and this cast is equivalent to
7291 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
7292 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007293 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7294 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7295 const Type *DstElTy = DstPTy->getElementType();
7296 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007297
Reid Spencerc635f472006-12-31 05:48:39 +00007298 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007299 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007300 while (SrcElTy != DstElTy &&
7301 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7302 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7303 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007304 ++NumZeros;
7305 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007306
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007307 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007308 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00007309 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7310 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007311 }
7312 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007313 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00007314
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007315 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7316 if (SVI->hasOneUse()) {
7317 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7318 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007319 if (isa<VectorType>(DestTy) &&
7320 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007321 SVI->getType()->getNumElements()) {
7322 CastInst *Tmp;
7323 // If either of the operands is a cast from CI.getType(), then
7324 // evaluating the shuffle in the casted destination's type will allow
7325 // us to eliminate at least one cast.
7326 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7327 Tmp->getOperand(0)->getType() == DestTy) ||
7328 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7329 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007330 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7331 SVI->getOperand(0), DestTy, &CI);
7332 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7333 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007334 // Return a new shuffle vector. Use the same element ID's, as we
7335 // know the vector types match #elts.
7336 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00007337 }
7338 }
7339 }
7340 }
Chris Lattner260ab202002-04-18 17:39:14 +00007341 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00007342}
7343
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007344/// GetSelectFoldableOperands - We want to turn code that looks like this:
7345/// %C = or %A, %B
7346/// %D = select %cond, %C, %A
7347/// into:
7348/// %C = select %cond, %B, 0
7349/// %D = or %A, %C
7350///
7351/// Assuming that the specified instruction is an operand to the select, return
7352/// a bitmask indicating which operands of this instruction are foldable if they
7353/// equal the other incoming value of the select.
7354///
7355static unsigned GetSelectFoldableOperands(Instruction *I) {
7356 switch (I->getOpcode()) {
7357 case Instruction::Add:
7358 case Instruction::Mul:
7359 case Instruction::And:
7360 case Instruction::Or:
7361 case Instruction::Xor:
7362 return 3; // Can fold through either operand.
7363 case Instruction::Sub: // Can only fold on the amount subtracted.
7364 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00007365 case Instruction::LShr:
7366 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00007367 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007368 default:
7369 return 0; // Cannot fold
7370 }
7371}
7372
7373/// GetSelectFoldableConstant - For the same transformation as the previous
7374/// function, return the identity constant that goes into the select.
7375static Constant *GetSelectFoldableConstant(Instruction *I) {
7376 switch (I->getOpcode()) {
7377 default: assert(0 && "This cannot happen!"); abort();
7378 case Instruction::Add:
7379 case Instruction::Sub:
7380 case Instruction::Or:
7381 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007382 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00007383 case Instruction::LShr:
7384 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00007385 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007386 case Instruction::And:
7387 return ConstantInt::getAllOnesValue(I->getType());
7388 case Instruction::Mul:
7389 return ConstantInt::get(I->getType(), 1);
7390 }
7391}
7392
Chris Lattner411336f2005-01-19 21:50:18 +00007393/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7394/// have the same opcode and only one use each. Try to simplify this.
7395Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7396 Instruction *FI) {
7397 if (TI->getNumOperands() == 1) {
7398 // If this is a non-volatile load or a cast from the same type,
7399 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007400 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00007401 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7402 return 0;
7403 } else {
7404 return 0; // unknown unary op.
7405 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007406
Chris Lattner411336f2005-01-19 21:50:18 +00007407 // Fold this by inserting a select from the input values.
7408 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7409 FI->getOperand(0), SI.getName()+".v");
7410 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007411 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7412 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00007413 }
7414
Reid Spencer2341c222007-02-02 02:16:23 +00007415 // Only handle binary operators here.
7416 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00007417 return 0;
7418
7419 // Figure out if the operations have any operands in common.
7420 Value *MatchOp, *OtherOpT, *OtherOpF;
7421 bool MatchIsOpZero;
7422 if (TI->getOperand(0) == FI->getOperand(0)) {
7423 MatchOp = TI->getOperand(0);
7424 OtherOpT = TI->getOperand(1);
7425 OtherOpF = FI->getOperand(1);
7426 MatchIsOpZero = true;
7427 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7428 MatchOp = TI->getOperand(1);
7429 OtherOpT = TI->getOperand(0);
7430 OtherOpF = FI->getOperand(0);
7431 MatchIsOpZero = false;
7432 } else if (!TI->isCommutative()) {
7433 return 0;
7434 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7435 MatchOp = TI->getOperand(0);
7436 OtherOpT = TI->getOperand(1);
7437 OtherOpF = FI->getOperand(0);
7438 MatchIsOpZero = true;
7439 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7440 MatchOp = TI->getOperand(1);
7441 OtherOpT = TI->getOperand(0);
7442 OtherOpF = FI->getOperand(1);
7443 MatchIsOpZero = true;
7444 } else {
7445 return 0;
7446 }
7447
7448 // If we reach here, they do have operations in common.
7449 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7450 OtherOpF, SI.getName()+".v");
7451 InsertNewInstBefore(NewSI, SI);
7452
7453 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7454 if (MatchIsOpZero)
7455 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7456 else
7457 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00007458 }
Reid Spencer2f34b982007-02-02 14:41:37 +00007459 assert(0 && "Shouldn't get here");
7460 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00007461}
7462
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007463Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00007464 Value *CondVal = SI.getCondition();
7465 Value *TrueVal = SI.getTrueValue();
7466 Value *FalseVal = SI.getFalseValue();
7467
7468 // select true, X, Y -> X
7469 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00007470 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00007471 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00007472
7473 // select C, X, X -> X
7474 if (TrueVal == FalseVal)
7475 return ReplaceInstUsesWith(SI, TrueVal);
7476
Chris Lattner81a7a232004-10-16 18:11:37 +00007477 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7478 return ReplaceInstUsesWith(SI, FalseVal);
7479 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7480 return ReplaceInstUsesWith(SI, TrueVal);
7481 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7482 if (isa<Constant>(TrueVal))
7483 return ReplaceInstUsesWith(SI, TrueVal);
7484 else
7485 return ReplaceInstUsesWith(SI, FalseVal);
7486 }
7487
Reid Spencer542964f2007-01-11 18:21:29 +00007488 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007489 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007490 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007491 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007492 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007493 } else {
7494 // Change: A = select B, false, C --> A = and !B, C
7495 Value *NotCond =
7496 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7497 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007498 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007499 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007500 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007501 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007502 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007503 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007504 } else {
7505 // Change: A = select B, C, true --> A = or !B, C
7506 Value *NotCond =
7507 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7508 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007509 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007510 }
7511 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00007512 }
Chris Lattner1c631e82004-04-08 04:43:23 +00007513
Chris Lattner183b3362004-04-09 19:05:30 +00007514 // Selecting between two integer constants?
7515 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7516 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7517 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00007518 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007519 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00007520 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00007521 // select C, 0, 1 -> cast !C to int
7522 Value *NotCond =
7523 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00007524 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007525 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00007526 }
Chris Lattner35167c32004-06-09 07:59:58 +00007527
Reid Spencer266e42b2006-12-23 06:05:41 +00007528 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007529
Reid Spencer266e42b2006-12-23 06:05:41 +00007530 // (x <s 0) ? -1 : 0 -> ashr x, 31
7531 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00007532 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7533 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7534 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00007535 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00007536 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007537 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00007538 else {
7539 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00007540 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007541 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00007542 }
7543
7544 if (CanXForm) {
7545 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007546 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00007547 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00007548 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00007549 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7550 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7551 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00007552 InsertNewInstBefore(SRA, SI);
7553
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007554 // Finally, convert to the type of the select RHS. We figure out
7555 // if this requires a SExt, Trunc or BitCast based on the sizes.
7556 Instruction::CastOps opc = Instruction::BitCast;
7557 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7558 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
7559 if (SRASize < SISize)
7560 opc = Instruction::SExt;
7561 else if (SRASize > SISize)
7562 opc = Instruction::Trunc;
7563 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007564 }
7565 }
7566
7567
7568 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00007569 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007570 // non-constant value, eliminate this whole mess. This corresponds to
7571 // cases like this: ((X & 27) ? 27 : 0)
7572 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007573 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007574 cast<Constant>(IC->getOperand(1))->isNullValue())
7575 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7576 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007577 isa<ConstantInt>(ICA->getOperand(1)) &&
7578 (ICA->getOperand(1) == TrueValC ||
7579 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007580 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7581 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007582 // know whether we have a icmp_ne or icmp_eq and whether the
7583 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00007584 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007585 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007586 Value *V = ICA;
7587 if (ShouldNotVal)
7588 V = InsertNewInstBefore(BinaryOperator::create(
7589 Instruction::Xor, V, ICA->getOperand(1)), SI);
7590 return ReplaceInstUsesWith(SI, V);
7591 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007592 }
Chris Lattner533bc492004-03-30 19:37:13 +00007593 }
Chris Lattner623fba12004-04-10 22:21:27 +00007594
7595 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007596 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7597 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007598 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007599 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007600 return ReplaceInstUsesWith(SI, FalseVal);
7601 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007602 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007603 return ReplaceInstUsesWith(SI, TrueVal);
7604 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7605
Reid Spencer266e42b2006-12-23 06:05:41 +00007606 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007607 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007608 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007609 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007610 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007611 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7612 return ReplaceInstUsesWith(SI, TrueVal);
7613 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7614 }
7615 }
7616
7617 // See if we are selecting two values based on a comparison of the two values.
7618 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7619 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7620 // Transform (X == Y) ? X : Y -> Y
7621 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7622 return ReplaceInstUsesWith(SI, FalseVal);
7623 // Transform (X != Y) ? X : Y -> X
7624 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7625 return ReplaceInstUsesWith(SI, TrueVal);
7626 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7627
7628 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7629 // Transform (X == Y) ? Y : X -> X
7630 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7631 return ReplaceInstUsesWith(SI, FalseVal);
7632 // Transform (X != Y) ? Y : X -> Y
7633 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007634 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007635 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7636 }
7637 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007638
Chris Lattnera04c9042005-01-13 22:52:24 +00007639 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7640 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7641 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007642 Instruction *AddOp = 0, *SubOp = 0;
7643
Chris Lattner411336f2005-01-19 21:50:18 +00007644 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7645 if (TI->getOpcode() == FI->getOpcode())
7646 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7647 return IV;
7648
7649 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7650 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007651 if (TI->getOpcode() == Instruction::Sub &&
7652 FI->getOpcode() == Instruction::Add) {
7653 AddOp = FI; SubOp = TI;
7654 } else if (FI->getOpcode() == Instruction::Sub &&
7655 TI->getOpcode() == Instruction::Add) {
7656 AddOp = TI; SubOp = FI;
7657 }
7658
7659 if (AddOp) {
7660 Value *OtherAddOp = 0;
7661 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7662 OtherAddOp = AddOp->getOperand(1);
7663 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7664 OtherAddOp = AddOp->getOperand(0);
7665 }
7666
7667 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007668 // So at this point we know we have (Y -> OtherAddOp):
7669 // select C, (add X, Y), (sub X, Z)
7670 Value *NegVal; // Compute -Z
7671 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7672 NegVal = ConstantExpr::getNeg(C);
7673 } else {
7674 NegVal = InsertNewInstBefore(
7675 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007676 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007677
7678 Value *NewTrueOp = OtherAddOp;
7679 Value *NewFalseOp = NegVal;
7680 if (AddOp != TI)
7681 std::swap(NewTrueOp, NewFalseOp);
7682 Instruction *NewSel =
7683 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7684
7685 NewSel = InsertNewInstBefore(NewSel, SI);
7686 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007687 }
7688 }
7689 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007690
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007691 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007692 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007693 // See the comment above GetSelectFoldableOperands for a description of the
7694 // transformation we are doing here.
7695 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7696 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7697 !isa<Constant>(FalseVal))
7698 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7699 unsigned OpToFold = 0;
7700 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7701 OpToFold = 1;
7702 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7703 OpToFold = 2;
7704 }
7705
7706 if (OpToFold) {
7707 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007708 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007709 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007710 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007711 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7713 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007714 else {
7715 assert(0 && "Unknown instruction!!");
7716 }
7717 }
7718 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007719
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007720 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7721 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7722 !isa<Constant>(TrueVal))
7723 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7724 unsigned OpToFold = 0;
7725 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7726 OpToFold = 1;
7727 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7728 OpToFold = 2;
7729 }
7730
7731 if (OpToFold) {
7732 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007733 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007734 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007735 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007736 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007737 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7738 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007739 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007740 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007741 }
7742 }
7743 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007744
7745 if (BinaryOperator::isNot(CondVal)) {
7746 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7747 SI.setOperand(1, FalseVal);
7748 SI.setOperand(2, TrueVal);
7749 return &SI;
7750 }
7751
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007752 return 0;
7753}
7754
Chris Lattner82f2ef22006-03-06 20:18:44 +00007755/// GetKnownAlignment - If the specified pointer has an alignment that we can
7756/// determine, return it, otherwise return 0.
7757static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7758 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7759 unsigned Align = GV->getAlignment();
7760 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007761 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007762 return Align;
7763 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7764 unsigned Align = AI->getAlignment();
7765 if (Align == 0 && TD) {
7766 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007767 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007768 else if (isa<MallocInst>(AI)) {
7769 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007770 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007771 Align =
7772 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007773 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007774 Align =
7775 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007776 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007777 }
7778 }
7779 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007780 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007781 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007782 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007783 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007784 if (isa<PointerType>(CI->getOperand(0)->getType()))
7785 return GetKnownAlignment(CI->getOperand(0), TD);
7786 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007787 } else if (isa<GetElementPtrInst>(V) ||
7788 (isa<ConstantExpr>(V) &&
7789 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7790 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007791 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7792 if (BaseAlignment == 0) return 0;
7793
7794 // If all indexes are zero, it is just the alignment of the base pointer.
7795 bool AllZeroOperands = true;
7796 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7797 if (!isa<Constant>(GEPI->getOperand(i)) ||
7798 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7799 AllZeroOperands = false;
7800 break;
7801 }
7802 if (AllZeroOperands)
7803 return BaseAlignment;
7804
7805 // Otherwise, if the base alignment is >= the alignment we expect for the
7806 // base pointer type, then we know that the resultant pointer is aligned at
7807 // least as much as its type requires.
7808 if (!TD) return 0;
7809
7810 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007811 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007812 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007813 <= BaseAlignment) {
7814 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007815 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007816 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007817 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007818 return 0;
7819 }
7820 return 0;
7821}
7822
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007823
Chris Lattnerc66b2232006-01-13 20:11:04 +00007824/// visitCallInst - CallInst simplification. This mostly only handles folding
7825/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7826/// the heavy lifting.
7827///
Chris Lattner970c33a2003-06-19 17:00:31 +00007828Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007829 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7830 if (!II) return visitCallSite(&CI);
7831
Chris Lattner51ea1272004-02-28 05:22:00 +00007832 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7833 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007834 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007835 bool Changed = false;
7836
7837 // memmove/cpy/set of zero bytes is a noop.
7838 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7839 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7840
Chris Lattner00648e12004-10-12 04:52:52 +00007841 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007842 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007843 // Replace the instruction with just byte operations. We would
7844 // transform other cases to loads/stores, but we don't know if
7845 // alignment is sufficient.
7846 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007847 }
7848
Chris Lattner00648e12004-10-12 04:52:52 +00007849 // If we have a memmove and the source operation is a constant global,
7850 // then the source and dest pointers can't alias, so we can change this
7851 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007852 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007853 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7854 if (GVSrc->isConstant()) {
7855 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007856 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007857 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007858 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007859 Name = "llvm.memcpy.i32";
7860 else
7861 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007862 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007863 CI.getCalledFunction()->getFunctionType());
7864 CI.setOperand(0, MemCpy);
7865 Changed = true;
7866 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007867 }
Chris Lattner00648e12004-10-12 04:52:52 +00007868
Chris Lattner82f2ef22006-03-06 20:18:44 +00007869 // If we can determine a pointer alignment that is bigger than currently
7870 // set, update the alignment.
7871 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7872 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7873 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7874 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007875 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007876 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007877 Changed = true;
7878 }
7879 } else if (isa<MemSetInst>(MI)) {
7880 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007881 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007882 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007883 Changed = true;
7884 }
7885 }
7886
Chris Lattnerc66b2232006-01-13 20:11:04 +00007887 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007888 } else {
7889 switch (II->getIntrinsicID()) {
7890 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007891 case Intrinsic::ppc_altivec_lvx:
7892 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007893 case Intrinsic::x86_sse_loadu_ps:
7894 case Intrinsic::x86_sse2_loadu_pd:
7895 case Intrinsic::x86_sse2_loadu_dq:
7896 // Turn PPC lvx -> load if the pointer is known aligned.
7897 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007898 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007899 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007900 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007901 return new LoadInst(Ptr);
7902 }
7903 break;
7904 case Intrinsic::ppc_altivec_stvx:
7905 case Intrinsic::ppc_altivec_stvxl:
7906 // Turn stvx -> store if the pointer is known aligned.
7907 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007908 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007909 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7910 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007911 return new StoreInst(II->getOperand(1), Ptr);
7912 }
7913 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007914 case Intrinsic::x86_sse_storeu_ps:
7915 case Intrinsic::x86_sse2_storeu_pd:
7916 case Intrinsic::x86_sse2_storeu_dq:
7917 case Intrinsic::x86_sse2_storel_dq:
7918 // Turn X86 storeu -> store if the pointer is known aligned.
7919 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7920 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007921 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7922 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007923 return new StoreInst(II->getOperand(2), Ptr);
7924 }
7925 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007926
7927 case Intrinsic::x86_sse_cvttss2si: {
7928 // These intrinsics only demands the 0th element of its input vector. If
7929 // we can simplify the input based on that, do so now.
7930 uint64_t UndefElts;
7931 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7932 UndefElts)) {
7933 II->setOperand(1, V);
7934 return II;
7935 }
7936 break;
7937 }
7938
Chris Lattnere79d2492006-04-06 19:19:17 +00007939 case Intrinsic::ppc_altivec_vperm:
7940 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007941 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007942 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7943
7944 // Check that all of the elements are integer constants or undefs.
7945 bool AllEltsOk = true;
7946 for (unsigned i = 0; i != 16; ++i) {
7947 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7948 !isa<UndefValue>(Mask->getOperand(i))) {
7949 AllEltsOk = false;
7950 break;
7951 }
7952 }
7953
7954 if (AllEltsOk) {
7955 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007956 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7957 II->getOperand(1), Mask->getType(), CI);
7958 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7959 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007960 Value *Result = UndefValue::get(Op0->getType());
7961
7962 // Only extract each element once.
7963 Value *ExtractedElts[32];
7964 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7965
7966 for (unsigned i = 0; i != 16; ++i) {
7967 if (isa<UndefValue>(Mask->getOperand(i)))
7968 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007969 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007970 Idx &= 31; // Match the hardware behavior.
7971
7972 if (ExtractedElts[Idx] == 0) {
7973 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007974 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007975 InsertNewInstBefore(Elt, CI);
7976 ExtractedElts[Idx] = Elt;
7977 }
7978
7979 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007980 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007981 InsertNewInstBefore(cast<Instruction>(Result), CI);
7982 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007983 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007984 }
7985 }
7986 break;
7987
Chris Lattner503221f2006-01-13 21:28:09 +00007988 case Intrinsic::stackrestore: {
7989 // If the save is right next to the restore, remove the restore. This can
7990 // happen when variable allocas are DCE'd.
7991 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7992 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7993 BasicBlock::iterator BI = SS;
7994 if (&*++BI == II)
7995 return EraseInstFromFunction(CI);
7996 }
7997 }
7998
7999 // If the stack restore is in a return/unwind block and if there are no
8000 // allocas or calls between the restore and the return, nuke the restore.
8001 TerminatorInst *TI = II->getParent()->getTerminator();
8002 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8003 BasicBlock::iterator BI = II;
8004 bool CannotRemove = false;
8005 for (++BI; &*BI != TI; ++BI) {
8006 if (isa<AllocaInst>(BI) ||
8007 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8008 CannotRemove = true;
8009 break;
8010 }
8011 }
8012 if (!CannotRemove)
8013 return EraseInstFromFunction(CI);
8014 }
8015 break;
8016 }
8017 }
Chris Lattner00648e12004-10-12 04:52:52 +00008018 }
8019
Chris Lattnerc66b2232006-01-13 20:11:04 +00008020 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008021}
8022
8023// InvokeInst simplification
8024//
8025Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00008026 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008027}
8028
Chris Lattneraec3d942003-10-07 22:32:43 +00008029// visitCallSite - Improvements for call and invoke instructions.
8030//
8031Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008032 bool Changed = false;
8033
8034 // If the callee is a constexpr cast of a function, attempt to move the cast
8035 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00008036 if (transformConstExprCastCall(CS)) return 0;
8037
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008038 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00008039
Chris Lattner61d9d812005-05-13 07:09:09 +00008040 if (Function *CalleeF = dyn_cast<Function>(Callee))
8041 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8042 Instruction *OldCall = CS.getInstruction();
8043 // If the call and callee calling conventions don't match, this call must
8044 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008045 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008046 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00008047 if (!OldCall->use_empty())
8048 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8049 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8050 return EraseInstFromFunction(*OldCall);
8051 return 0;
8052 }
8053
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008054 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8055 // This instruction is not reachable, just remove it. We insert a store to
8056 // undef so that we know that this code is not reachable, despite the fact
8057 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008058 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008059 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008060 CS.getInstruction());
8061
8062 if (!CS.getInstruction()->use_empty())
8063 CS.getInstruction()->
8064 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8065
8066 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8067 // Don't break the CFG, insert a dummy cond branch.
8068 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00008069 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00008070 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008071 return EraseInstFromFunction(*CS.getInstruction());
8072 }
Chris Lattner81a7a232004-10-16 18:11:37 +00008073
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008074 const PointerType *PTy = cast<PointerType>(Callee->getType());
8075 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8076 if (FTy->isVarArg()) {
8077 // See if we can optimize any arguments passed through the varargs area of
8078 // the call.
8079 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8080 E = CS.arg_end(); I != E; ++I)
8081 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8082 // If this cast does not effect the value passed through the varargs
8083 // area, we can eliminate the use of the cast.
8084 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008085 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008086 *I = Op;
8087 Changed = true;
8088 }
8089 }
8090 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008091
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008092 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00008093}
8094
Chris Lattner970c33a2003-06-19 17:00:31 +00008095// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8096// attempt to move the cast to the arguments of the call/invoke.
8097//
8098bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8099 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8100 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008101 if (CE->getOpcode() != Instruction::BitCast ||
8102 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00008103 return false;
Reid Spencer87436872004-07-18 00:38:32 +00008104 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00008105 Instruction *Caller = CS.getInstruction();
8106
8107 // Okay, this is a cast from a function to a different type. Unless doing so
8108 // would cause a type conversion of one of our arguments, change this call to
8109 // be a direct call with arguments casted to the appropriate types.
8110 //
8111 const FunctionType *FT = Callee->getFunctionType();
8112 const Type *OldRetTy = Caller->getType();
8113
Chris Lattner1f7942f2004-01-14 06:06:08 +00008114 // Check to see if we are changing the return type...
8115 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00008116 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00008117 OldRetTy != FT->getReturnType() &&
8118 // Conversion is ok if changing from pointer to int of same size.
8119 !(isa<PointerType>(FT->getReturnType()) &&
8120 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00008121 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00008122
8123 // If the callsite is an invoke instruction, and the return value is used by
8124 // a PHI node in a successor, we cannot change the return type of the call
8125 // because there is no place to put the cast instruction (without breaking
8126 // the critical edge). Bail out in this case.
8127 if (!Caller->use_empty())
8128 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8129 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8130 UI != E; ++UI)
8131 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8132 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008133 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00008134 return false;
8135 }
Chris Lattner970c33a2003-06-19 17:00:31 +00008136
8137 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8138 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008139
Chris Lattner970c33a2003-06-19 17:00:31 +00008140 CallSite::arg_iterator AI = CS.arg_begin();
8141 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8142 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008143 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008144 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008145 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00008146 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00008147 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00008148 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00008149 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8150 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8151 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00008152 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00008153 }
8154
8155 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00008156 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00008157 return false; // Do not delete arguments unless we have a function body...
8158
8159 // Okay, we decided that this is a safe thing to do: go ahead and start
8160 // inserting cast instructions as necessary...
8161 std::vector<Value*> Args;
8162 Args.reserve(NumActualArgs);
8163
8164 AI = CS.arg_begin();
8165 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8166 const Type *ParamTy = FT->getParamType(i);
8167 if ((*AI)->getType() == ParamTy) {
8168 Args.push_back(*AI);
8169 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00008170 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00008171 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008172 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008173 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00008174 }
8175 }
8176
8177 // If the function takes more arguments than the call was taking, add them
8178 // now...
8179 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8180 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8181
8182 // If we are removing arguments to the function, emit an obnoxious warning...
8183 if (FT->getNumParams() < NumActualArgs)
8184 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00008185 cerr << "WARNING: While resolving call to function '"
8186 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00008187 } else {
8188 // Add all of the arguments in their promoted form to the arg list...
8189 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8190 const Type *PTy = getPromotedType((*AI)->getType());
8191 if (PTy != (*AI)->getType()) {
8192 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00008193 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8194 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008195 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00008196 InsertNewInstBefore(Cast, *Caller);
8197 Args.push_back(Cast);
8198 } else {
8199 Args.push_back(*AI);
8200 }
8201 }
8202 }
8203
8204 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00008205 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00008206
8207 Instruction *NC;
8208 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008209 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00008210 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00008211 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00008212 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00008213 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00008214 if (cast<CallInst>(Caller)->isTailCall())
8215 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00008216 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00008217 }
8218
Chris Lattner6e0123b2007-02-11 01:23:03 +00008219 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00008220 Value *NV = NC;
8221 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8222 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00008223 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00008224 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8225 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008226 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00008227
8228 // If this is an invoke instruction, we should insert it after the first
8229 // non-phi, instruction in the normal successor block.
8230 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8231 BasicBlock::iterator I = II->getNormalDest()->begin();
8232 while (isa<PHINode>(I)) ++I;
8233 InsertNewInstBefore(NC, *I);
8234 } else {
8235 // Otherwise, it's a call, just insert cast right after the call instr
8236 InsertNewInstBefore(NC, *Caller);
8237 }
Chris Lattner51ea1272004-02-28 05:22:00 +00008238 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00008239 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00008240 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00008241 }
8242 }
8243
8244 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8245 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00008246 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008247 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00008248 return true;
8249}
8250
Chris Lattnercadac0c2006-11-01 04:51:18 +00008251/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8252/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8253/// and a single binop.
8254Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8255 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00008256 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8257 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008258 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00008259 Value *LHSVal = FirstInst->getOperand(0);
8260 Value *RHSVal = FirstInst->getOperand(1);
8261
8262 const Type *LHSType = LHSVal->getType();
8263 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00008264
8265 // Scan to see if all operands are the same opcode, all have one use, and all
8266 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00008267 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00008268 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00008269 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00008270 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00008271 // types or GEP's with different index types.
8272 I->getOperand(0)->getType() != LHSType ||
8273 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00008274 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00008275
8276 // If they are CmpInst instructions, check their predicates
8277 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8278 if (cast<CmpInst>(I)->getPredicate() !=
8279 cast<CmpInst>(FirstInst)->getPredicate())
8280 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00008281
8282 // Keep track of which operand needs a phi node.
8283 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8284 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00008285 }
8286
Chris Lattner4f218d52006-11-08 19:42:28 +00008287 // Otherwise, this is safe to transform, determine if it is profitable.
8288
8289 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8290 // Indexes are often folded into load/store instructions, so we don't want to
8291 // hide them behind a phi.
8292 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8293 return 0;
8294
Chris Lattnercadac0c2006-11-01 04:51:18 +00008295 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00008296 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00008297 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00008298 if (LHSVal == 0) {
8299 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8300 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8301 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00008302 InsertNewInstBefore(NewLHS, PN);
8303 LHSVal = NewLHS;
8304 }
Chris Lattnercd62f112006-11-08 19:29:23 +00008305
8306 if (RHSVal == 0) {
8307 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8308 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8309 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00008310 InsertNewInstBefore(NewRHS, PN);
8311 RHSVal = NewRHS;
8312 }
8313
Chris Lattnercd62f112006-11-08 19:29:23 +00008314 // Add all operands to the new PHIs.
8315 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8316 if (NewLHS) {
8317 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8318 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8319 }
8320 if (NewRHS) {
8321 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8322 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8323 }
8324 }
8325
Chris Lattnercadac0c2006-11-01 04:51:18 +00008326 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00008327 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00008328 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8329 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8330 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00008331 else {
8332 assert(isa<GetElementPtrInst>(FirstInst));
8333 return new GetElementPtrInst(LHSVal, RHSVal);
8334 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00008335}
8336
Chris Lattner14f82c72006-11-01 07:13:54 +00008337/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8338/// of the block that defines it. This means that it must be obvious the value
8339/// of the load is not changed from the point of the load to the end of the
8340/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00008341///
8342/// Finally, it is safe, but not profitable, to sink a load targetting a
8343/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8344/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00008345static bool isSafeToSinkLoad(LoadInst *L) {
8346 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8347
8348 for (++BBI; BBI != E; ++BBI)
8349 if (BBI->mayWriteToMemory())
8350 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00008351
8352 // Check for non-address taken alloca. If not address-taken already, it isn't
8353 // profitable to do this xform.
8354 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8355 bool isAddressTaken = false;
8356 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8357 UI != E; ++UI) {
8358 if (isa<LoadInst>(UI)) continue;
8359 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8360 // If storing TO the alloca, then the address isn't taken.
8361 if (SI->getOperand(1) == AI) continue;
8362 }
8363 isAddressTaken = true;
8364 break;
8365 }
8366
8367 if (!isAddressTaken)
8368 return false;
8369 }
8370
Chris Lattner14f82c72006-11-01 07:13:54 +00008371 return true;
8372}
8373
Chris Lattner970c33a2003-06-19 17:00:31 +00008374
Chris Lattner7515cab2004-11-14 19:13:23 +00008375// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8376// operator and they all are only used by the PHI, PHI together their
8377// inputs, and do the operation once, to the result of the PHI.
8378Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8379 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8380
8381 // Scan the instruction, looking for input operations that can be folded away.
8382 // If all input operands to the phi are the same instruction (e.g. a cast from
8383 // the same type or "+42") we can pull the operation through the PHI, reducing
8384 // code size and simplifying code.
8385 Constant *ConstantOp = 0;
8386 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00008387 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00008388 if (isa<CastInst>(FirstInst)) {
8389 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00008390 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008391 // Can fold binop, compare or shift here if the RHS is a constant,
8392 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00008393 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008394 if (ConstantOp == 0)
8395 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00008396 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8397 isVolatile = LI->isVolatile();
8398 // We can't sink the load if the loaded value could be modified between the
8399 // load and the PHI.
8400 if (LI->getParent() != PN.getIncomingBlock(0) ||
8401 !isSafeToSinkLoad(LI))
8402 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00008403 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00008404 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00008405 return FoldPHIArgBinOpIntoPHI(PN);
8406 // Can't handle general GEPs yet.
8407 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008408 } else {
8409 return 0; // Cannot fold this operation.
8410 }
8411
8412 // Check to see if all arguments are the same operation.
8413 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8414 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8415 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00008416 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00008417 return 0;
8418 if (CastSrcTy) {
8419 if (I->getOperand(0)->getType() != CastSrcTy)
8420 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00008421 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008422 // We can't sink the load if the loaded value could be modified between
8423 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00008424 if (LI->isVolatile() != isVolatile ||
8425 LI->getParent() != PN.getIncomingBlock(i) ||
8426 !isSafeToSinkLoad(LI))
8427 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008428 } else if (I->getOperand(1) != ConstantOp) {
8429 return 0;
8430 }
8431 }
8432
8433 // Okay, they are all the same operation. Create a new PHI node of the
8434 // correct type, and PHI together all of the LHS's of the instructions.
8435 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8436 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00008437 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00008438
8439 Value *InVal = FirstInst->getOperand(0);
8440 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00008441
8442 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00008443 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8444 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8445 if (NewInVal != InVal)
8446 InVal = 0;
8447 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8448 }
8449
8450 Value *PhiVal;
8451 if (InVal) {
8452 // The new PHI unions all of the same values together. This is really
8453 // common, so we handle it intelligently here for compile-time speed.
8454 PhiVal = InVal;
8455 delete NewPN;
8456 } else {
8457 InsertNewInstBefore(NewPN, PN);
8458 PhiVal = NewPN;
8459 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008460
Chris Lattner7515cab2004-11-14 19:13:23 +00008461 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008462 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8463 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00008464 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00008465 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00008466 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00008467 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00008468 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8469 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8470 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00008471 else
Reid Spencer2341c222007-02-02 02:16:23 +00008472 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00008473 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008474}
Chris Lattner48a44f72002-05-02 17:06:02 +00008475
Chris Lattner71536432005-01-17 05:10:15 +00008476/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8477/// that is dead.
8478static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8479 if (PN->use_empty()) return true;
8480 if (!PN->hasOneUse()) return false;
8481
8482 // Remember this node, and if we find the cycle, return.
8483 if (!PotentiallyDeadPHIs.insert(PN).second)
8484 return true;
8485
8486 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8487 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008488
Chris Lattner71536432005-01-17 05:10:15 +00008489 return false;
8490}
8491
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008492// PHINode simplification
8493//
Chris Lattner113f4f42002-06-25 16:13:24 +00008494Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00008495 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00008496 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00008497
Owen Andersonae8aa642006-07-10 22:03:18 +00008498 if (Value *V = PN.hasConstantValue())
8499 return ReplaceInstUsesWith(PN, V);
8500
Owen Andersonae8aa642006-07-10 22:03:18 +00008501 // If all PHI operands are the same operation, pull them through the PHI,
8502 // reducing code size.
8503 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8504 PN.getIncomingValue(0)->hasOneUse())
8505 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8506 return Result;
8507
8508 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8509 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8510 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008511 if (PN.hasOneUse()) {
8512 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8513 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00008514 std::set<PHINode*> PotentiallyDeadPHIs;
8515 PotentiallyDeadPHIs.insert(&PN);
8516 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8517 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8518 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008519
8520 // If this phi has a single use, and if that use just computes a value for
8521 // the next iteration of a loop, delete the phi. This occurs with unused
8522 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8523 // common case here is good because the only other things that catch this
8524 // are induction variable analysis (sometimes) and ADCE, which is only run
8525 // late.
8526 if (PHIUser->hasOneUse() &&
8527 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8528 PHIUser->use_back() == &PN) {
8529 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8530 }
8531 }
Owen Andersonae8aa642006-07-10 22:03:18 +00008532
Chris Lattner91daeb52003-12-19 05:58:40 +00008533 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008534}
8535
Reid Spencer13bc5d72006-12-12 09:18:51 +00008536static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8537 Instruction *InsertPoint,
8538 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00008539 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8540 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008541 // We must cast correctly to the pointer type. Ensure that we
8542 // sign extend the integer value if it is smaller as this is
8543 // used for address computation.
8544 Instruction::CastOps opcode =
8545 (VTySize < PtrSize ? Instruction::SExt :
8546 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8547 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00008548}
8549
Chris Lattner48a44f72002-05-02 17:06:02 +00008550
Chris Lattner113f4f42002-06-25 16:13:24 +00008551Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008552 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00008553 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00008554 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008555 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00008556 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008557
Chris Lattner81a7a232004-10-16 18:11:37 +00008558 if (isa<UndefValue>(GEP.getOperand(0)))
8559 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8560
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008561 bool HasZeroPointerIndex = false;
8562 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8563 HasZeroPointerIndex = C->isNullValue();
8564
8565 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008566 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008567
Chris Lattner69193f92004-04-05 01:30:19 +00008568 // Eliminate unneeded casts for indices.
8569 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00008570 gep_type_iterator GTI = gep_type_begin(GEP);
8571 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8572 if (isa<SequentialType>(*GTI)) {
8573 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008574 if (CI->getOpcode() == Instruction::ZExt ||
8575 CI->getOpcode() == Instruction::SExt) {
8576 const Type *SrcTy = CI->getOperand(0)->getType();
8577 // We can eliminate a cast from i32 to i64 iff the target
8578 // is a 32-bit pointer target.
8579 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8580 MadeChange = true;
8581 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008582 }
8583 }
8584 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008585 // If we are using a wider index than needed for this platform, shrink it
8586 // to what we need. If the incoming value needs a cast instruction,
8587 // insert it. This explicit cast can make subsequent optimizations more
8588 // obvious.
8589 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008590 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008591 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008592 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008593 MadeChange = true;
8594 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008595 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8596 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008597 GEP.setOperand(i, Op);
8598 MadeChange = true;
8599 }
Chris Lattner69193f92004-04-05 01:30:19 +00008600 }
8601 if (MadeChange) return &GEP;
8602
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008603 // Combine Indices - If the source pointer to this getelementptr instruction
8604 // is a getelementptr instruction, combine the indices of the two
8605 // getelementptr instructions into a single instruction.
8606 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008607 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008608 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008609 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008610
8611 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008612 // Note that if our source is a gep chain itself that we wait for that
8613 // chain to be resolved before we perform this transformation. This
8614 // avoids us creating a TON of code in some cases.
8615 //
8616 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8617 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8618 return 0; // Wait until our source is folded to completion.
8619
Chris Lattneraf6094f2007-02-15 22:48:32 +00008620 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008621
8622 // Find out whether the last index in the source GEP is a sequential idx.
8623 bool EndsWithSequential = false;
8624 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8625 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008626 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008627
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008628 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008629 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008630 // Replace: gep (gep %P, long B), long A, ...
8631 // With: T = long A+B; gep %P, T, ...
8632 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008633 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008634 if (SO1 == Constant::getNullValue(SO1->getType())) {
8635 Sum = GO1;
8636 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8637 Sum = SO1;
8638 } else {
8639 // If they aren't the same type, convert both to an integer of the
8640 // target's pointer size.
8641 if (SO1->getType() != GO1->getType()) {
8642 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008643 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008644 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008645 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008646 } else {
8647 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008648 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008649 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008650 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008651
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008652 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008653 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008654 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008655 } else {
8656 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008657 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8658 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008659 }
8660 }
8661 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008662 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8663 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8664 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008665 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8666 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008667 }
Chris Lattner69193f92004-04-05 01:30:19 +00008668 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008669
8670 // Recycle the GEP we already have if possible.
8671 if (SrcGEPOperands.size() == 2) {
8672 GEP.setOperand(0, SrcGEPOperands[0]);
8673 GEP.setOperand(1, Sum);
8674 return &GEP;
8675 } else {
8676 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8677 SrcGEPOperands.end()-1);
8678 Indices.push_back(Sum);
8679 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8680 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008681 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008682 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008683 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008684 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008685 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8686 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008687 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8688 }
8689
8690 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008691 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8692 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008693
Chris Lattner5f667a62004-05-07 22:09:22 +00008694 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008695 // GEP of global variable. If all of the indices for this GEP are
8696 // constants, we can promote this to a constexpr instead of an instruction.
8697
8698 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008699 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008700 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8701 for (; I != E && isa<Constant>(*I); ++I)
8702 Indices.push_back(cast<Constant>(*I));
8703
8704 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008705 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8706 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008707
8708 // Replace all uses of the GEP with the new constexpr...
8709 return ReplaceInstUsesWith(GEP, CE);
8710 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008711 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008712 if (!isa<PointerType>(X->getType())) {
8713 // Not interesting. Source pointer must be a cast from pointer.
8714 } else if (HasZeroPointerIndex) {
8715 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8716 // into : GEP [10 x ubyte]* X, long 0, ...
8717 //
8718 // This occurs when the program declares an array extern like "int X[];"
8719 //
8720 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8721 const PointerType *XTy = cast<PointerType>(X->getType());
8722 if (const ArrayType *XATy =
8723 dyn_cast<ArrayType>(XTy->getElementType()))
8724 if (const ArrayType *CATy =
8725 dyn_cast<ArrayType>(CPTy->getElementType()))
8726 if (CATy->getElementType() == XATy->getElementType()) {
8727 // At this point, we know that the cast source type is a pointer
8728 // to an array of the same type as the destination pointer
8729 // array. Because the array type is never stepped over (there
8730 // is a leading zero) we can fold the cast into this GEP.
8731 GEP.setOperand(0, X);
8732 return &GEP;
8733 }
8734 } else if (GEP.getNumOperands() == 2) {
8735 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008736 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8737 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008738 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8739 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8740 if (isa<ArrayType>(SrcElTy) &&
8741 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8742 TD->getTypeSize(ResElTy)) {
8743 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008744 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008745 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008746 // V and GEP are both pointer types --> BitCast
8747 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008748 }
Chris Lattner2a893292005-09-13 18:36:04 +00008749
8750 // Transform things like:
8751 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8752 // (where tmp = 8*tmp2) into:
8753 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8754
8755 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008756 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008757 uint64_t ArrayEltSize =
8758 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8759
8760 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8761 // allow either a mul, shift, or constant here.
8762 Value *NewIdx = 0;
8763 ConstantInt *Scale = 0;
8764 if (ArrayEltSize == 1) {
8765 NewIdx = GEP.getOperand(1);
8766 Scale = ConstantInt::get(NewIdx->getType(), 1);
8767 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008768 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008769 Scale = CI;
8770 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8771 if (Inst->getOpcode() == Instruction::Shl &&
8772 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008773 unsigned ShAmt =
8774 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008775 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008776 NewIdx = Inst->getOperand(0);
8777 } else if (Inst->getOpcode() == Instruction::Mul &&
8778 isa<ConstantInt>(Inst->getOperand(1))) {
8779 Scale = cast<ConstantInt>(Inst->getOperand(1));
8780 NewIdx = Inst->getOperand(0);
8781 }
8782 }
8783
8784 // If the index will be to exactly the right offset with the scale taken
8785 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008786 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008787 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008788 Scale = ConstantInt::get(Scale->getType(),
8789 Scale->getZExtValue() / ArrayEltSize);
8790 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008791 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8792 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008793 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8794 NewIdx = InsertNewInstBefore(Sc, GEP);
8795 }
8796
8797 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008798 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008799 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008800 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008801 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8802 // The NewGEP must be pointer typed, so must the old one -> BitCast
8803 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008804 }
8805 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008806 }
Chris Lattnerca081252001-12-14 16:52:21 +00008807 }
8808
Chris Lattnerca081252001-12-14 16:52:21 +00008809 return 0;
8810}
8811
Chris Lattner1085bdf2002-11-04 16:18:53 +00008812Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8813 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8814 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008815 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8816 const Type *NewTy =
8817 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008818 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008819
8820 // Create and insert the replacement instruction...
8821 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008822 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008823 else {
8824 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008825 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008826 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008827
8828 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008829
Chris Lattner1085bdf2002-11-04 16:18:53 +00008830 // Scan to the end of the allocation instructions, to skip over a block of
8831 // allocas if possible...
8832 //
8833 BasicBlock::iterator It = New;
8834 while (isa<AllocationInst>(*It)) ++It;
8835
8836 // Now that I is pointing to the first non-allocation-inst in the block,
8837 // insert our getelementptr instruction...
8838 //
Reid Spencerc635f472006-12-31 05:48:39 +00008839 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008840 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8841 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008842
8843 // Now make everything use the getelementptr instead of the original
8844 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008845 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008846 } else if (isa<UndefValue>(AI.getArraySize())) {
8847 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008848 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008849
8850 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8851 // Note that we only do this for alloca's, because malloc should allocate and
8852 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008853 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008854 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008855 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8856
Chris Lattner1085bdf2002-11-04 16:18:53 +00008857 return 0;
8858}
8859
Chris Lattner8427bff2003-12-07 01:24:23 +00008860Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8861 Value *Op = FI.getOperand(0);
8862
8863 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8864 if (CastInst *CI = dyn_cast<CastInst>(Op))
8865 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8866 FI.setOperand(0, CI->getOperand(0));
8867 return &FI;
8868 }
8869
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008870 // free undef -> unreachable.
8871 if (isa<UndefValue>(Op)) {
8872 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008873 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008874 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008875 return EraseInstFromFunction(FI);
8876 }
8877
Chris Lattnerf3a36602004-02-28 04:57:37 +00008878 // If we have 'free null' delete the instruction. This can happen in stl code
8879 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008880 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008881 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008882
Chris Lattner8427bff2003-12-07 01:24:23 +00008883 return 0;
8884}
8885
8886
Chris Lattner72684fe2005-01-31 05:51:45 +00008887/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008888static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8889 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008890 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008891
8892 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008893 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008894 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008895
Reid Spencer31a4ef42007-01-22 05:51:25 +00008896 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008897 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008898 // If the source is an array, the code below will not succeed. Check to
8899 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8900 // constants.
8901 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8902 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8903 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008904 Value *Idxs[2];
8905 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8906 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008907 SrcTy = cast<PointerType>(CastOp->getType());
8908 SrcPTy = SrcTy->getElementType();
8909 }
8910
Reid Spencer31a4ef42007-01-22 05:51:25 +00008911 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008912 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008913 // Do not allow turning this into a load of an integer, which is then
8914 // casted to a pointer, this pessimizes pointer analysis a lot.
8915 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008916 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8917 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008918
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008919 // Okay, we are casting from one integer or pointer type to another of
8920 // the same size. Instead of casting the pointer before the load, cast
8921 // the result of the loaded value.
8922 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8923 CI->getName(),
8924 LI.isVolatile()),LI);
8925 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008926 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008927 }
Chris Lattner35e24772004-07-13 01:49:43 +00008928 }
8929 }
8930 return 0;
8931}
8932
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008933/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008934/// from this value cannot trap. If it is not obviously safe to load from the
8935/// specified pointer, we do a quick local scan of the basic block containing
8936/// ScanFrom, to determine if the address is already accessed.
8937static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8938 // If it is an alloca or global variable, it is always safe to load from.
8939 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8940
8941 // Otherwise, be a little bit agressive by scanning the local block where we
8942 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008943 // from/to. If so, the previous load or store would have already trapped,
8944 // so there is no harm doing an extra load (also, CSE will later eliminate
8945 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008946 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8947
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008948 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008949 --BBI;
8950
8951 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8952 if (LI->getOperand(0) == V) return true;
8953 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8954 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008955
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008956 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008957 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008958}
8959
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008960Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8961 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008962
Chris Lattnera9d84e32005-05-01 04:24:53 +00008963 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008964 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008965 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8966 return Res;
8967
8968 // None of the following transforms are legal for volatile loads.
8969 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008970
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008971 if (&LI.getParent()->front() != &LI) {
8972 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008973 // If the instruction immediately before this is a store to the same
8974 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008975 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8976 if (SI->getOperand(1) == LI.getOperand(0))
8977 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008978 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8979 if (LIB->getOperand(0) == LI.getOperand(0))
8980 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008981 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008982
8983 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8984 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8985 isa<UndefValue>(GEPI->getOperand(0))) {
8986 // Insert a new store to null instruction before the load to indicate
8987 // that this code is not reachable. We do this instead of inserting
8988 // an unreachable instruction directly because we cannot modify the
8989 // CFG.
8990 new StoreInst(UndefValue::get(LI.getType()),
8991 Constant::getNullValue(Op->getType()), &LI);
8992 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8993 }
8994
Chris Lattner81a7a232004-10-16 18:11:37 +00008995 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008996 // load null/undef -> undef
8997 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008998 // Insert a new store to null instruction before the load to indicate that
8999 // this code is not reachable. We do this instead of inserting an
9000 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00009001 new StoreInst(UndefValue::get(LI.getType()),
9002 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00009003 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009004 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00009005
Chris Lattner81a7a232004-10-16 18:11:37 +00009006 // Instcombine load (constant global) into the value loaded.
9007 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00009008 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00009009 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00009010
Chris Lattner81a7a232004-10-16 18:11:37 +00009011 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9012 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9013 if (CE->getOpcode() == Instruction::GetElementPtr) {
9014 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00009015 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00009016 if (Constant *V =
9017 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00009018 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00009019 if (CE->getOperand(0)->isNullValue()) {
9020 // Insert a new store to null instruction before the load to indicate
9021 // that this code is not reachable. We do this instead of inserting
9022 // an unreachable instruction directly because we cannot modify the
9023 // CFG.
9024 new StoreInst(UndefValue::get(LI.getType()),
9025 Constant::getNullValue(Op->getType()), &LI);
9026 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9027 }
9028
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009029 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00009030 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9031 return Res;
9032 }
9033 }
Chris Lattnere228ee52004-04-08 20:39:49 +00009034
Chris Lattnera9d84e32005-05-01 04:24:53 +00009035 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009036 // Change select and PHI nodes to select values instead of addresses: this
9037 // helps alias analysis out a lot, allows many others simplifications, and
9038 // exposes redundancy in the code.
9039 //
9040 // Note that we cannot do the transformation unless we know that the
9041 // introduced loads cannot trap! Something like this is valid as long as
9042 // the condition is always false: load (select bool %C, int* null, int* %G),
9043 // but it would not be valid if we transformed it to load from null
9044 // unconditionally.
9045 //
9046 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9047 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00009048 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9049 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009050 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00009051 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009052 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00009053 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009054 return new SelectInst(SI->getCondition(), V1, V2);
9055 }
9056
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00009057 // load (select (cond, null, P)) -> load P
9058 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9059 if (C->isNullValue()) {
9060 LI.setOperand(0, SI->getOperand(2));
9061 return &LI;
9062 }
9063
9064 // load (select (cond, P, null)) -> load P
9065 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9066 if (C->isNullValue()) {
9067 LI.setOperand(0, SI->getOperand(1));
9068 return &LI;
9069 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009070 }
9071 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00009072 return 0;
9073}
9074
Reid Spencere928a152007-01-19 21:20:31 +00009075/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00009076/// when possible.
9077static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9078 User *CI = cast<User>(SI.getOperand(1));
9079 Value *CastOp = CI->getOperand(0);
9080
9081 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9082 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9083 const Type *SrcPTy = SrcTy->getElementType();
9084
Reid Spencer31a4ef42007-01-22 05:51:25 +00009085 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00009086 // If the source is an array, the code below will not succeed. Check to
9087 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9088 // constants.
9089 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9090 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9091 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00009092 Value* Idxs[2];
9093 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9094 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00009095 SrcTy = cast<PointerType>(CastOp->getType());
9096 SrcPTy = SrcTy->getElementType();
9097 }
9098
Reid Spencer9a4bed02007-01-20 23:35:48 +00009099 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9100 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9101 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00009102
9103 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00009104 // the same size. Instead of casting the pointer before
9105 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00009106 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009107 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00009108 Instruction::CastOps opcode = Instruction::BitCast;
9109 const Type* CastSrcTy = SIOp0->getType();
9110 const Type* CastDstTy = SrcPTy;
9111 if (isa<PointerType>(CastDstTy)) {
9112 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009113 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00009114 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00009115 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009116 opcode = Instruction::PtrToInt;
9117 }
9118 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00009119 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00009120 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009121 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00009122 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9123 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00009124 return new StoreInst(NewCast, CastOp);
9125 }
9126 }
9127 }
9128 return 0;
9129}
9130
Chris Lattner31f486c2005-01-31 05:36:43 +00009131Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9132 Value *Val = SI.getOperand(0);
9133 Value *Ptr = SI.getOperand(1);
9134
9135 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00009136 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00009137 ++NumCombined;
9138 return 0;
9139 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00009140
9141 // If the RHS is an alloca with a single use, zapify the store, making the
9142 // alloca dead.
9143 if (Ptr->hasOneUse()) {
9144 if (isa<AllocaInst>(Ptr)) {
9145 EraseInstFromFunction(SI);
9146 ++NumCombined;
9147 return 0;
9148 }
9149
9150 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9151 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9152 GEP->getOperand(0)->hasOneUse()) {
9153 EraseInstFromFunction(SI);
9154 ++NumCombined;
9155 return 0;
9156 }
9157 }
Chris Lattner31f486c2005-01-31 05:36:43 +00009158
Chris Lattner5997cf92006-02-08 03:25:32 +00009159 // Do really simple DSE, to catch cases where there are several consequtive
9160 // stores to the same location, separated by a few arithmetic operations. This
9161 // situation often occurs with bitfield accesses.
9162 BasicBlock::iterator BBI = &SI;
9163 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9164 --ScanInsts) {
9165 --BBI;
9166
9167 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9168 // Prev store isn't volatile, and stores to the same location?
9169 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9170 ++NumDeadStore;
9171 ++BBI;
9172 EraseInstFromFunction(*PrevSI);
9173 continue;
9174 }
9175 break;
9176 }
9177
Chris Lattnerdab43b22006-05-26 19:19:20 +00009178 // If this is a load, we have to stop. However, if the loaded value is from
9179 // the pointer we're loading and is producing the pointer we're storing,
9180 // then *this* store is dead (X = load P; store X -> P).
9181 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9182 if (LI == Val && LI->getOperand(0) == Ptr) {
9183 EraseInstFromFunction(SI);
9184 ++NumCombined;
9185 return 0;
9186 }
9187 // Otherwise, this is a load from some other location. Stores before it
9188 // may not be dead.
9189 break;
9190 }
9191
Chris Lattner5997cf92006-02-08 03:25:32 +00009192 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00009193 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00009194 break;
9195 }
9196
9197
9198 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00009199
9200 // store X, null -> turns into 'unreachable' in SimplifyCFG
9201 if (isa<ConstantPointerNull>(Ptr)) {
9202 if (!isa<UndefValue>(Val)) {
9203 SI.setOperand(0, UndefValue::get(Val->getType()));
9204 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009205 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00009206 ++NumCombined;
9207 }
9208 return 0; // Do not modify these!
9209 }
9210
9211 // store undef, Ptr -> noop
9212 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00009213 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00009214 ++NumCombined;
9215 return 0;
9216 }
9217
Chris Lattner72684fe2005-01-31 05:51:45 +00009218 // If the pointer destination is a cast, see if we can fold the cast into the
9219 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00009220 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00009221 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9222 return Res;
9223 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009224 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00009225 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9226 return Res;
9227
Chris Lattner219175c2005-09-12 23:23:25 +00009228
9229 // If this store is the last instruction in the basic block, and if the block
9230 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00009231 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00009232 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9233 if (BI->isUnconditional()) {
9234 // Check to see if the successor block has exactly two incoming edges. If
9235 // so, see if the other predecessor contains a store to the same location.
9236 // if so, insert a PHI node (if needed) and move the stores down.
9237 BasicBlock *Dest = BI->getSuccessor(0);
9238
9239 pred_iterator PI = pred_begin(Dest);
9240 BasicBlock *Other = 0;
9241 if (*PI != BI->getParent())
9242 Other = *PI;
9243 ++PI;
9244 if (PI != pred_end(Dest)) {
9245 if (*PI != BI->getParent())
9246 if (Other)
9247 Other = 0;
9248 else
9249 Other = *PI;
9250 if (++PI != pred_end(Dest))
9251 Other = 0;
9252 }
9253 if (Other) { // If only one other pred...
9254 BBI = Other->getTerminator();
9255 // Make sure this other block ends in an unconditional branch and that
9256 // there is an instruction before the branch.
9257 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9258 BBI != Other->begin()) {
9259 --BBI;
9260 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9261
9262 // If this instruction is a store to the same location.
9263 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9264 // Okay, we know we can perform this transformation. Insert a PHI
9265 // node now if we need it.
9266 Value *MergedVal = OtherStore->getOperand(0);
9267 if (MergedVal != SI.getOperand(0)) {
9268 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9269 PN->reserveOperandSpace(2);
9270 PN->addIncoming(SI.getOperand(0), SI.getParent());
9271 PN->addIncoming(OtherStore->getOperand(0), Other);
9272 MergedVal = InsertNewInstBefore(PN, Dest->front());
9273 }
9274
9275 // Advance to a place where it is safe to insert the new store and
9276 // insert it.
9277 BBI = Dest->begin();
9278 while (isa<PHINode>(BBI)) ++BBI;
9279 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9280 OtherStore->isVolatile()), *BBI);
9281
9282 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00009283 EraseInstFromFunction(SI);
9284 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00009285 ++NumCombined;
9286 return 0;
9287 }
9288 }
9289 }
9290 }
9291
Chris Lattner31f486c2005-01-31 05:36:43 +00009292 return 0;
9293}
9294
9295
Chris Lattner9eef8a72003-06-04 04:46:00 +00009296Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9297 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00009298 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00009299 BasicBlock *TrueDest;
9300 BasicBlock *FalseDest;
9301 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9302 !isa<Constant>(X)) {
9303 // Swap Destinations and condition...
9304 BI.setCondition(X);
9305 BI.setSuccessor(0, FalseDest);
9306 BI.setSuccessor(1, TrueDest);
9307 return &BI;
9308 }
9309
Reid Spencer266e42b2006-12-23 06:05:41 +00009310 // Cannonicalize fcmp_one -> fcmp_oeq
9311 FCmpInst::Predicate FPred; Value *Y;
9312 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9313 TrueDest, FalseDest)))
9314 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9315 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9316 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009317 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009318 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9319 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00009320 // Swap Destinations and condition...
9321 BI.setCondition(NewSCC);
9322 BI.setSuccessor(0, FalseDest);
9323 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009324 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009325 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009326 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00009327 return &BI;
9328 }
9329
9330 // Cannonicalize icmp_ne -> icmp_eq
9331 ICmpInst::Predicate IPred;
9332 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9333 TrueDest, FalseDest)))
9334 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9335 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9336 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9337 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009338 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009339 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9340 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00009341 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00009342 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009343 BI.setSuccessor(0, FalseDest);
9344 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009345 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009346 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009347 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009348 return &BI;
9349 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009350
Chris Lattner9eef8a72003-06-04 04:46:00 +00009351 return 0;
9352}
Chris Lattner1085bdf2002-11-04 16:18:53 +00009353
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009354Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9355 Value *Cond = SI.getCondition();
9356 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9357 if (I->getOpcode() == Instruction::Add)
9358 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9359 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9360 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00009361 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009362 AddRHS));
9363 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009364 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009365 return &SI;
9366 }
9367 }
9368 return 0;
9369}
9370
Chris Lattner6bc98652006-03-05 00:22:33 +00009371/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9372/// is to leave as a vector operation.
9373static bool CheapToScalarize(Value *V, bool isConstant) {
9374 if (isa<ConstantAggregateZero>(V))
9375 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009376 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009377 if (isConstant) return true;
9378 // If all elts are the same, we can extract.
9379 Constant *Op0 = C->getOperand(0);
9380 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9381 if (C->getOperand(i) != Op0)
9382 return false;
9383 return true;
9384 }
9385 Instruction *I = dyn_cast<Instruction>(V);
9386 if (!I) return false;
9387
9388 // Insert element gets simplified to the inserted element or is deleted if
9389 // this is constant idx extract element and its a constant idx insertelt.
9390 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9391 isa<ConstantInt>(I->getOperand(2)))
9392 return true;
9393 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9394 return true;
9395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9396 if (BO->hasOneUse() &&
9397 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9398 CheapToScalarize(BO->getOperand(1), isConstant)))
9399 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00009400 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9401 if (CI->hasOneUse() &&
9402 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9403 CheapToScalarize(CI->getOperand(1), isConstant)))
9404 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00009405
9406 return false;
9407}
9408
Chris Lattner945e4372007-02-14 05:52:17 +00009409/// Read and decode a shufflevector mask.
9410///
9411/// It turns undef elements into values that are larger than the number of
9412/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00009413static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9414 unsigned NElts = SVI->getType()->getNumElements();
9415 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9416 return std::vector<unsigned>(NElts, 0);
9417 if (isa<UndefValue>(SVI->getOperand(2)))
9418 return std::vector<unsigned>(NElts, 2*NElts);
9419
9420 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009421 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00009422 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9423 if (isa<UndefValue>(CP->getOperand(i)))
9424 Result.push_back(NElts*2); // undef -> 8
9425 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00009426 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00009427 return Result;
9428}
9429
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009430/// FindScalarElement - Given a vector and an element number, see if the scalar
9431/// value is already around as a register, for example if it were inserted then
9432/// extracted from the vector.
9433static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009434 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9435 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00009436 unsigned Width = PTy->getNumElements();
9437 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009438 return UndefValue::get(PTy->getElementType());
9439
9440 if (isa<UndefValue>(V))
9441 return UndefValue::get(PTy->getElementType());
9442 else if (isa<ConstantAggregateZero>(V))
9443 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00009444 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009445 return CP->getOperand(EltNo);
9446 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9447 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009448 if (!isa<ConstantInt>(III->getOperand(2)))
9449 return 0;
9450 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009451
9452 // If this is an insert to the element we are looking for, return the
9453 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009454 if (EltNo == IIElt)
9455 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009456
9457 // Otherwise, the insertelement doesn't modify the value, recurse on its
9458 // vector input.
9459 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00009460 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00009461 unsigned InEl = getShuffleMask(SVI)[EltNo];
9462 if (InEl < Width)
9463 return FindScalarElement(SVI->getOperand(0), InEl);
9464 else if (InEl < Width*2)
9465 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9466 else
9467 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009468 }
9469
9470 // Otherwise, we don't know.
9471 return 0;
9472}
9473
Robert Bocchinoa8352962006-01-13 22:48:06 +00009474Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009475
Chris Lattner92346c32006-03-31 18:25:14 +00009476 // If packed val is undef, replace extract with scalar undef.
9477 if (isa<UndefValue>(EI.getOperand(0)))
9478 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9479
9480 // If packed val is constant 0, replace extract with scalar 0.
9481 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9482 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9483
Reid Spencerd84d35b2007-02-15 02:26:10 +00009484 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009485 // If packed val is constant with uniform operands, replace EI
9486 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00009487 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009488 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00009489 if (C->getOperand(i) != op0) {
9490 op0 = 0;
9491 break;
9492 }
9493 if (op0)
9494 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009495 }
Chris Lattner6bc98652006-03-05 00:22:33 +00009496
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009497 // If extracting a specified index from the vector, see if we can recursively
9498 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009499 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00009500 // This instruction only demands the single element from the input vector.
9501 // If the input vector has a single use, simplify it based on this use
9502 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009503 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00009504 if (EI.getOperand(0)->hasOneUse()) {
9505 uint64_t UndefElts;
9506 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00009507 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00009508 UndefElts)) {
9509 EI.setOperand(0, V);
9510 return &EI;
9511 }
9512 }
9513
Reid Spencere0fc4df2006-10-20 07:07:24 +00009514 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009515 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00009516 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009517
Chris Lattner83f65782006-05-25 22:53:38 +00009518 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009519 if (I->hasOneUse()) {
9520 // Push extractelement into predecessor operation if legal and
9521 // profitable to do so
9522 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009523 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9524 if (CheapToScalarize(BO, isConstantElt)) {
9525 ExtractElementInst *newEI0 =
9526 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9527 EI.getName()+".lhs");
9528 ExtractElementInst *newEI1 =
9529 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9530 EI.getName()+".rhs");
9531 InsertNewInstBefore(newEI0, EI);
9532 InsertNewInstBefore(newEI1, EI);
9533 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9534 }
Reid Spencerde46e482006-11-02 20:25:50 +00009535 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009536 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00009537 PointerType::get(EI.getType()), EI);
9538 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00009539 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00009540 InsertNewInstBefore(GEP, EI);
9541 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00009542 }
9543 }
9544 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9545 // Extracting the inserted element?
9546 if (IE->getOperand(2) == EI.getOperand(1))
9547 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9548 // If the inserted and extracted elements are constants, they must not
9549 // be the same value, extract from the pre-inserted value instead.
9550 if (isa<Constant>(IE->getOperand(2)) &&
9551 isa<Constant>(EI.getOperand(1))) {
9552 AddUsesToWorkList(EI);
9553 EI.setOperand(0, IE->getOperand(0));
9554 return &EI;
9555 }
9556 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9557 // If this is extracting an element from a shufflevector, figure out where
9558 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009559 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9560 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00009561 Value *Src;
9562 if (SrcIdx < SVI->getType()->getNumElements())
9563 Src = SVI->getOperand(0);
9564 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9565 SrcIdx -= SVI->getType()->getNumElements();
9566 Src = SVI->getOperand(1);
9567 } else {
9568 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009569 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009570 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009571 }
9572 }
Chris Lattner83f65782006-05-25 22:53:38 +00009573 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009574 return 0;
9575}
9576
Chris Lattner90951862006-04-16 00:51:47 +00009577/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9578/// elements from either LHS or RHS, return the shuffle mask and true.
9579/// Otherwise, return false.
9580static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9581 std::vector<Constant*> &Mask) {
9582 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9583 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009584 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009585
9586 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009587 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009588 return true;
9589 } else if (V == LHS) {
9590 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009591 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009592 return true;
9593 } else if (V == RHS) {
9594 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009595 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009596 return true;
9597 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9598 // If this is an insert of an extract from some other vector, include it.
9599 Value *VecOp = IEI->getOperand(0);
9600 Value *ScalarOp = IEI->getOperand(1);
9601 Value *IdxOp = IEI->getOperand(2);
9602
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009603 if (!isa<ConstantInt>(IdxOp))
9604 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009605 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009606
9607 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9608 // Okay, we can handle this if the vector we are insertinting into is
9609 // transitively ok.
9610 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9611 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009612 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009613 return true;
9614 }
9615 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9616 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009617 EI->getOperand(0)->getType() == V->getType()) {
9618 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009619 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009620
9621 // This must be extracting from either LHS or RHS.
9622 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9623 // Okay, we can handle this if the vector we are insertinting into is
9624 // transitively ok.
9625 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9626 // If so, update the mask to reflect the inserted value.
9627 if (EI->getOperand(0) == LHS) {
9628 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009629 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009630 } else {
9631 assert(EI->getOperand(0) == RHS);
9632 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009633 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009634
9635 }
9636 return true;
9637 }
9638 }
9639 }
9640 }
9641 }
9642 // TODO: Handle shufflevector here!
9643
9644 return false;
9645}
9646
9647/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9648/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9649/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009650static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009651 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009652 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009653 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009654 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009655 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009656
9657 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009658 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009659 return V;
9660 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009661 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009662 return V;
9663 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9664 // If this is an insert of an extract from some other vector, include it.
9665 Value *VecOp = IEI->getOperand(0);
9666 Value *ScalarOp = IEI->getOperand(1);
9667 Value *IdxOp = IEI->getOperand(2);
9668
9669 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9670 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9671 EI->getOperand(0)->getType() == V->getType()) {
9672 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009673 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9674 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009675
9676 // Either the extracted from or inserted into vector must be RHSVec,
9677 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009678 if (EI->getOperand(0) == RHS || RHS == 0) {
9679 RHS = EI->getOperand(0);
9680 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009681 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009682 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009683 return V;
9684 }
9685
Chris Lattner90951862006-04-16 00:51:47 +00009686 if (VecOp == RHS) {
9687 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009688 // Everything but the extracted element is replaced with the RHS.
9689 for (unsigned i = 0; i != NumElts; ++i) {
9690 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009691 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009692 }
9693 return V;
9694 }
Chris Lattner90951862006-04-16 00:51:47 +00009695
9696 // If this insertelement is a chain that comes from exactly these two
9697 // vectors, return the vector and the effective shuffle.
9698 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9699 return EI->getOperand(0);
9700
Chris Lattner39fac442006-04-15 01:39:45 +00009701 }
9702 }
9703 }
Chris Lattner90951862006-04-16 00:51:47 +00009704 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009705
9706 // Otherwise, can't do anything fancy. Return an identity vector.
9707 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009708 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009709 return V;
9710}
9711
9712Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9713 Value *VecOp = IE.getOperand(0);
9714 Value *ScalarOp = IE.getOperand(1);
9715 Value *IdxOp = IE.getOperand(2);
9716
9717 // If the inserted element was extracted from some other vector, and if the
9718 // indexes are constant, try to turn this into a shufflevector operation.
9719 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9720 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9721 EI->getOperand(0)->getType() == IE.getType()) {
9722 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009723 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9724 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009725
9726 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9727 return ReplaceInstUsesWith(IE, VecOp);
9728
9729 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9730 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9731
9732 // If we are extracting a value from a vector, then inserting it right
9733 // back into the same place, just use the input vector.
9734 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9735 return ReplaceInstUsesWith(IE, VecOp);
9736
9737 // We could theoretically do this for ANY input. However, doing so could
9738 // turn chains of insertelement instructions into a chain of shufflevector
9739 // instructions, and right now we do not merge shufflevectors. As such,
9740 // only do this in a situation where it is clear that there is benefit.
9741 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9742 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9743 // the values of VecOp, except then one read from EIOp0.
9744 // Build a new shuffle mask.
9745 std::vector<Constant*> Mask;
9746 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009747 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009748 else {
9749 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009750 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009751 NumVectorElts));
9752 }
Reid Spencerc635f472006-12-31 05:48:39 +00009753 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009754 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009755 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009756 }
9757
9758 // If this insertelement isn't used by some other insertelement, turn it
9759 // (and any insertelements it points to), into one big shuffle.
9760 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9761 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009762 Value *RHS = 0;
9763 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9764 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9765 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009766 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009767 }
9768 }
9769 }
9770
9771 return 0;
9772}
9773
9774
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009775Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9776 Value *LHS = SVI.getOperand(0);
9777 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009778 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009779
9780 bool MadeChange = false;
9781
Chris Lattner2deeaea2006-10-05 06:55:50 +00009782 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009783 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009784 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9785
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009786 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009787 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009788 if (isa<UndefValue>(SVI.getOperand(1))) {
9789 // Scan to see if there are any references to the RHS. If so, replace them
9790 // with undef element refs and set MadeChange to true.
9791 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9792 if (Mask[i] >= e && Mask[i] != 2*e) {
9793 Mask[i] = 2*e;
9794 MadeChange = true;
9795 }
9796 }
9797
9798 if (MadeChange) {
9799 // Remap any references to RHS to use LHS.
9800 std::vector<Constant*> Elts;
9801 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9802 if (Mask[i] == 2*e)
9803 Elts.push_back(UndefValue::get(Type::Int32Ty));
9804 else
9805 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9806 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009807 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009808 }
9809 }
Chris Lattner39fac442006-04-15 01:39:45 +00009810
Chris Lattner12249be2006-05-25 23:48:38 +00009811 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9812 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9813 if (LHS == RHS || isa<UndefValue>(LHS)) {
9814 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009815 // shuffle(undef,undef,mask) -> undef.
9816 return ReplaceInstUsesWith(SVI, LHS);
9817 }
9818
Chris Lattner12249be2006-05-25 23:48:38 +00009819 // Remap any references to RHS to use LHS.
9820 std::vector<Constant*> Elts;
9821 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009822 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009823 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009824 else {
9825 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9826 (Mask[i] < e && isa<UndefValue>(LHS)))
9827 Mask[i] = 2*e; // Turn into undef.
9828 else
9829 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009830 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009831 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009832 }
Chris Lattner12249be2006-05-25 23:48:38 +00009833 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009834 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009835 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009836 LHS = SVI.getOperand(0);
9837 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009838 MadeChange = true;
9839 }
9840
Chris Lattner0e477162006-05-26 00:29:06 +00009841 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009842 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009843
Chris Lattner12249be2006-05-25 23:48:38 +00009844 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9845 if (Mask[i] >= e*2) continue; // Ignore undef values.
9846 // Is this an identity shuffle of the LHS value?
9847 isLHSID &= (Mask[i] == i);
9848
9849 // Is this an identity shuffle of the RHS value?
9850 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009851 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009852
Chris Lattner12249be2006-05-25 23:48:38 +00009853 // Eliminate identity shuffles.
9854 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9855 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009856
Chris Lattner0e477162006-05-26 00:29:06 +00009857 // If the LHS is a shufflevector itself, see if we can combine it with this
9858 // one without producing an unusual shuffle. Here we are really conservative:
9859 // we are absolutely afraid of producing a shuffle mask not in the input
9860 // program, because the code gen may not be smart enough to turn a merged
9861 // shuffle into two specific shuffles: it may produce worse code. As such,
9862 // we only merge two shuffles if the result is one of the two input shuffle
9863 // masks. In this case, merging the shuffles just removes one instruction,
9864 // which we know is safe. This is good for things like turning:
9865 // (splat(splat)) -> splat.
9866 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9867 if (isa<UndefValue>(RHS)) {
9868 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9869
9870 std::vector<unsigned> NewMask;
9871 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9872 if (Mask[i] >= 2*e)
9873 NewMask.push_back(2*e);
9874 else
9875 NewMask.push_back(LHSMask[Mask[i]]);
9876
9877 // If the result mask is equal to the src shuffle or this shuffle mask, do
9878 // the replacement.
9879 if (NewMask == LHSMask || NewMask == Mask) {
9880 std::vector<Constant*> Elts;
9881 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9882 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009883 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009884 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009885 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009886 }
9887 }
9888 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9889 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009890 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009891 }
9892 }
9893 }
Chris Lattner4284f642007-01-30 22:32:46 +00009894
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009895 return MadeChange ? &SVI : 0;
9896}
9897
9898
Robert Bocchinoa8352962006-01-13 22:48:06 +00009899
Chris Lattner39c98bb2004-12-08 23:43:58 +00009900
9901/// TryToSinkInstruction - Try to move the specified instruction from its
9902/// current block into the beginning of DestBlock, which can only happen if it's
9903/// safe to move the instruction past all of the instructions between it and the
9904/// end of its block.
9905static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9906 assert(I->hasOneUse() && "Invariants didn't hold!");
9907
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009908 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9909 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009910
Chris Lattner39c98bb2004-12-08 23:43:58 +00009911 // Do not sink alloca instructions out of the entry block.
9912 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9913 return false;
9914
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009915 // We can only sink load instructions if there is nothing between the load and
9916 // the end of block that could change the value.
9917 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009918 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9919 Scan != E; ++Scan)
9920 if (Scan->mayWriteToMemory())
9921 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009922 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009923
9924 BasicBlock::iterator InsertPos = DestBlock->begin();
9925 while (isa<PHINode>(InsertPos)) ++InsertPos;
9926
Chris Lattner9f269e42005-08-08 19:11:57 +00009927 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009928 ++NumSunkInst;
9929 return true;
9930}
9931
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009932
9933/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9934/// all reachable code to the worklist.
9935///
9936/// This has a couple of tricks to make the code faster and more powerful. In
9937/// particular, we constant fold and DCE instructions as we go, to avoid adding
9938/// them to the worklist (this significantly speeds up instcombine on code where
9939/// many instructions are dead or constant). Additionally, if we find a branch
9940/// whose condition is a known constant, we only visit the reachable successors.
9941///
9942static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009943 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009944 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009945 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009946 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009947 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009948
9949 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9950 Instruction *Inst = BBI++;
9951
9952 // DCE instruction if trivially dead.
9953 if (isInstructionTriviallyDead(Inst)) {
9954 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009955 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009956 Inst->eraseFromParent();
9957 continue;
9958 }
9959
9960 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009961 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009962 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009963 Inst->replaceAllUsesWith(C);
9964 ++NumConstProp;
9965 Inst->eraseFromParent();
9966 continue;
9967 }
9968
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009969 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009970 }
9971
9972 // Recursively visit successors. If this is a branch or switch on a constant,
9973 // only visit the reachable successor.
9974 TerminatorInst *TI = BB->getTerminator();
9975 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009976 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009977 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009978 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009979 return;
9980 }
9981 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9982 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9983 // See if this is an explicit destination.
9984 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9985 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009986 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009987 return;
9988 }
9989
9990 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009991 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009992 return;
9993 }
9994 }
9995
9996 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009997 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009998}
9999
Chris Lattner960a5432007-03-03 02:04:50 +000010000bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +000010001 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000010002 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +000010003
10004 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10005 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000010006
Chris Lattner4ed40f72005-07-07 20:40:38 +000010007 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010008 // Do a depth-first traversal of the function, populate the worklist with
10009 // the reachable instructions. Ignore blocks that are not reachable. Keep
10010 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000010011 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010012 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000010013
Chris Lattner4ed40f72005-07-07 20:40:38 +000010014 // Do a quick scan over the function. If we find any blocks that are
10015 // unreachable, remove any instructions inside of them. This prevents
10016 // the instcombine code from having to deal with some bad special cases.
10017 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10018 if (!Visited.count(BB)) {
10019 Instruction *Term = BB->getTerminator();
10020 while (Term != BB->begin()) { // Remove instrs bottom-up
10021 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000010022
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010023 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +000010024 ++NumDeadInst;
10025
10026 if (!I->use_empty())
10027 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10028 I->eraseFromParent();
10029 }
10030 }
10031 }
Chris Lattnerca081252001-12-14 16:52:21 +000010032
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010033 while (!Worklist.empty()) {
10034 Instruction *I = RemoveOneFromWorkList();
10035 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000010036
Chris Lattner1443bc52006-05-11 17:11:52 +000010037 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000010038 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000010039 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010040 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000010041 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000010042 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010043
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010044 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000010045
10046 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010047 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010048 continue;
10049 }
Chris Lattner99f48c62002-09-02 04:59:56 +000010050
Chris Lattner1443bc52006-05-11 17:11:52 +000010051 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +000010052 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010053 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000010054
Chris Lattner1443bc52006-05-11 17:11:52 +000010055 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000010056 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000010057 ReplaceInstUsesWith(*I, C);
10058
Chris Lattner99f48c62002-09-02 04:59:56 +000010059 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010060 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010061 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010062 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000010063 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010064
Chris Lattner39c98bb2004-12-08 23:43:58 +000010065 // See if we can trivially sink this instruction to a successor basic block.
10066 if (I->hasOneUse()) {
10067 BasicBlock *BB = I->getParent();
10068 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10069 if (UserParent != BB) {
10070 bool UserIsSuccessor = false;
10071 // See if the user is one of our successors.
10072 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10073 if (*SI == UserParent) {
10074 UserIsSuccessor = true;
10075 break;
10076 }
10077
10078 // If the user is one of our immediate successors, and if that successor
10079 // only has us as a predecessors (we'd have to split the critical edge
10080 // otherwise), we can keep going.
10081 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10082 next(pred_begin(UserParent)) == pred_end(UserParent))
10083 // Okay, the CFG is simple enough, try to sink this instruction.
10084 Changed |= TryToSinkInstruction(I, UserParent);
10085 }
10086 }
10087
Chris Lattnerca081252001-12-14 16:52:21 +000010088 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010089 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000010090 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000010091 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000010092 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010093 DOUT << "IC: Old = " << *I
10094 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000010095
Chris Lattner396dbfe2004-06-09 05:08:07 +000010096 // Everything uses the new instruction now.
10097 I->replaceAllUsesWith(Result);
10098
10099 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010100 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000010101 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010102
Chris Lattner6e0123b2007-02-11 01:23:03 +000010103 // Move the name to the new instruction first.
10104 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010105
10106 // Insert the new instruction into the basic block...
10107 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000010108 BasicBlock::iterator InsertPos = I;
10109
10110 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10111 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10112 ++InsertPos;
10113
10114 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010115
Chris Lattner63d75af2004-05-01 23:27:23 +000010116 // Make sure that we reprocess all operands now that we reduced their
10117 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010118 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000010119
Chris Lattner396dbfe2004-06-09 05:08:07 +000010120 // Instructions can end up on the worklist more than once. Make sure
10121 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010122 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010123
10124 // Erase the old instruction.
10125 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000010126 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010127 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +000010128
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010129 // If the instruction was modified, it's possible that it is now dead.
10130 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000010131 if (isInstructionTriviallyDead(I)) {
10132 // Make sure we process all operands now that we are reducing their
10133 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000010134 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010135
Chris Lattner63d75af2004-05-01 23:27:23 +000010136 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000010137 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010138 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000010139 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000010140 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000010141 AddToWorkList(I);
10142 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010143 }
Chris Lattner053c0932002-05-14 15:24:07 +000010144 }
Chris Lattner260ab202002-04-18 17:39:14 +000010145 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000010146 }
10147 }
10148
Chris Lattner960a5432007-03-03 02:04:50 +000010149 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +000010150 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000010151}
10152
Chris Lattner960a5432007-03-03 02:04:50 +000010153
10154bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000010155 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10156
Chris Lattner960a5432007-03-03 02:04:50 +000010157 bool EverMadeChange = false;
10158
10159 // Iterate while there is work to do.
10160 unsigned Iteration = 0;
10161 while (DoOneIteration(F, Iteration++))
10162 EverMadeChange = true;
10163 return EverMadeChange;
10164}
10165
Brian Gaeke38b79e82004-07-27 17:43:21 +000010166FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000010167 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000010168}
Brian Gaeke960707c2003-11-11 22:41:34 +000010169