blob: bd88fccc22ee70dd1f1e1ddcc3a1c958e423b591 [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
Reid Spencerbb5741f2007-03-08 01:52:58 +0000995/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
996/// this predicate to simplify operations downstream. Mask is known to be zero
997/// for bits that V cannot have.
998static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000999 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +00001000 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1001 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1002 return (KnownZero & Mask) == Mask;
1003}
1004
Chris Lattner0157e7f2006-02-11 09:31:47 +00001005/// ShrinkDemandedConstant - Check to see if the specified operand of the
1006/// specified instruction is a constant integer. If so, check to see if there
1007/// are any bits set in the constant that are not demanded. If so, shrink the
1008/// constant and return true.
1009static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1010 uint64_t Demanded) {
1011 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1012 if (!OpC) return false;
1013
1014 // If there are no bits set that aren't demanded, nothing to do.
1015 if ((~Demanded & OpC->getZExtValue()) == 0)
1016 return false;
1017
1018 // This is producing any bits that are not needed, shrink the RHS.
1019 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001020 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001021 return true;
1022}
1023
Reid Spencerd9281782007-03-12 17:15:10 +00001024/// ShrinkDemandedConstant - Check to see if the specified operand of the
1025/// specified instruction is a constant integer. If so, check to see if there
1026/// are any bits set in the constant that are not demanded. If so, shrink the
1027/// constant and return true.
1028static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1029 APInt Demanded) {
1030 assert(I && "No instruction?");
1031 assert(OpNo < I->getNumOperands() && "Operand index too large");
1032
1033 // If the operand is not a constant integer, nothing to do.
1034 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1035 if (!OpC) return false;
1036
1037 // If there are no bits set that aren't demanded, nothing to do.
1038 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1039 if ((~Demanded & OpC->getValue()) == 0)
1040 return false;
1041
1042 // This instruction is producing bits that are not demanded. Shrink the RHS.
1043 Demanded &= OpC->getValue();
1044 I->setOperand(OpNo, ConstantInt::get(Demanded));
1045 return true;
1046}
1047
Chris Lattneree0f2802006-02-12 02:07:56 +00001048// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1049// set of known zero and one bits, compute the maximum and minimum values that
1050// could have the specified known zero and known one bits, returning them in
1051// min/max.
1052static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1053 uint64_t KnownZero,
1054 uint64_t KnownOne,
1055 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001056 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001057 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1058
1059 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1060
1061 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1062 // bit if it is unknown.
1063 Min = KnownOne;
1064 Max = KnownOne|UnknownBits;
1065
1066 if (SignBit & UnknownBits) { // Sign bit is unknown
1067 Min |= SignBit;
1068 Max &= ~SignBit;
1069 }
1070
1071 // Sign extend the min/max values.
1072 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1073 Min = (Min << ShAmt) >> ShAmt;
1074 Max = (Max << ShAmt) >> ShAmt;
1075}
1076
1077// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1078// a set of known zero and one bits, compute the maximum and minimum values that
1079// could have the specified known zero and known one bits, returning them in
1080// min/max.
1081static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1082 uint64_t KnownZero,
1083 uint64_t KnownOne,
1084 uint64_t &Min,
1085 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001086 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001087 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1088
1089 // The minimum value is when the unknown bits are all zeros.
1090 Min = KnownOne;
1091 // The maximum value is when the unknown bits are all ones.
1092 Max = KnownOne|UnknownBits;
1093}
Chris Lattner0157e7f2006-02-11 09:31:47 +00001094
1095
1096/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1097/// DemandedMask bits of the result of V are ever used downstream. If we can
1098/// use this information to simplify V, do so and return true. Otherwise,
1099/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1100/// the expression (used to simplify the caller). The KnownZero/One bits may
1101/// only be accurate for those bits in the DemandedMask.
1102bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1103 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +00001104 unsigned Depth) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001105 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng75b871f2007-01-11 12:24:14 +00001106 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +00001107 // We know all of the bits for a constant!
1108 KnownOne = CI->getZExtValue() & DemandedMask;
1109 KnownZero = ~KnownOne & DemandedMask;
1110 return false;
1111 }
1112
1113 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001114 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001115 if (Depth != 0) { // Not at the root.
1116 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1117 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +00001118 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001119 }
Chris Lattner2590e512006-02-07 06:56:34 +00001120 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001121 // just set the DemandedMask to all bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001122 DemandedMask = VTy->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001123 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001124 if (V != UndefValue::get(VTy))
1125 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner92a68652006-02-07 08:05:22 +00001126 return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001127 } else if (Depth == 6) { // Limit search depth.
1128 return false;
1129 }
1130
1131 Instruction *I = dyn_cast<Instruction>(V);
1132 if (!I) return false; // Only analyze instructions.
1133
Chris Lattnerab2f9132007-03-04 23:16:36 +00001134 DemandedMask &= VTy->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +00001135
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001136 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001137 switch (I->getOpcode()) {
1138 default: break;
1139 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001140 // If either the LHS or the RHS are Zero, the result is zero.
1141 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1142 KnownZero, KnownOne, Depth+1))
1143 return true;
1144 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1145
1146 // If something is known zero on the RHS, the bits aren't demanded on the
1147 // LHS.
1148 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1149 KnownZero2, KnownOne2, Depth+1))
1150 return true;
1151 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1152
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001153 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001154 // These bits cannot contribute to the result of the 'and'.
1155 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1156 return UpdateValueUsesWith(I, I->getOperand(0));
1157 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1158 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001159
1160 // If all of the demanded bits in the inputs are known zeros, return zero.
1161 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001162 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001163
Chris Lattner0157e7f2006-02-11 09:31:47 +00001164 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001165 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001166 return UpdateValueUsesWith(I, I);
1167
1168 // Output known-1 bits are only known if set in both the LHS & RHS.
1169 KnownOne &= KnownOne2;
1170 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1171 KnownZero |= KnownZero2;
1172 break;
1173 case Instruction::Or:
1174 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1175 KnownZero, KnownOne, Depth+1))
1176 return true;
1177 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1178 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1179 KnownZero2, KnownOne2, Depth+1))
1180 return true;
1181 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1182
1183 // If all of the demanded bits are known zero on one side, return the other.
1184 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +00001185 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001186 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +00001187 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001188 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001189
1190 // If all of the potentially set bits on one side are known to be set on
1191 // the other side, just use the 'other' side.
1192 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1193 (DemandedMask & (~KnownZero)))
1194 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +00001195 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1196 (DemandedMask & (~KnownZero2)))
1197 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001198
1199 // If the RHS is a constant, see if we can simplify it.
1200 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1201 return UpdateValueUsesWith(I, I);
1202
1203 // Output known-0 bits are only known if clear in both the LHS & RHS.
1204 KnownZero &= KnownZero2;
1205 // Output known-1 are known to be set if set in either the LHS | RHS.
1206 KnownOne |= KnownOne2;
1207 break;
1208 case Instruction::Xor: {
1209 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1210 KnownZero, KnownOne, Depth+1))
1211 return true;
1212 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1213 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1214 KnownZero2, KnownOne2, Depth+1))
1215 return true;
1216 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1217
1218 // If all of the demanded bits are known zero on one side, return the other.
1219 // These bits cannot contribute to the result of the 'xor'.
1220 if ((DemandedMask & KnownZero) == DemandedMask)
1221 return UpdateValueUsesWith(I, I->getOperand(0));
1222 if ((DemandedMask & KnownZero2) == DemandedMask)
1223 return UpdateValueUsesWith(I, I->getOperand(1));
1224
1225 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1226 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1227 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1228 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1229
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001230 // If all of the demanded bits are known to be zero on one side or the
1231 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001232 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001233 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1234 Instruction *Or =
1235 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1236 I->getName());
1237 InsertNewInstBefore(Or, *I);
1238 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001239 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001240
Chris Lattner5b2edb12006-02-12 08:02:11 +00001241 // If all of the demanded bits on one side are known, and all of the set
1242 // bits on that side are also known to be set on the other side, turn this
1243 // into an AND, as we know the bits will be cleared.
1244 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1245 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1246 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001247 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +00001248 Instruction *And =
1249 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1250 InsertNewInstBefore(And, *I);
1251 return UpdateValueUsesWith(I, And);
1252 }
1253 }
1254
Chris Lattner0157e7f2006-02-11 09:31:47 +00001255 // If the RHS is a constant, see if we can simplify it.
1256 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1257 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1258 return UpdateValueUsesWith(I, I);
1259
1260 KnownZero = KnownZeroOut;
1261 KnownOne = KnownOneOut;
1262 break;
1263 }
1264 case Instruction::Select:
1265 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1266 KnownZero, KnownOne, Depth+1))
1267 return true;
1268 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1269 KnownZero2, KnownOne2, Depth+1))
1270 return true;
1271 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1272 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1273
1274 // If the operands are constants, see if we can simplify them.
1275 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1276 return UpdateValueUsesWith(I, I);
1277 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1278 return UpdateValueUsesWith(I, I);
1279
1280 // Only known if known in both the LHS and RHS.
1281 KnownOne &= KnownOne2;
1282 KnownZero &= KnownZero2;
1283 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001284 case Instruction::Trunc:
1285 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1286 KnownZero, KnownOne, Depth+1))
1287 return true;
1288 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1289 break;
1290 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001291 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001292 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001293
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001294 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1295 KnownZero, KnownOne, Depth+1))
1296 return true;
1297 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1298 break;
1299 case Instruction::ZExt: {
1300 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001301 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1302 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001303 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001304
Reid Spencera94d3942007-01-19 21:13:56 +00001305 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001306 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1307 KnownZero, KnownOne, Depth+1))
1308 return true;
1309 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1310 // The top bits are known to be zero.
1311 KnownZero |= NewBits;
1312 break;
1313 }
1314 case Instruction::SExt: {
1315 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001316 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1317 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001318 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001319
1320 // Get the sign bit for the source type
1321 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001322 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001323
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001324 // If any of the sign extended bits are demanded, we know that the sign
1325 // bit is demanded.
1326 if (NewBits & DemandedMask)
1327 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001328
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001329 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1330 KnownZero, KnownOne, Depth+1))
1331 return true;
1332 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001333
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001334 // If the sign bit of the input is known set or clear, then we know the
1335 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001336
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001337 // If the input sign bit is known zero, or if the NewBits are not demanded
1338 // convert this into a zero extension.
1339 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1340 // Convert to ZExt cast
Chris Lattnerab2f9132007-03-04 23:16:36 +00001341 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001342 return UpdateValueUsesWith(I, NewCast);
1343 } else if (KnownOne & InSignBit) { // Input sign bit known set
1344 KnownOne |= NewBits;
1345 KnownZero &= ~NewBits;
1346 } else { // Input sign bit unknown
1347 KnownZero &= ~NewBits;
1348 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001349 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001350 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001351 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001352 case Instruction::Add:
1353 // If there is a constant on the RHS, there are a variety of xformations
1354 // we can do.
1355 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1356 // If null, this should be simplified elsewhere. Some of the xforms here
1357 // won't work if the RHS is zero.
1358 if (RHS->isNullValue())
1359 break;
1360
1361 // Figure out what the input bits are. If the top bits of the and result
1362 // are not demanded, then the add doesn't demand them from its input
1363 // either.
1364
1365 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001366 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001367 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1368
1369 // If the top bit of the output is demanded, demand everything from the
1370 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001371 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001372
1373 // Find information about known zero/one bits in the input.
1374 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1375 KnownZero2, KnownOne2, Depth+1))
1376 return true;
1377
1378 // If the RHS of the add has bits set that can't affect the input, reduce
1379 // the constant.
1380 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1381 return UpdateValueUsesWith(I, I);
1382
1383 // Avoid excess work.
1384 if (KnownZero2 == 0 && KnownOne2 == 0)
1385 break;
1386
1387 // Turn it into OR if input bits are zero.
1388 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1389 Instruction *Or =
1390 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1391 I->getName());
1392 InsertNewInstBefore(Or, *I);
1393 return UpdateValueUsesWith(I, Or);
1394 }
1395
1396 // We can say something about the output known-zero and known-one bits,
1397 // depending on potential carries from the input constant and the
1398 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1399 // bits set and the RHS constant is 0x01001, then we know we have a known
1400 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1401
1402 // To compute this, we first compute the potential carry bits. These are
1403 // the bits which may be modified. I'm not aware of a better way to do
1404 // this scan.
1405 uint64_t RHSVal = RHS->getZExtValue();
1406
1407 bool CarryIn = false;
1408 uint64_t CarryBits = 0;
1409 uint64_t CurBit = 1;
1410 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1411 // Record the current carry in.
1412 if (CarryIn) CarryBits |= CurBit;
1413
1414 bool CarryOut;
1415
1416 // This bit has a carry out unless it is "zero + zero" or
1417 // "zero + anything" with no carry in.
1418 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1419 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1420 } else if (!CarryIn &&
1421 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1422 CarryOut = false; // 0 + anything has no carry out if no carry in.
1423 } else {
1424 // Otherwise, we have to assume we have a carry out.
1425 CarryOut = true;
1426 }
1427
1428 // This stage's carry out becomes the next stage's carry-in.
1429 CarryIn = CarryOut;
1430 }
1431
1432 // Now that we know which bits have carries, compute the known-1/0 sets.
1433
1434 // Bits are known one if they are known zero in one operand and one in the
1435 // other, and there is no input carry.
1436 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1437
1438 // Bits are known zero if they are known zero in both operands and there
1439 // is no input carry.
1440 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner5fdded12007-03-05 00:02:29 +00001441 } else {
1442 // If the high-bits of this ADD are not demanded, then it does not demand
1443 // the high bits of its LHS or RHS.
1444 if ((DemandedMask & VTy->getSignBit()) == 0) {
1445 // Right fill the mask of bits for this ADD to demand the most
1446 // significant bit and all those below it.
1447 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1448 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1449 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1450 KnownZero2, KnownOne2, Depth+1))
1451 return true;
1452 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1453 KnownZero2, KnownOne2, Depth+1))
1454 return true;
1455 }
1456 }
1457 break;
1458 case Instruction::Sub:
1459 // If the high-bits of this SUB are not demanded, then it does not demand
1460 // the high bits of its LHS or RHS.
1461 if ((DemandedMask & VTy->getSignBit()) == 0) {
1462 // Right fill the mask of bits for this SUB to demand the most
1463 // significant bit and all those below it.
1464 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1465 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1466 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1467 KnownZero2, KnownOne2, Depth+1))
1468 return true;
1469 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1470 KnownZero2, KnownOne2, Depth+1))
1471 return true;
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001472 }
1473 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001474 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001475 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1476 uint64_t ShiftAmt = SA->getZExtValue();
1477 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001478 KnownZero, KnownOne, Depth+1))
1479 return true;
1480 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001481 KnownZero <<= ShiftAmt;
1482 KnownOne <<= ShiftAmt;
1483 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001484 }
Chris Lattner2590e512006-02-07 06:56:34 +00001485 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001486 case Instruction::LShr:
1487 // For a logical shift right
1488 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1489 unsigned ShiftAmt = SA->getZExtValue();
1490
1491 // Compute the new bits that are at the top now.
1492 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001493 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1494 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001495 // Unsigned shift right.
1496 if (SimplifyDemandedBits(I->getOperand(0),
1497 (DemandedMask << ShiftAmt) & TypeMask,
1498 KnownZero, KnownOne, Depth+1))
1499 return true;
1500 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1501 KnownZero &= TypeMask;
1502 KnownOne &= TypeMask;
1503 KnownZero >>= ShiftAmt;
1504 KnownOne >>= ShiftAmt;
1505 KnownZero |= HighBits; // high bits known zero.
1506 }
1507 break;
1508 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001509 // If this is an arithmetic shift right and only the low-bit is set, we can
1510 // always convert this into a logical shr, even if the shift amount is
1511 // variable. The low bit of the shift cannot be an input sign bit unless
1512 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001513 if (DemandedMask == 1) {
1514 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001515 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001516 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001517 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001518 return UpdateValueUsesWith(I, NewVal);
1519 }
1520
Reid Spencere0fc4df2006-10-20 07:07:24 +00001521 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1522 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001523
1524 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001525 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001526 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1527 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001528 // Signed shift right.
1529 if (SimplifyDemandedBits(I->getOperand(0),
1530 (DemandedMask << ShiftAmt) & TypeMask,
1531 KnownZero, KnownOne, Depth+1))
1532 return true;
1533 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1534 KnownZero &= TypeMask;
1535 KnownOne &= TypeMask;
1536 KnownZero >>= ShiftAmt;
1537 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001538
Reid Spencerfdff9382006-11-08 06:47:33 +00001539 // Handle the sign bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001540 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00001541 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001542
Reid Spencerfdff9382006-11-08 06:47:33 +00001543 // If the input sign bit is known to be zero, or if none of the top bits
1544 // are demanded, turn this into an unsigned shift right.
1545 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1546 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001547 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001548 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001549 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1550 return UpdateValueUsesWith(I, NewVal);
1551 } else if (KnownOne & SignBit) { // New bits are known one.
1552 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001553 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001554 }
Chris Lattner2590e512006-02-07 06:56:34 +00001555 break;
1556 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001557
1558 // If the client is only demanding bits that we know, return the known
1559 // constant.
1560 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001561 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001562 return false;
1563}
1564
Reid Spencer1791f232007-03-12 17:25:59 +00001565/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1566/// value based on the demanded bits. When this function is called, it is known
1567/// that only the bits set in DemandedMask of the result of V are ever used
1568/// downstream. Consequently, depending on the mask and V, it may be possible
1569/// to replace V with a constant or one of its operands. In such cases, this
1570/// function does the replacement and returns true. In all other cases, it
1571/// returns false after analyzing the expression and setting KnownOne and known
1572/// to be one in the expression. KnownZero contains all the bits that are known
1573/// to be zero in the expression. These are provided to potentially allow the
1574/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1575/// the expression. KnownOne and KnownZero always follow the invariant that
1576/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1577/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1578/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1579/// and KnownOne must all be the same.
1580bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1581 APInt& KnownZero, APInt& KnownOne,
1582 unsigned Depth) {
1583 assert(V != 0 && "Null pointer of Value???");
1584 assert(Depth <= 6 && "Limit Search Depth");
1585 uint32_t BitWidth = DemandedMask.getBitWidth();
1586 const IntegerType *VTy = cast<IntegerType>(V->getType());
1587 assert(VTy->getBitWidth() == BitWidth &&
1588 KnownZero.getBitWidth() == BitWidth &&
1589 KnownOne.getBitWidth() == BitWidth &&
1590 "Value *V, DemandedMask, KnownZero and KnownOne \
1591 must have same BitWidth");
1592 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1593 // We know all of the bits for a constant!
1594 KnownOne = CI->getValue() & DemandedMask;
1595 KnownZero = ~KnownOne & DemandedMask;
1596 return false;
1597 }
1598
1599 //KnownZero.clear();
1600 //KnownOne.clear();
1601 if (!V->hasOneUse()) { // Other users may use these bits.
1602 if (Depth != 0) { // Not at the root.
1603 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1604 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1605 return false;
1606 }
1607 // If this is the root being simplified, allow it to have multiple uses,
1608 // just set the DemandedMask to all bits.
1609 DemandedMask = APInt::getAllOnesValue(BitWidth);
1610 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1611 if (V != UndefValue::get(VTy))
1612 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1613 return false;
1614 } else if (Depth == 6) { // Limit search depth.
1615 return false;
1616 }
1617
1618 Instruction *I = dyn_cast<Instruction>(V);
1619 if (!I) return false; // Only analyze instructions.
1620
1621 DemandedMask &= APInt::getAllOnesValue(BitWidth);
1622
1623 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1624 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1625 switch (I->getOpcode()) {
1626 default: break;
1627 case Instruction::And:
1628 // If either the LHS or the RHS are Zero, the result is zero.
1629 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1630 RHSKnownZero, RHSKnownOne, Depth+1))
1631 return true;
1632 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1633 "Bits known to be one AND zero?");
1634
1635 // If something is known zero on the RHS, the bits aren't demanded on the
1636 // LHS.
1637 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1638 LHSKnownZero, LHSKnownOne, Depth+1))
1639 return true;
1640 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1641 "Bits known to be one AND zero?");
1642
1643 // If all of the demanded bits are known 1 on one side, return the other.
1644 // These bits cannot contribute to the result of the 'and'.
1645 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1646 (DemandedMask & ~LHSKnownZero))
1647 return UpdateValueUsesWith(I, I->getOperand(0));
1648 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1649 (DemandedMask & ~RHSKnownZero))
1650 return UpdateValueUsesWith(I, I->getOperand(1));
1651
1652 // If all of the demanded bits in the inputs are known zeros, return zero.
1653 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1654 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1655
1656 // If the RHS is a constant, see if we can simplify it.
1657 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1658 return UpdateValueUsesWith(I, I);
1659
1660 // Output known-1 bits are only known if set in both the LHS & RHS.
1661 RHSKnownOne &= LHSKnownOne;
1662 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1663 RHSKnownZero |= LHSKnownZero;
1664 break;
1665 case Instruction::Or:
1666 // If either the LHS or the RHS are One, the result is One.
1667 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1668 RHSKnownZero, RHSKnownOne, Depth+1))
1669 return true;
1670 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1671 "Bits known to be one AND zero?");
1672 // If something is known one on the RHS, the bits aren't demanded on the
1673 // LHS.
1674 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1675 LHSKnownZero, LHSKnownOne, Depth+1))
1676 return true;
1677 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1678 "Bits known to be one AND zero?");
1679
1680 // If all of the demanded bits are known zero on one side, return the other.
1681 // These bits cannot contribute to the result of the 'or'.
1682 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1683 (DemandedMask & ~LHSKnownOne))
1684 return UpdateValueUsesWith(I, I->getOperand(0));
1685 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1686 (DemandedMask & ~RHSKnownOne))
1687 return UpdateValueUsesWith(I, I->getOperand(1));
1688
1689 // If all of the potentially set bits on one side are known to be set on
1690 // the other side, just use the 'other' side.
1691 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1692 (DemandedMask & (~RHSKnownZero)))
1693 return UpdateValueUsesWith(I, I->getOperand(0));
1694 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1695 (DemandedMask & (~LHSKnownZero)))
1696 return UpdateValueUsesWith(I, I->getOperand(1));
1697
1698 // If the RHS is a constant, see if we can simplify it.
1699 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1700 return UpdateValueUsesWith(I, I);
1701
1702 // Output known-0 bits are only known if clear in both the LHS & RHS.
1703 RHSKnownZero &= LHSKnownZero;
1704 // Output known-1 are known to be set if set in either the LHS | RHS.
1705 RHSKnownOne |= LHSKnownOne;
1706 break;
1707 case Instruction::Xor: {
1708 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1709 RHSKnownZero, RHSKnownOne, Depth+1))
1710 return true;
1711 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1712 "Bits known to be one AND zero?");
1713 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1714 LHSKnownZero, LHSKnownOne, Depth+1))
1715 return true;
1716 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1717 "Bits known to be one AND zero?");
1718
1719 // If all of the demanded bits are known zero on one side, return the other.
1720 // These bits cannot contribute to the result of the 'xor'.
1721 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1722 return UpdateValueUsesWith(I, I->getOperand(0));
1723 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1724 return UpdateValueUsesWith(I, I->getOperand(1));
1725
1726 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1727 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1728 (RHSKnownOne & LHSKnownOne);
1729 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1730 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1731 (RHSKnownOne & LHSKnownZero);
1732
1733 // If all of the demanded bits are known to be zero on one side or the
1734 // other, turn this into an *inclusive* or.
1735 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1736 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1737 Instruction *Or =
1738 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1739 I->getName());
1740 InsertNewInstBefore(Or, *I);
1741 return UpdateValueUsesWith(I, Or);
1742 }
1743
1744 // If all of the demanded bits on one side are known, and all of the set
1745 // bits on that side are also known to be set on the other side, turn this
1746 // into an AND, as we know the bits will be cleared.
1747 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1748 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1749 // all known
1750 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1751 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1752 Instruction *And =
1753 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1754 InsertNewInstBefore(And, *I);
1755 return UpdateValueUsesWith(I, And);
1756 }
1757 }
1758
1759 // If the RHS is a constant, see if we can simplify it.
1760 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1761 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1762 return UpdateValueUsesWith(I, I);
1763
1764 RHSKnownZero = KnownZeroOut;
1765 RHSKnownOne = KnownOneOut;
1766 break;
1767 }
1768 case Instruction::Select:
1769 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1770 RHSKnownZero, RHSKnownOne, Depth+1))
1771 return true;
1772 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1773 LHSKnownZero, LHSKnownOne, Depth+1))
1774 return true;
1775 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1776 "Bits known to be one AND zero?");
1777 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1778 "Bits known to be one AND zero?");
1779
1780 // If the operands are constants, see if we can simplify them.
1781 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1782 return UpdateValueUsesWith(I, I);
1783 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1784 return UpdateValueUsesWith(I, I);
1785
1786 // Only known if known in both the LHS and RHS.
1787 RHSKnownOne &= LHSKnownOne;
1788 RHSKnownZero &= LHSKnownZero;
1789 break;
1790 case Instruction::Trunc: {
1791 uint32_t truncBf =
1792 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1793 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1794 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1795 return true;
1796 DemandedMask.trunc(BitWidth);
1797 RHSKnownZero.trunc(BitWidth);
1798 RHSKnownOne.trunc(BitWidth);
1799 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1800 "Bits known to be one AND zero?");
1801 break;
1802 }
1803 case Instruction::BitCast:
1804 if (!I->getOperand(0)->getType()->isInteger())
1805 return false;
1806
1807 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1808 RHSKnownZero, RHSKnownOne, Depth+1))
1809 return true;
1810 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1811 "Bits known to be one AND zero?");
1812 break;
1813 case Instruction::ZExt: {
1814 // Compute the bits in the result that are not present in the input.
1815 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1816 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1817
1818 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1819 uint32_t zextBf = SrcTy->getBitWidth();
1820 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1821 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1822 return true;
1823 DemandedMask.zext(BitWidth);
1824 RHSKnownZero.zext(BitWidth);
1825 RHSKnownOne.zext(BitWidth);
1826 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1827 "Bits known to be one AND zero?");
1828 // The top bits are known to be zero.
1829 RHSKnownZero |= NewBits;
1830 break;
1831 }
1832 case Instruction::SExt: {
1833 // Compute the bits in the result that are not present in the input.
1834 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1835 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1836
1837 // Get the sign bit for the source type
1838 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1839 InSignBit.zext(BitWidth);
1840 APInt InputDemandedBits = DemandedMask &
1841 SrcTy->getMask().zext(BitWidth);
1842
1843 // If any of the sign extended bits are demanded, we know that the sign
1844 // bit is demanded.
1845 if ((NewBits & DemandedMask) != 0)
1846 InputDemandedBits |= InSignBit;
1847
1848 uint32_t sextBf = SrcTy->getBitWidth();
1849 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1850 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1851 return true;
1852 InputDemandedBits.zext(BitWidth);
1853 RHSKnownZero.zext(BitWidth);
1854 RHSKnownOne.zext(BitWidth);
1855 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1856 "Bits known to be one AND zero?");
1857
1858 // If the sign bit of the input is known set or clear, then we know the
1859 // top bits of the result.
1860
1861 // If the input sign bit is known zero, or if the NewBits are not demanded
1862 // convert this into a zero extension.
1863 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1864 {
1865 // Convert to ZExt cast
1866 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1867 return UpdateValueUsesWith(I, NewCast);
1868 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1869 RHSKnownOne |= NewBits;
1870 RHSKnownZero &= ~NewBits;
1871 } else { // Input sign bit unknown
1872 RHSKnownZero &= ~NewBits;
1873 RHSKnownOne &= ~NewBits;
1874 }
1875 break;
1876 }
1877 case Instruction::Add: {
1878 // Figure out what the input bits are. If the top bits of the and result
1879 // are not demanded, then the add doesn't demand them from its input
1880 // either.
1881 unsigned NLZ = DemandedMask.countLeadingZeros();
1882
1883 // If there is a constant on the RHS, there are a variety of xformations
1884 // we can do.
1885 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1886 // If null, this should be simplified elsewhere. Some of the xforms here
1887 // won't work if the RHS is zero.
1888 if (RHS->isZero())
1889 break;
1890
1891 // If the top bit of the output is demanded, demand everything from the
1892 // input. Otherwise, we demand all the input bits except NLZ top bits.
1893 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1894
1895 // Find information about known zero/one bits in the input.
1896 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1897 LHSKnownZero, LHSKnownOne, Depth+1))
1898 return true;
1899
1900 // If the RHS of the add has bits set that can't affect the input, reduce
1901 // the constant.
1902 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1903 return UpdateValueUsesWith(I, I);
1904
1905 // Avoid excess work.
1906 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1907 break;
1908
1909 // Turn it into OR if input bits are zero.
1910 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1911 Instruction *Or =
1912 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1913 I->getName());
1914 InsertNewInstBefore(Or, *I);
1915 return UpdateValueUsesWith(I, Or);
1916 }
1917
1918 // We can say something about the output known-zero and known-one bits,
1919 // depending on potential carries from the input constant and the
1920 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1921 // bits set and the RHS constant is 0x01001, then we know we have a known
1922 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1923
1924 // To compute this, we first compute the potential carry bits. These are
1925 // the bits which may be modified. I'm not aware of a better way to do
1926 // this scan.
1927 APInt RHSVal(RHS->getValue());
1928
1929 bool CarryIn = false;
1930 APInt CarryBits(BitWidth, 0);
1931 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1932 *RHSRawVal = RHSVal.getRawData();
1933 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1934 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1935 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1936 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1937 if (AddVal < RHSRawVal[i])
1938 CarryIn = true;
1939 else
1940 CarryIn = false;
1941 CarryBits.setWordToValue(i, WordCarryBits);
1942 }
1943
1944 // Now that we know which bits have carries, compute the known-1/0 sets.
1945
1946 // Bits are known one if they are known zero in one operand and one in the
1947 // other, and there is no input carry.
1948 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1949 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1950
1951 // Bits are known zero if they are known zero in both operands and there
1952 // is no input carry.
1953 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1954 } else {
1955 // If the high-bits of this ADD are not demanded, then it does not demand
1956 // the high bits of its LHS or RHS.
1957 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1958 // Right fill the mask of bits for this ADD to demand the most
1959 // significant bit and all those below it.
1960 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1961 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1962 LHSKnownZero, LHSKnownOne, Depth+1))
1963 return true;
1964 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1965 LHSKnownZero, LHSKnownOne, Depth+1))
1966 return true;
1967 }
1968 }
1969 break;
1970 }
1971 case Instruction::Sub:
1972 // If the high-bits of this SUB are not demanded, then it does not demand
1973 // the high bits of its LHS or RHS.
1974 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1975 // Right fill the mask of bits for this SUB to demand the most
1976 // significant bit and all those below it.
1977 unsigned NLZ = DemandedMask.countLeadingZeros();
1978 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1979 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1980 LHSKnownZero, LHSKnownOne, Depth+1))
1981 return true;
1982 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1983 LHSKnownZero, LHSKnownOne, Depth+1))
1984 return true;
1985 }
1986 break;
1987 case Instruction::Shl:
1988 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1989 uint64_t ShiftAmt = SA->getZExtValue();
1990 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1991 RHSKnownZero, RHSKnownOne, Depth+1))
1992 return true;
1993 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1994 "Bits known to be one AND zero?");
1995 RHSKnownZero <<= ShiftAmt;
1996 RHSKnownOne <<= ShiftAmt;
1997 // low bits known zero.
Zhou Shengebe634e2007-03-13 06:40:59 +00001998 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001999 }
2000 break;
2001 case Instruction::LShr:
2002 // For a logical shift right
2003 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2004 unsigned ShiftAmt = SA->getZExtValue();
2005
2006 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2007 // Unsigned shift right.
2008 if (SimplifyDemandedBits(I->getOperand(0),
2009 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2010 RHSKnownZero, RHSKnownOne, Depth+1))
2011 return true;
2012 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2013 "Bits known to be one AND zero?");
2014 // Compute the new bits that are at the top now.
Zhou Shengebe634e2007-03-13 06:40:59 +00002015 APInt HighBits(APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth).shl(
Reid Spencer1791f232007-03-12 17:25:59 +00002016 BitWidth - ShiftAmt));
2017 RHSKnownZero &= TypeMask;
2018 RHSKnownOne &= TypeMask;
2019 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2020 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2021 RHSKnownZero |= HighBits; // high bits known zero.
2022 }
2023 break;
2024 case Instruction::AShr:
2025 // If this is an arithmetic shift right and only the low-bit is set, we can
2026 // always convert this into a logical shr, even if the shift amount is
2027 // variable. The low bit of the shift cannot be an input sign bit unless
2028 // the shift amount is >= the size of the datatype, which is undefined.
2029 if (DemandedMask == 1) {
2030 // Perform the logical shift right.
2031 Value *NewVal = BinaryOperator::createLShr(
2032 I->getOperand(0), I->getOperand(1), I->getName());
2033 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2034 return UpdateValueUsesWith(I, NewVal);
2035 }
2036
2037 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2038 unsigned ShiftAmt = SA->getZExtValue();
2039
2040 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2041 // Signed shift right.
2042 if (SimplifyDemandedBits(I->getOperand(0),
2043 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2044 RHSKnownZero, RHSKnownOne, Depth+1))
2045 return true;
2046 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2047 "Bits known to be one AND zero?");
2048 // Compute the new bits that are at the top now.
Zhou Shengebe634e2007-03-13 06:40:59 +00002049 APInt HighBits(APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth).shl(
Reid Spencer1791f232007-03-12 17:25:59 +00002050 BitWidth - ShiftAmt));
2051 RHSKnownZero &= TypeMask;
2052 RHSKnownOne &= TypeMask;
2053 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2054 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2055
2056 // Handle the sign bits.
2057 APInt SignBit(APInt::getSignBit(BitWidth));
2058 // Adjust to where it is now in the mask.
2059 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
2060
2061 // If the input sign bit is known to be zero, or if none of the top bits
2062 // are demanded, turn this into an unsigned shift right.
2063 if ((RHSKnownZero & SignBit) != 0 ||
2064 (HighBits & ~DemandedMask) == HighBits) {
2065 // Perform the logical shift right.
2066 Value *NewVal = BinaryOperator::createLShr(
2067 I->getOperand(0), SA, I->getName());
2068 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2069 return UpdateValueUsesWith(I, NewVal);
2070 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2071 RHSKnownOne |= HighBits;
2072 }
2073 }
2074 break;
2075 }
2076
2077 // If the client is only demanding bits that we know, return the known
2078 // constant.
2079 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2080 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2081 return false;
2082}
2083
Chris Lattner2deeaea2006-10-05 06:55:50 +00002084
2085/// SimplifyDemandedVectorElts - The specified value producecs a vector with
2086/// 64 or fewer elements. DemandedElts contains the set of elements that are
2087/// actually used by the caller. This method analyzes which elements of the
2088/// operand are undef and returns that information in UndefElts.
2089///
2090/// If the information about demanded elements can be used to simplify the
2091/// operation, the operation is simplified, then the resultant value is
2092/// returned. This returns null if no change was made.
2093Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2094 uint64_t &UndefElts,
2095 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002096 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002097 assert(VWidth <= 64 && "Vector too wide to analyze!");
2098 uint64_t EltMask = ~0ULL >> (64-VWidth);
2099 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2100 "Invalid DemandedElts!");
2101
2102 if (isa<UndefValue>(V)) {
2103 // If the entire vector is undefined, just return this info.
2104 UndefElts = EltMask;
2105 return 0;
2106 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2107 UndefElts = EltMask;
2108 return UndefValue::get(V->getType());
2109 }
2110
2111 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002112 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2113 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002114 Constant *Undef = UndefValue::get(EltTy);
2115
2116 std::vector<Constant*> Elts;
2117 for (unsigned i = 0; i != VWidth; ++i)
2118 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
2119 Elts.push_back(Undef);
2120 UndefElts |= (1ULL << i);
2121 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
2122 Elts.push_back(Undef);
2123 UndefElts |= (1ULL << i);
2124 } else { // Otherwise, defined.
2125 Elts.push_back(CP->getOperand(i));
2126 }
2127
2128 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002129 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00002130 return NewCP != CP ? NewCP : 0;
2131 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002132 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00002133 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002134 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002135 Constant *Zero = Constant::getNullValue(EltTy);
2136 Constant *Undef = UndefValue::get(EltTy);
2137 std::vector<Constant*> Elts;
2138 for (unsigned i = 0; i != VWidth; ++i)
2139 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2140 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002141 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00002142 }
2143
2144 if (!V->hasOneUse()) { // Other users may use these bits.
2145 if (Depth != 0) { // Not at the root.
2146 // TODO: Just compute the UndefElts information recursively.
2147 return false;
2148 }
2149 return false;
2150 } else if (Depth == 10) { // Limit search depth.
2151 return false;
2152 }
2153
2154 Instruction *I = dyn_cast<Instruction>(V);
2155 if (!I) return false; // Only analyze instructions.
2156
2157 bool MadeChange = false;
2158 uint64_t UndefElts2;
2159 Value *TmpV;
2160 switch (I->getOpcode()) {
2161 default: break;
2162
2163 case Instruction::InsertElement: {
2164 // If this is a variable index, we don't know which element it overwrites.
2165 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002166 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00002167 if (Idx == 0) {
2168 // Note that we can't propagate undef elt info, because we don't know
2169 // which elt is getting updated.
2170 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2171 UndefElts2, Depth+1);
2172 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2173 break;
2174 }
2175
2176 // If this is inserting an element that isn't demanded, remove this
2177 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002178 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002179 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2180 return AddSoonDeadInstToWorklist(*I, 0);
2181
2182 // Otherwise, the element inserted overwrites whatever was there, so the
2183 // input demanded set is simpler than the output set.
2184 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2185 DemandedElts & ~(1ULL << IdxNo),
2186 UndefElts, Depth+1);
2187 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2188
2189 // The inserted element is defined.
2190 UndefElts |= 1ULL << IdxNo;
2191 break;
2192 }
2193
2194 case Instruction::And:
2195 case Instruction::Or:
2196 case Instruction::Xor:
2197 case Instruction::Add:
2198 case Instruction::Sub:
2199 case Instruction::Mul:
2200 // div/rem demand all inputs, because they don't want divide by zero.
2201 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2202 UndefElts, Depth+1);
2203 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2204 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2205 UndefElts2, Depth+1);
2206 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2207
2208 // Output elements are undefined if both are undefined. Consider things
2209 // like undef&0. The result is known zero, not undef.
2210 UndefElts &= UndefElts2;
2211 break;
2212
2213 case Instruction::Call: {
2214 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2215 if (!II) break;
2216 switch (II->getIntrinsicID()) {
2217 default: break;
2218
2219 // Binary vector operations that work column-wise. A dest element is a
2220 // function of the corresponding input elements from the two inputs.
2221 case Intrinsic::x86_sse_sub_ss:
2222 case Intrinsic::x86_sse_mul_ss:
2223 case Intrinsic::x86_sse_min_ss:
2224 case Intrinsic::x86_sse_max_ss:
2225 case Intrinsic::x86_sse2_sub_sd:
2226 case Intrinsic::x86_sse2_mul_sd:
2227 case Intrinsic::x86_sse2_min_sd:
2228 case Intrinsic::x86_sse2_max_sd:
2229 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2230 UndefElts, Depth+1);
2231 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2232 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2233 UndefElts2, Depth+1);
2234 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2235
2236 // If only the low elt is demanded and this is a scalarizable intrinsic,
2237 // scalarize it now.
2238 if (DemandedElts == 1) {
2239 switch (II->getIntrinsicID()) {
2240 default: break;
2241 case Intrinsic::x86_sse_sub_ss:
2242 case Intrinsic::x86_sse_mul_ss:
2243 case Intrinsic::x86_sse2_sub_sd:
2244 case Intrinsic::x86_sse2_mul_sd:
2245 // TODO: Lower MIN/MAX/ABS/etc
2246 Value *LHS = II->getOperand(1);
2247 Value *RHS = II->getOperand(2);
2248 // Extract the element as scalars.
2249 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2250 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2251
2252 switch (II->getIntrinsicID()) {
2253 default: assert(0 && "Case stmts out of sync!");
2254 case Intrinsic::x86_sse_sub_ss:
2255 case Intrinsic::x86_sse2_sub_sd:
2256 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2257 II->getName()), *II);
2258 break;
2259 case Intrinsic::x86_sse_mul_ss:
2260 case Intrinsic::x86_sse2_mul_sd:
2261 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2262 II->getName()), *II);
2263 break;
2264 }
2265
2266 Instruction *New =
2267 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2268 II->getName());
2269 InsertNewInstBefore(New, *II);
2270 AddSoonDeadInstToWorklist(*II, 0);
2271 return New;
2272 }
2273 }
2274
2275 // Output elements are undefined if both are undefined. Consider things
2276 // like undef&0. The result is known zero, not undef.
2277 UndefElts &= UndefElts2;
2278 break;
2279 }
2280 break;
2281 }
2282 }
2283 return MadeChange ? I : 0;
2284}
2285
Reid Spencer266e42b2006-12-23 06:05:41 +00002286/// @returns true if the specified compare instruction is
2287/// true when both operands are equal...
2288/// @brief Determine if the ICmpInst returns true if both operands are equal
2289static bool isTrueWhenEqual(ICmpInst &ICI) {
2290 ICmpInst::Predicate pred = ICI.getPredicate();
2291 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2292 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2293 pred == ICmpInst::ICMP_SLE;
2294}
2295
Chris Lattnerb8b97502003-08-13 19:01:45 +00002296/// AssociativeOpt - Perform an optimization on an associative operator. This
2297/// function is designed to check a chain of associative operators for a
2298/// potential to apply a certain optimization. Since the optimization may be
2299/// applicable if the expression was reassociated, this checks the chain, then
2300/// reassociates the expression as necessary to expose the optimization
2301/// opportunity. This makes use of a special Functor, which must define
2302/// 'shouldApply' and 'apply' methods.
2303///
2304template<typename Functor>
2305Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2306 unsigned Opcode = Root.getOpcode();
2307 Value *LHS = Root.getOperand(0);
2308
2309 // Quick check, see if the immediate LHS matches...
2310 if (F.shouldApply(LHS))
2311 return F.apply(Root);
2312
2313 // Otherwise, if the LHS is not of the same opcode as the root, return.
2314 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002315 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002316 // Should we apply this transform to the RHS?
2317 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2318
2319 // If not to the RHS, check to see if we should apply to the LHS...
2320 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2321 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2322 ShouldApply = true;
2323 }
2324
2325 // If the functor wants to apply the optimization to the RHS of LHSI,
2326 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2327 if (ShouldApply) {
2328 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002329
Chris Lattnerb8b97502003-08-13 19:01:45 +00002330 // Now all of the instructions are in the current basic block, go ahead
2331 // and perform the reassociation.
2332 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2333
2334 // First move the selected RHS to the LHS of the root...
2335 Root.setOperand(0, LHSI->getOperand(1));
2336
2337 // Make what used to be the LHS of the root be the user of the root...
2338 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00002339 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00002340 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2341 return 0;
2342 }
Chris Lattner284d3b02004-04-16 18:08:07 +00002343 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00002344 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00002345 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2346 BasicBlock::iterator ARI = &Root; ++ARI;
2347 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2348 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00002349
2350 // Now propagate the ExtraOperand down the chain of instructions until we
2351 // get to LHSI.
2352 while (TmpLHSI != LHSI) {
2353 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00002354 // Move the instruction to immediately before the chain we are
2355 // constructing to avoid breaking dominance properties.
2356 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2357 BB->getInstList().insert(ARI, NextLHSI);
2358 ARI = NextLHSI;
2359
Chris Lattnerb8b97502003-08-13 19:01:45 +00002360 Value *NextOp = NextLHSI->getOperand(1);
2361 NextLHSI->setOperand(1, ExtraOperand);
2362 TmpLHSI = NextLHSI;
2363 ExtraOperand = NextOp;
2364 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002365
Chris Lattnerb8b97502003-08-13 19:01:45 +00002366 // Now that the instructions are reassociated, have the functor perform
2367 // the transformation...
2368 return F.apply(Root);
2369 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002370
Chris Lattnerb8b97502003-08-13 19:01:45 +00002371 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2372 }
2373 return 0;
2374}
2375
2376
2377// AddRHS - Implements: X + X --> X << 1
2378struct AddRHS {
2379 Value *RHS;
2380 AddRHS(Value *rhs) : RHS(rhs) {}
2381 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2382 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00002383 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00002384 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002385 }
2386};
2387
2388// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2389// iff C1&C2 == 0
2390struct AddMaskingAnd {
2391 Constant *C2;
2392 AddMaskingAnd(Constant *c) : C2(c) {}
2393 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00002394 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002395 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002396 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00002397 }
2398 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002399 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002400 }
2401};
2402
Chris Lattner86102b82005-01-01 16:22:27 +00002403static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00002404 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002405 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002406 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002407 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002408
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002409 return IC->InsertNewInstBefore(CastInst::create(
2410 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00002411 }
2412
Chris Lattner183b3362004-04-09 19:05:30 +00002413 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00002414 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2415 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002416
Chris Lattner183b3362004-04-09 19:05:30 +00002417 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2418 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00002419 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2420 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00002421 }
2422
2423 Value *Op0 = SO, *Op1 = ConstOperand;
2424 if (!ConstIsRHS)
2425 std::swap(Op0, Op1);
2426 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00002427 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2428 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00002429 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2430 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2431 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002432 else {
Chris Lattner183b3362004-04-09 19:05:30 +00002433 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002434 abort();
2435 }
Chris Lattner86102b82005-01-01 16:22:27 +00002436 return IC->InsertNewInstBefore(New, I);
2437}
2438
2439// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2440// constant as the other operand, try to fold the binary operator into the
2441// select arguments. This also works for Cast instructions, which obviously do
2442// not have a second operand.
2443static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2444 InstCombiner *IC) {
2445 // Don't modify shared select instructions
2446 if (!SI->hasOneUse()) return 0;
2447 Value *TV = SI->getOperand(1);
2448 Value *FV = SI->getOperand(2);
2449
2450 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00002451 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00002452 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00002453
Chris Lattner86102b82005-01-01 16:22:27 +00002454 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2455 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2456
2457 return new SelectInst(SI->getCondition(), SelectTrueVal,
2458 SelectFalseVal);
2459 }
2460 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00002461}
2462
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002463
2464/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2465/// node as operand #0, see if we can fold the instruction into the PHI (which
2466/// is only possible if all operands to the PHI are constants).
2467Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2468 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00002469 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00002470 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002471
Chris Lattner04689872006-09-09 22:02:56 +00002472 // Check to see if all of the operands of the PHI are constants. If there is
2473 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002474 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00002475 BasicBlock *NonConstBB = 0;
2476 for (unsigned i = 0; i != NumPHIValues; ++i)
2477 if (!isa<Constant>(PN->getIncomingValue(i))) {
2478 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002479 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00002480 NonConstBB = PN->getIncomingBlock(i);
2481
2482 // If the incoming non-constant value is in I's block, we have an infinite
2483 // loop.
2484 if (NonConstBB == I.getParent())
2485 return 0;
2486 }
2487
2488 // If there is exactly one non-constant value, we can insert a copy of the
2489 // operation in that block. However, if this is a critical edge, we would be
2490 // inserting the computation one some other paths (e.g. inside a loop). Only
2491 // do this if the pred block is unconditionally branching into the phi block.
2492 if (NonConstBB) {
2493 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2494 if (!BI || !BI->isUnconditional()) return 0;
2495 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002496
2497 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002498 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00002499 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002500 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002501 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002502
2503 // Next, add all of the operands to the PHI.
2504 if (I.getNumOperands() == 2) {
2505 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00002506 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002507 Value *InV;
2508 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002509 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2510 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2511 else
2512 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00002513 } else {
2514 assert(PN->getIncomingBlock(i) == NonConstBB);
2515 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2516 InV = BinaryOperator::create(BO->getOpcode(),
2517 PN->getIncomingValue(i), C, "phitmp",
2518 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00002519 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2520 InV = CmpInst::create(CI->getOpcode(),
2521 CI->getPredicate(),
2522 PN->getIncomingValue(i), C, "phitmp",
2523 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00002524 else
2525 assert(0 && "Unknown binop!");
2526
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002527 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002528 }
2529 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002530 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002531 } else {
2532 CastInst *CI = cast<CastInst>(&I);
2533 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00002534 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002535 Value *InV;
2536 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002537 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00002538 } else {
2539 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002540 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2541 I.getType(), "phitmp",
2542 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002543 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002544 }
2545 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002546 }
2547 }
2548 return ReplaceInstUsesWith(I, NewPN);
2549}
2550
Chris Lattner113f4f42002-06-25 16:13:24 +00002551Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002552 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002553 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002554
Chris Lattnercf4a9962004-04-10 22:01:55 +00002555 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00002556 // X + undef -> undef
2557 if (isa<UndefValue>(RHS))
2558 return ReplaceInstUsesWith(I, RHS);
2559
Chris Lattnercf4a9962004-04-10 22:01:55 +00002560 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002561 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002562 if (RHSC->isNullValue())
2563 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002564 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2565 if (CFP->isExactlyValue(-0.0))
2566 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002567 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002568
Chris Lattnercf4a9962004-04-10 22:01:55 +00002569 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002570 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00002571 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00002572 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002573 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002574
2575 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2576 // (X & 254)+1 -> (X&254)|1
2577 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002578 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00002579 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002580 KnownZero, KnownOne))
2581 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00002582 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002583
2584 if (isa<PHINode>(LHS))
2585 if (Instruction *NV = FoldOpIntoPhi(I))
2586 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002587
Chris Lattner330628a2006-01-06 17:59:59 +00002588 ConstantInt *XorRHS = 0;
2589 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002590 if (isa<ConstantInt>(RHSC) &&
2591 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002592 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2593 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2594 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2595
2596 uint64_t C0080Val = 1ULL << 31;
2597 int64_t CFF80Val = -C0080Val;
2598 unsigned Size = 32;
2599 do {
2600 if (TySizeBits > Size) {
2601 bool Found = false;
2602 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2604 if (RHSSExt == CFF80Val) {
2605 if (XorRHS->getZExtValue() == C0080Val)
2606 Found = true;
2607 } else if (RHSZExt == C0080Val) {
2608 if (XorRHS->getSExtValue() == CFF80Val)
2609 Found = true;
2610 }
2611 if (Found) {
2612 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002613 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002614 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00002615 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002616 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002617 Size = 0; // Not a sign ext, but can't be any others either.
2618 goto FoundSExt;
2619 }
2620 }
2621 Size >>= 1;
2622 C0080Val >>= Size;
2623 CFF80Val >>= Size;
2624 } while (Size >= 8);
2625
2626FoundSExt:
2627 const Type *MiddleType = 0;
2628 switch (Size) {
2629 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00002630 case 32: MiddleType = Type::Int32Ty; break;
2631 case 16: MiddleType = Type::Int16Ty; break;
2632 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002633 }
2634 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002635 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002636 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002637 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002638 }
2639 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002640 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002641
Chris Lattnerb8b97502003-08-13 19:01:45 +00002642 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002643 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002644 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002645
2646 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2647 if (RHSI->getOpcode() == Instruction::Sub)
2648 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2649 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2650 }
2651 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2652 if (LHSI->getOpcode() == Instruction::Sub)
2653 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2654 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2655 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002656 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002657
Chris Lattner147e9752002-05-08 22:46:53 +00002658 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002659 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002660 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002661
2662 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002663 if (!isa<Constant>(RHS))
2664 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002665 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002666
Misha Brukmanb1c93172005-04-21 23:48:37 +00002667
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002668 ConstantInt *C2;
2669 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2670 if (X == RHS) // X*C + X --> X * (C+1)
2671 return BinaryOperator::createMul(RHS, AddOne(C2));
2672
2673 // X*C1 + X*C2 --> X * (C1+C2)
2674 ConstantInt *C1;
2675 if (X == dyn_castFoldableMul(RHS, C1))
2676 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002677 }
2678
2679 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002680 if (dyn_castFoldableMul(RHS, C2) == LHS)
2681 return BinaryOperator::createMul(LHS, AddOne(C2));
2682
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002683 // X + ~X --> -1 since ~X = -X-1
2684 if (dyn_castNotVal(LHS) == RHS ||
2685 dyn_castNotVal(RHS) == LHS)
2686 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2687
Chris Lattner57c8d992003-02-18 19:57:07 +00002688
Chris Lattnerb8b97502003-08-13 19:01:45 +00002689 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002690 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002691 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2692 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002693
Chris Lattnerb9cde762003-10-02 15:11:26 +00002694 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002695 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002696 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2697 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2698 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00002699 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00002700
Chris Lattnerbff91d92004-10-08 05:07:56 +00002701 // (X & FF00) + xx00 -> (X+xx00) & FF00
2702 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2703 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2704 if (Anded == CRHS) {
2705 // See if all bits from the first bit set in the Add RHS up are included
2706 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002707 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002708
2709 // Form a mask of all bits from the lowest bit added through the top.
2710 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00002711 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002712
2713 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002714 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002715
Chris Lattnerbff91d92004-10-08 05:07:56 +00002716 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2717 // Okay, the xform is safe. Insert the new add pronto.
2718 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2719 LHS->getName()), I);
2720 return BinaryOperator::createAnd(NewAdd, C2);
2721 }
2722 }
2723 }
2724
Chris Lattnerd4252a72004-07-30 07:50:03 +00002725 // Try to fold constant add into select arguments.
2726 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002727 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002728 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002729 }
2730
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002731 // add (cast *A to intptrtype) B ->
2732 // cast (GEP (cast *A to sbyte*) B) ->
2733 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002734 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002735 CastInst *CI = dyn_cast<CastInst>(LHS);
2736 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002737 if (!CI) {
2738 CI = dyn_cast<CastInst>(RHS);
2739 Other = LHS;
2740 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002741 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002742 (CI->getType()->getPrimitiveSizeInBits() ==
2743 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002744 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002745 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002746 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002747 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002748 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002749 }
2750 }
2751
Chris Lattner113f4f42002-06-25 16:13:24 +00002752 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002753}
2754
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002755// isSignBit - Return true if the value represented by the constant only has the
2756// highest order bit set.
2757static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002758 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00002759 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002760}
2761
Chris Lattner113f4f42002-06-25 16:13:24 +00002762Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002763 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002764
Chris Lattnere6794492002-08-12 21:17:25 +00002765 if (Op0 == Op1) // sub X, X -> 0
2766 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002767
Chris Lattnere6794492002-08-12 21:17:25 +00002768 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002769 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002770 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002771
Chris Lattner81a7a232004-10-16 18:11:37 +00002772 if (isa<UndefValue>(Op0))
2773 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2774 if (isa<UndefValue>(Op1))
2775 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2776
Chris Lattner8f2f5982003-11-05 01:06:05 +00002777 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2778 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002779 if (C->isAllOnesValue())
2780 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002781
Chris Lattner8f2f5982003-11-05 01:06:05 +00002782 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002783 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002784 if (match(Op1, m_Not(m_Value(X))))
2785 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002786 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00002787 // -(X >>u 31) -> (X >>s 31)
2788 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002789 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002790 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002791 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002792 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002793 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002794 if (CU->getZExtValue() ==
2795 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002796 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002797 return BinaryOperator::create(Instruction::AShr,
2798 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002799 }
2800 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002801 }
2802 else if (SI->getOpcode() == Instruction::AShr) {
2803 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2804 // Check to see if we are shifting out everything but the sign bit.
2805 if (CU->getZExtValue() ==
2806 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002807 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002808 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002809 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002810 }
2811 }
2812 }
Chris Lattner022167f2004-03-13 00:11:49 +00002813 }
Chris Lattner183b3362004-04-09 19:05:30 +00002814
2815 // Try to fold constant sub into select arguments.
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002817 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002818 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002819
2820 if (isa<PHINode>(Op0))
2821 if (Instruction *NV = FoldOpIntoPhi(I))
2822 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002823 }
2824
Chris Lattnera9be4492005-04-07 16:15:25 +00002825 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2826 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002827 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002828 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002829 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002830 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002831 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002832 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2833 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2834 // C1-(X+C2) --> (C1-C2)-X
2835 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2836 Op1I->getOperand(0));
2837 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002838 }
2839
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002840 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002841 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2842 // is not used by anyone else...
2843 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002844 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002845 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002846 // Swap the two operands of the subexpr...
2847 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2848 Op1I->setOperand(0, IIOp1);
2849 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002850
Chris Lattner3082c5a2003-02-18 19:28:33 +00002851 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002852 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002853 }
2854
2855 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2856 //
2857 if (Op1I->getOpcode() == Instruction::And &&
2858 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2859 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2860
Chris Lattner396dbfe2004-06-09 05:08:07 +00002861 Value *NewNot =
2862 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002863 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002864 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002865
Reid Spencer3c514952006-10-16 23:08:08 +00002866 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002867 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002868 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002869 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002870 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002871 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002872 ConstantExpr::getNeg(DivRHS));
2873
Chris Lattner57c8d992003-02-18 19:57:07 +00002874 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002875 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002876 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002877 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002878 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002879 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002880 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002881 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002882 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002883
Chris Lattner7a002fe2006-12-02 00:13:08 +00002884 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002885 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2886 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002887 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2888 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2889 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2890 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002891 } else if (Op0I->getOpcode() == Instruction::Sub) {
2892 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2893 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002894 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002895
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002896 ConstantInt *C1;
2897 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2898 if (X == Op1) { // X*C - X --> X * (C-1)
2899 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2900 return BinaryOperator::createMul(Op1, CP1);
2901 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002902
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002903 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2904 if (X == dyn_castFoldableMul(Op1, C2))
2905 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2906 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002907 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002908}
2909
Reid Spencer266e42b2006-12-23 06:05:41 +00002910/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002911/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002912static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2913 switch (pred) {
2914 case ICmpInst::ICMP_SLT:
2915 // True if LHS s< RHS and RHS == 0
2916 return RHS->isNullValue();
2917 case ICmpInst::ICMP_SLE:
2918 // True if LHS s<= RHS and RHS == -1
2919 return RHS->isAllOnesValue();
2920 case ICmpInst::ICMP_UGE:
2921 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2922 return RHS->getZExtValue() == (1ULL <<
2923 (RHS->getType()->getPrimitiveSizeInBits()-1));
2924 case ICmpInst::ICMP_UGT:
2925 // True if LHS u> RHS and RHS == high-bit-mask - 1
2926 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002927 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002928 default:
2929 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002930 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002931}
2932
Chris Lattner113f4f42002-06-25 16:13:24 +00002933Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002934 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002935 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002936
Chris Lattner81a7a232004-10-16 18:11:37 +00002937 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2939
Chris Lattnere6794492002-08-12 21:17:25 +00002940 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002941 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2942 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002943
2944 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002945 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002946 if (SI->getOpcode() == Instruction::Shl)
2947 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002948 return BinaryOperator::createMul(SI->getOperand(0),
2949 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002950
Chris Lattnercce81be2003-09-11 22:24:54 +00002951 if (CI->isNullValue())
2952 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2953 if (CI->equalsInt(1)) // X * 1 == X
2954 return ReplaceInstUsesWith(I, Op0);
2955 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002956 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002957
Reid Spencere0fc4df2006-10-20 07:07:24 +00002958 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002959 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2960 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002961 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002962 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002963 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002964 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002965 if (Op1F->isNullValue())
2966 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002967
Chris Lattner3082c5a2003-02-18 19:28:33 +00002968 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2969 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2970 if (Op1F->getValue() == 1.0)
2971 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2972 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002973
2974 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2975 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2976 isa<ConstantInt>(Op0I->getOperand(1))) {
2977 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2978 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2979 Op1, "tmp");
2980 InsertNewInstBefore(Add, I);
2981 Value *C1C2 = ConstantExpr::getMul(Op1,
2982 cast<Constant>(Op0I->getOperand(1)));
2983 return BinaryOperator::createAdd(Add, C1C2);
2984
2985 }
Chris Lattner183b3362004-04-09 19:05:30 +00002986
2987 // Try to fold constant mul into select arguments.
2988 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002989 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002990 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002991
2992 if (isa<PHINode>(Op0))
2993 if (Instruction *NV = FoldOpIntoPhi(I))
2994 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002995 }
2996
Chris Lattner934a64cf2003-03-10 23:23:04 +00002997 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2998 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002999 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00003000
Chris Lattner2635b522004-02-23 05:39:21 +00003001 // If one of the operands of the multiply is a cast from a boolean value, then
3002 // we know the bool is either zero or one, so this is a 'masking' multiply.
3003 // See if we can simplify things based on how the boolean was originally
3004 // formed.
3005 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00003006 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00003007 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00003008 BoolCast = CI;
3009 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00003010 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00003011 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00003012 BoolCast = CI;
3013 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003014 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00003015 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3016 const Type *SCOpTy = SCIOp0->getType();
3017
Reid Spencer266e42b2006-12-23 06:05:41 +00003018 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00003019 // multiply into a shift/and combination.
3020 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00003021 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00003022 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00003023 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003024 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00003025 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00003026 InsertNewInstBefore(
3027 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00003028 BoolCast->getOperand(0)->getName()+
3029 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00003030
3031 // If the multiply type is not the same as the source type, sign extend
3032 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003033 if (I.getType() != V->getType()) {
3034 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3035 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3036 Instruction::CastOps opcode =
3037 (SrcBits == DstBits ? Instruction::BitCast :
3038 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3039 V = InsertCastBefore(opcode, V, I.getType(), I);
3040 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003041
Chris Lattner2635b522004-02-23 05:39:21 +00003042 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003043 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00003044 }
3045 }
3046 }
3047
Chris Lattner113f4f42002-06-25 16:13:24 +00003048 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00003049}
3050
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003051/// This function implements the transforms on div instructions that work
3052/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3053/// used by the visitors to those instructions.
3054/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003055Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003056 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00003057
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003058 // undef / X -> 0
3059 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003061
3062 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003063 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003064 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003065
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003066 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00003067 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3068 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003069 // same basic block, then we replace the select with Y, and the condition
3070 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00003071 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003072 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00003073 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3074 if (ST->isNullValue()) {
3075 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3076 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003077 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00003078 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3079 I.setOperand(1, SI->getOperand(2));
3080 else
3081 UpdateValueUsesWith(SI, SI->getOperand(2));
3082 return &I;
3083 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003084
Chris Lattnerd79dc792006-09-09 20:26:32 +00003085 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3086 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3087 if (ST->isNullValue()) {
3088 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3089 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003090 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00003091 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3092 I.setOperand(1, SI->getOperand(1));
3093 else
3094 UpdateValueUsesWith(SI, SI->getOperand(1));
3095 return &I;
3096 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003097 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003098
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003099 return 0;
3100}
Misha Brukmanb1c93172005-04-21 23:48:37 +00003101
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003102/// This function implements the transforms common to both integer division
3103/// instructions (udiv and sdiv). It is called by the visitors to those integer
3104/// division instructions.
3105/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003106Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3108
3109 if (Instruction *Common = commonDivTransforms(I))
3110 return Common;
3111
3112 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3113 // div X, 1 == X
3114 if (RHS->equalsInt(1))
3115 return ReplaceInstUsesWith(I, Op0);
3116
3117 // (X / C1) / C2 -> X / (C1*C2)
3118 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3119 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3120 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3121 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3122 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00003123 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003124
3125 if (!RHS->isNullValue()) { // avoid X udiv 0
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3128 return R;
3129 if (isa<PHINode>(Op0))
3130 if (Instruction *NV = FoldOpIntoPhi(I))
3131 return NV;
3132 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003133 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003134
Chris Lattner3082c5a2003-02-18 19:28:33 +00003135 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003136 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00003137 if (LHS->equalsInt(0))
3138 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3139
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003140 return 0;
3141}
3142
3143Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3145
3146 // Handle the integer div common cases
3147 if (Instruction *Common = commonIDivTransforms(I))
3148 return Common;
3149
3150 // X udiv C^2 -> X >> C
3151 // Check to see if this is an unsigned division with an exact power of 2,
3152 // if so, convert to a right shift.
3153 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3154 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
3155 if (isPowerOf2_64(Val)) {
3156 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00003157 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00003158 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003159 }
3160 }
3161
3162 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00003163 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003164 if (RHSI->getOpcode() == Instruction::Shl &&
3165 isa<ConstantInt>(RHSI->getOperand(0))) {
3166 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3167 if (isPowerOf2_64(C1)) {
3168 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003169 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003170 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003171 Constant *C2V = ConstantInt::get(NTy, C2);
3172 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00003173 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00003174 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00003175 }
3176 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00003177 }
3178
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003179 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3180 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00003181 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003182 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00003183 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3184 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3185 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3186 // Compute the shift amounts
3187 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3188 // Construct the "on true" case of the select
3189 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3190 Instruction *TSI = BinaryOperator::createLShr(
3191 Op0, TC, SI->getName()+".t");
3192 TSI = InsertNewInstBefore(TSI, I);
3193
3194 // Construct the "on false" case of the select
3195 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3196 Instruction *FSI = BinaryOperator::createLShr(
3197 Op0, FC, SI->getName()+".f");
3198 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003199
Reid Spencer3939b1a2007-03-05 23:36:13 +00003200 // construct the select instruction and return it.
3201 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003202 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00003203 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003204 return 0;
3205}
3206
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003207Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3208 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3209
3210 // Handle the integer div common cases
3211 if (Instruction *Common = commonIDivTransforms(I))
3212 return Common;
3213
3214 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3215 // sdiv X, -1 == -X
3216 if (RHS->isAllOnesValue())
3217 return BinaryOperator::createNeg(Op0);
3218
3219 // -X/C -> X/-C
3220 if (Value *LHSNeg = dyn_castNegVal(Op0))
3221 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3222 }
3223
3224 // If the sign bits of both operands are zero (i.e. we can prove they are
3225 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00003226 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003227 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3228 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3229 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3230 }
3231 }
3232
3233 return 0;
3234}
3235
3236Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3237 return commonDivTransforms(I);
3238}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003239
Chris Lattner85dda9a2006-03-02 06:50:58 +00003240/// GetFactor - If we can prove that the specified value is at least a multiple
3241/// of some factor, return that factor.
3242static Constant *GetFactor(Value *V) {
3243 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3244 return CI;
3245
3246 // Unless we can be tricky, we know this is a multiple of 1.
3247 Constant *Result = ConstantInt::get(V->getType(), 1);
3248
3249 Instruction *I = dyn_cast<Instruction>(V);
3250 if (!I) return Result;
3251
3252 if (I->getOpcode() == Instruction::Mul) {
3253 // Handle multiplies by a constant, etc.
3254 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3255 GetFactor(I->getOperand(1)));
3256 } else if (I->getOpcode() == Instruction::Shl) {
3257 // (X<<C) -> X * (1 << C)
3258 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3259 ShRHS = ConstantExpr::getShl(Result, ShRHS);
3260 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3261 }
3262 } else if (I->getOpcode() == Instruction::And) {
3263 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3264 // X & 0xFFF0 is known to be a multiple of 16.
3265 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3266 if (Zeros != V->getType()->getPrimitiveSizeInBits())
3267 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00003268 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00003269 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003270 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00003271 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003272 if (!CI->isIntegerCast())
3273 return Result;
3274 Value *Op = CI->getOperand(0);
3275 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00003276 }
3277 return Result;
3278}
3279
Reid Spencer7eb55b32006-11-02 01:53:59 +00003280/// This function implements the transforms on rem instructions that work
3281/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3282/// is used by the visitors to those instructions.
3283/// @brief Transforms common to all three rem instructions
3284Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003286
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003287 // 0 % X == 0, we don't need to preserve faults!
3288 if (Constant *LHS = dyn_cast<Constant>(Op0))
3289 if (LHS->isNullValue())
3290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3291
3292 if (isa<UndefValue>(Op0)) // undef % X -> 0
3293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3294 if (isa<UndefValue>(Op1))
3295 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00003296
3297 // Handle cases involving: rem X, (select Cond, Y, Z)
3298 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3299 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3300 // the same basic block, then we replace the select with Y, and the
3301 // condition of the select with false (if the cond value is in the same
3302 // BB). If the select has uses other than the div, this allows them to be
3303 // simplified also.
3304 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3305 if (ST->isNullValue()) {
3306 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3307 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003308 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003309 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3310 I.setOperand(1, SI->getOperand(2));
3311 else
3312 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00003313 return &I;
3314 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003315 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3316 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3317 if (ST->isNullValue()) {
3318 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3319 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003320 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003321 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3322 I.setOperand(1, SI->getOperand(1));
3323 else
3324 UpdateValueUsesWith(SI, SI->getOperand(1));
3325 return &I;
3326 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00003327 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00003328
Reid Spencer7eb55b32006-11-02 01:53:59 +00003329 return 0;
3330}
3331
3332/// This function implements the transforms common to both integer remainder
3333/// instructions (urem and srem). It is called by the visitors to those integer
3334/// remainder instructions.
3335/// @brief Common integer remainder transforms
3336Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3338
3339 if (Instruction *common = commonRemTransforms(I))
3340 return common;
3341
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003342 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003343 // X % 0 == undef, we don't need to preserve faults!
3344 if (RHS->equalsInt(0))
3345 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3346
Chris Lattner3082c5a2003-02-18 19:28:33 +00003347 if (RHS->equalsInt(1)) // X % 1 == 0
3348 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3349
Chris Lattnerb70f1412006-02-28 05:49:21 +00003350 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3351 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3352 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3353 return R;
3354 } else if (isa<PHINode>(Op0I)) {
3355 if (Instruction *NV = FoldOpIntoPhi(I))
3356 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003357 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003358 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
3359 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00003360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00003361 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003362 }
3363
Reid Spencer7eb55b32006-11-02 01:53:59 +00003364 return 0;
3365}
3366
3367Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3369
3370 if (Instruction *common = commonIRemTransforms(I))
3371 return common;
3372
3373 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3374 // X urem C^2 -> X and C
3375 // Check to see if this is an unsigned remainder with an exact power of 2,
3376 // if so, convert to a bitwise and.
3377 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3378 if (isPowerOf2_64(C->getZExtValue()))
3379 return BinaryOperator::createAnd(Op0, SubOne(C));
3380 }
3381
Chris Lattner2e90b732006-02-05 07:54:04 +00003382 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003383 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3384 if (RHSI->getOpcode() == Instruction::Shl &&
3385 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003386 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00003387 if (isPowerOf2_64(C1)) {
3388 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3389 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3390 "tmp"), I);
3391 return BinaryOperator::createAnd(Op0, Add);
3392 }
3393 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003394 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003395
Reid Spencer7eb55b32006-11-02 01:53:59 +00003396 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3397 // where C1&C2 are powers of two.
3398 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3399 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3400 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3401 // STO == 0 and SFO == 0 handled above.
3402 if (isPowerOf2_64(STO->getZExtValue()) &&
3403 isPowerOf2_64(SFO->getZExtValue())) {
3404 Value *TrueAnd = InsertNewInstBefore(
3405 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3406 Value *FalseAnd = InsertNewInstBefore(
3407 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3408 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3409 }
3410 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003411 }
3412
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003413 return 0;
3414}
3415
Reid Spencer7eb55b32006-11-02 01:53:59 +00003416Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3418
3419 if (Instruction *common = commonIRemTransforms(I))
3420 return common;
3421
3422 if (Value *RHSNeg = dyn_castNegVal(Op1))
3423 if (!isa<ConstantInt>(RHSNeg) ||
3424 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3425 // X % -Y -> X % Y
3426 AddUsesToWorkList(I);
3427 I.setOperand(1, RHSNeg);
3428 return &I;
3429 }
3430
3431 // If the top bits of both operands are zero (i.e. we can prove they are
3432 // unsigned inputs), turn this into a urem.
3433 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3434 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3435 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3436 return BinaryOperator::createURem(Op0, Op1, I.getName());
3437 }
3438
3439 return 0;
3440}
3441
3442Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003443 return commonRemTransforms(I);
3444}
3445
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003446// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00003447static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3448 if (isSigned) {
3449 // Calculate 0111111111..11111
3450 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3451 int64_t Val = INT64_MAX; // All ones
3452 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
3453 return C->getSExtValue() == Val-1;
3454 }
Reid Spencera94d3942007-01-19 21:13:56 +00003455 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003456}
3457
3458// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00003459static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3460 if (isSigned) {
3461 // Calculate 1111111111000000000000
3462 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3463 int64_t Val = -1; // All ones
3464 Val <<= TypeBits-1; // Shift over to the right spot
3465 return C->getSExtValue() == Val+1;
3466 }
3467 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003468}
3469
Chris Lattner35167c32004-06-09 07:59:58 +00003470// isOneBitSet - Return true if there is exactly one bit set in the specified
3471// constant.
3472static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003473 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00003474 return V && (V & (V-1)) == 0;
3475}
3476
Chris Lattner8fc5af42004-09-23 21:46:38 +00003477#if 0 // Currently unused
3478// isLowOnes - Return true if the constant is of the form 0+1+.
3479static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003480 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003481
3482 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003483 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003484
3485 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3486 return U && V && (U & V) == 0;
3487}
3488#endif
3489
3490// isHighOnes - Return true if the constant is of the form 1+0+.
3491// This is the same as lowones(~X).
3492static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003493 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00003494 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00003495
3496 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003497 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003498
3499 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3500 return U && V && (U & V) == 0;
3501}
3502
Reid Spencer266e42b2006-12-23 06:05:41 +00003503/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003504/// are carefully arranged to allow folding of expressions such as:
3505///
3506/// (A < B) | (A > B) --> (A != B)
3507///
Reid Spencer266e42b2006-12-23 06:05:41 +00003508/// Note that this is only valid if the first and second predicates have the
3509/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003510///
Reid Spencer266e42b2006-12-23 06:05:41 +00003511/// Three bits are used to represent the condition, as follows:
3512/// 0 A > B
3513/// 1 A == B
3514/// 2 A < B
3515///
3516/// <=> Value Definition
3517/// 000 0 Always false
3518/// 001 1 A > B
3519/// 010 2 A == B
3520/// 011 3 A >= B
3521/// 100 4 A < B
3522/// 101 5 A != B
3523/// 110 6 A <= B
3524/// 111 7 Always true
3525///
3526static unsigned getICmpCode(const ICmpInst *ICI) {
3527 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003528 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003529 case ICmpInst::ICMP_UGT: return 1; // 001
3530 case ICmpInst::ICMP_SGT: return 1; // 001
3531 case ICmpInst::ICMP_EQ: return 2; // 010
3532 case ICmpInst::ICMP_UGE: return 3; // 011
3533 case ICmpInst::ICMP_SGE: return 3; // 011
3534 case ICmpInst::ICMP_ULT: return 4; // 100
3535 case ICmpInst::ICMP_SLT: return 4; // 100
3536 case ICmpInst::ICMP_NE: return 5; // 101
3537 case ICmpInst::ICMP_ULE: return 6; // 110
3538 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003539 // True -> 7
3540 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00003541 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003542 return 0;
3543 }
3544}
3545
Reid Spencer266e42b2006-12-23 06:05:41 +00003546/// getICmpValue - This is the complement of getICmpCode, which turns an
3547/// opcode and two operands into either a constant true or false, or a brand
3548/// new /// ICmp instruction. The sign is passed in to determine which kind
3549/// of predicate to use in new icmp instructions.
3550static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3551 switch (code) {
3552 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00003553 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003554 case 1:
3555 if (sign)
3556 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3557 else
3558 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3559 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3560 case 3:
3561 if (sign)
3562 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3563 else
3564 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3565 case 4:
3566 if (sign)
3567 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3568 else
3569 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3570 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3571 case 6:
3572 if (sign)
3573 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3574 else
3575 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003576 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003577 }
3578}
3579
Reid Spencer266e42b2006-12-23 06:05:41 +00003580static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3581 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3582 (ICmpInst::isSignedPredicate(p1) &&
3583 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3584 (ICmpInst::isSignedPredicate(p2) &&
3585 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3586}
3587
3588namespace {
3589// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3590struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003591 InstCombiner &IC;
3592 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003593 ICmpInst::Predicate pred;
3594 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3595 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3596 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003597 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003598 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3599 if (PredicatesFoldable(pred, ICI->getPredicate()))
3600 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3601 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003602 return false;
3603 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003604 Instruction *apply(Instruction &Log) const {
3605 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3606 if (ICI->getOperand(0) != LHS) {
3607 assert(ICI->getOperand(1) == LHS);
3608 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003609 }
3610
Reid Spencer266e42b2006-12-23 06:05:41 +00003611 unsigned LHSCode = getICmpCode(ICI);
3612 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003613 unsigned Code;
3614 switch (Log.getOpcode()) {
3615 case Instruction::And: Code = LHSCode & RHSCode; break;
3616 case Instruction::Or: Code = LHSCode | RHSCode; break;
3617 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003618 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003619 }
3620
Reid Spencer266e42b2006-12-23 06:05:41 +00003621 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003622 if (Instruction *I = dyn_cast<Instruction>(RV))
3623 return I;
3624 // Otherwise, it's a constant boolean value...
3625 return IC.ReplaceInstUsesWith(Log, RV);
3626 }
3627};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003628} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003629
Chris Lattnerba1cb382003-09-19 17:17:26 +00003630// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3631// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003632// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003633Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003634 ConstantInt *OpRHS,
3635 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003636 BinaryOperator &TheAnd) {
3637 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003638 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003639 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003640 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003641
Chris Lattnerba1cb382003-09-19 17:17:26 +00003642 switch (Op->getOpcode()) {
3643 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003644 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003645 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00003646 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003647 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003648 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003649 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003650 }
3651 break;
3652 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003653 if (Together == AndRHS) // (X | C) & C --> C
3654 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003655
Chris Lattner86102b82005-01-01 16:22:27 +00003656 if (Op->hasOneUse() && Together != OpRHS) {
3657 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00003658 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003659 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003660 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00003661 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003662 }
3663 break;
3664 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003665 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003666 // Adding a one to a single bit bit-field should be turned into an XOR
3667 // of the bit. First thing to check is to see if this AND is with a
3668 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003669 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003670
3671 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00003672 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003673
3674 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003675 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003676 // Ok, at this point, we know that we are masking the result of the
3677 // ADD down to exactly one bit. If the constant we are adding has
3678 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003679 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003680
Chris Lattnerba1cb382003-09-19 17:17:26 +00003681 // Check to see if any bits below the one bit set in AndRHSV are set.
3682 if ((AddRHS & (AndRHSV-1)) == 0) {
3683 // If not, the only thing that can effect the output of the AND is
3684 // the bit specified by AndRHSV. If that bit is set, the effect of
3685 // the XOR is to toggle the bit. If it is clear, then the ADD has
3686 // no effect.
3687 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3688 TheAnd.setOperand(0, X);
3689 return &TheAnd;
3690 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003691 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003692 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003693 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003694 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003695 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003696 }
3697 }
3698 }
3699 }
3700 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003701
3702 case Instruction::Shl: {
3703 // We know that the AND will not produce any of the bits shifted in, so if
3704 // the anded constant includes them, clear them now!
3705 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003706 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00003707 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3708 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003709
Chris Lattner7e794272004-09-24 15:21:34 +00003710 if (CI == ShlMask) { // Masking out bits that the shift already masks
3711 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3712 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003713 TheAnd.setOperand(1, CI);
3714 return &TheAnd;
3715 }
3716 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003717 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003718 case Instruction::LShr:
3719 {
Chris Lattner2da29172003-09-19 19:05:02 +00003720 // We know that the AND will not produce any of the bits shifted in, so if
3721 // the anded constant includes them, clear them now! This only applies to
3722 // unsigned shifts, because a signed shr may bring in set bits!
3723 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003724 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003725 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3726 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003727
Reid Spencerfdff9382006-11-08 06:47:33 +00003728 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3729 return ReplaceInstUsesWith(TheAnd, Op);
3730 } else if (CI != AndRHS) {
3731 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3732 return &TheAnd;
3733 }
3734 break;
3735 }
3736 case Instruction::AShr:
3737 // Signed shr.
3738 // See if this is shifting in some sign extension, then masking it out
3739 // with an and.
3740 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003741 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003742 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003743 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3744 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003745 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003746 // Make the argument unsigned.
3747 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003748 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003749 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003750 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003751 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003752 }
Chris Lattner2da29172003-09-19 19:05:02 +00003753 }
3754 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003755 }
3756 return 0;
3757}
3758
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003759
Chris Lattner6862fbd2004-09-29 17:40:11 +00003760/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3761/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003762/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3763/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003764/// insert new instructions.
3765Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003766 bool isSigned, bool Inside,
3767 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003768 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003769 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003770 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003771
Chris Lattner6862fbd2004-09-29 17:40:11 +00003772 if (Inside) {
3773 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003774 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003775
Reid Spencer266e42b2006-12-23 06:05:41 +00003776 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003777 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003778 ICmpInst::Predicate pred = (isSigned ?
3779 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3780 return new ICmpInst(pred, V, Hi);
3781 }
3782
3783 // Emit V-Lo <u Hi-Lo
3784 Constant *NegLo = ConstantExpr::getNeg(Lo);
3785 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003786 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003787 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3788 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003789 }
3790
3791 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003792 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003793
Reid Spencer266e42b2006-12-23 06:05:41 +00003794 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003795 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003796 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003797 ICmpInst::Predicate pred = (isSigned ?
3798 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3799 return new ICmpInst(pred, V, Hi);
3800 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003801
Reid Spencer266e42b2006-12-23 06:05:41 +00003802 // Emit V-Lo > Hi-1-Lo
3803 Constant *NegLo = ConstantExpr::getNeg(Lo);
3804 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003805 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003806 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3807 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003808}
3809
Chris Lattnerb4b25302005-09-18 07:22:02 +00003810// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3811// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3812// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3813// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003814static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003815 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003816 if (!isShiftedMask_64(V)) return false;
3817
3818 // look for the first zero bit after the run of ones
3819 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3820 // look for the first non-zero bit
3821 ME = 64-CountLeadingZeros_64(V);
3822 return true;
3823}
3824
3825
3826
3827/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3828/// where isSub determines whether the operator is a sub. If we can fold one of
3829/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003830///
3831/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3832/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3833/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3834///
3835/// return (A +/- B).
3836///
3837Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003838 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003839 Instruction &I) {
3840 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3841 if (!LHSI || LHSI->getNumOperands() != 2 ||
3842 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3843
3844 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3845
3846 switch (LHSI->getOpcode()) {
3847 default: return 0;
3848 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003849 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3850 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003851 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003852 break;
3853
3854 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3855 // part, we don't need any explicit masks to take them out of A. If that
3856 // is all N is, ignore it.
3857 unsigned MB, ME;
3858 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003859 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003860 Mask >>= 64-MB+1;
3861 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003862 break;
3863 }
3864 }
Chris Lattneraf517572005-09-18 04:24:45 +00003865 return 0;
3866 case Instruction::Or:
3867 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003868 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003869 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003870 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003871 break;
3872 return 0;
3873 }
3874
3875 Instruction *New;
3876 if (isSub)
3877 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3878 else
3879 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3880 return InsertNewInstBefore(New, I);
3881}
3882
Chris Lattner113f4f42002-06-25 16:13:24 +00003883Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003884 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003885 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003886
Chris Lattner81a7a232004-10-16 18:11:37 +00003887 if (isa<UndefValue>(Op1)) // X & undef -> 0
3888 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3889
Chris Lattner86102b82005-01-01 16:22:27 +00003890 // and X, X = X
3891 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003892 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003893
Chris Lattner5b2edb12006-02-12 08:02:11 +00003894 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003895 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003896 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003897 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003898 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003899 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003900 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003901 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003902 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003903 if (CP->isAllOnesValue())
3904 return ReplaceInstUsesWith(I, I.getOperand(0));
3905 }
3906 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003907
Zhou Sheng75b871f2007-01-11 12:24:14 +00003908 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003909 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003910 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003911 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003912
Chris Lattnerba1cb382003-09-19 17:17:26 +00003913 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003914 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003915 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003916 Value *Op0LHS = Op0I->getOperand(0);
3917 Value *Op0RHS = Op0I->getOperand(1);
3918 switch (Op0I->getOpcode()) {
3919 case Instruction::Xor:
3920 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003921 // If the mask is only needed on one incoming arm, push it up.
3922 if (Op0I->hasOneUse()) {
3923 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3924 // Not masking anything out for the LHS, move to RHS.
3925 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3926 Op0RHS->getName()+".masked");
3927 InsertNewInstBefore(NewRHS, I);
3928 return BinaryOperator::create(
3929 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003930 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003931 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003932 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3933 // Not masking anything out for the RHS, move to LHS.
3934 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3935 Op0LHS->getName()+".masked");
3936 InsertNewInstBefore(NewLHS, I);
3937 return BinaryOperator::create(
3938 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3939 }
3940 }
3941
Chris Lattner86102b82005-01-01 16:22:27 +00003942 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003943 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003944 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3945 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3946 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3947 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3948 return BinaryOperator::createAnd(V, AndRHS);
3949 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3950 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003951 break;
3952
3953 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003954 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3955 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3956 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3957 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3958 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003959 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003960 }
3961
Chris Lattner16464b32003-07-23 19:25:52 +00003962 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003963 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003964 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003965 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003966 // If this is an integer truncation or change from signed-to-unsigned, and
3967 // if the source is an and/or with immediate, transform it. This
3968 // frequently occurs for bitfield accesses.
3969 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003970 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003971 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003972 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003973 if (CastOp->getOpcode() == Instruction::And) {
3974 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003975 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3976 // This will fold the two constants together, which may allow
3977 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003978 Instruction *NewCast = CastInst::createTruncOrBitCast(
3979 CastOp->getOperand(0), I.getType(),
3980 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003981 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003982 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003983 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003984 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003985 return BinaryOperator::createAnd(NewCast, C3);
3986 } else if (CastOp->getOpcode() == Instruction::Or) {
3987 // Change: and (cast (or X, C1) to T), C2
3988 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003989 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003990 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3991 return ReplaceInstUsesWith(I, AndRHS);
3992 }
3993 }
Chris Lattner33217db2003-07-23 19:36:21 +00003994 }
Chris Lattner183b3362004-04-09 19:05:30 +00003995
3996 // Try to fold constant and into select arguments.
3997 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003998 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003999 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004000 if (isa<PHINode>(Op0))
4001 if (Instruction *NV = FoldOpIntoPhi(I))
4002 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00004003 }
4004
Chris Lattnerbb74e222003-03-10 23:06:50 +00004005 Value *Op0NotVal = dyn_castNotVal(Op0);
4006 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004007
Chris Lattner023a4832004-06-18 06:07:51 +00004008 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4010
Misha Brukman9c003d82004-07-30 12:50:08 +00004011 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00004012 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004013 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4014 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00004015 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004016 return BinaryOperator::createNot(Or);
4017 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004018
4019 {
4020 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00004021 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4022 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4023 return ReplaceInstUsesWith(I, Op1);
4024 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4025 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4026 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004027
4028 if (Op0->hasOneUse() &&
4029 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4030 if (A == Op1) { // (A^B)&A -> A&(A^B)
4031 I.swapOperands(); // Simplify below
4032 std::swap(Op0, Op1);
4033 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4034 cast<BinaryOperator>(Op0)->swapOperands();
4035 I.swapOperands(); // Simplify below
4036 std::swap(Op0, Op1);
4037 }
4038 }
4039 if (Op1->hasOneUse() &&
4040 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4041 if (B == Op0) { // B&(A^B) -> B&(B^A)
4042 cast<BinaryOperator>(Op1)->swapOperands();
4043 std::swap(A, B);
4044 }
4045 if (A == Op0) { // A&(A^B) -> A & ~B
4046 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4047 InsertNewInstBefore(NotB, I);
4048 return BinaryOperator::createAnd(A, NotB);
4049 }
4050 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004051 }
4052
Reid Spencer266e42b2006-12-23 06:05:41 +00004053 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4054 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4055 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004056 return R;
4057
Chris Lattner623826c2004-09-28 21:48:02 +00004058 Value *LHSVal, *RHSVal;
4059 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004060 ICmpInst::Predicate LHSCC, RHSCC;
4061 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4062 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4063 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4064 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4065 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4066 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4067 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4068 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00004069 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004070 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4071 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4072 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4073 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00004074 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00004075 std::swap(LHS, RHS);
4076 std::swap(LHSCst, RHSCst);
4077 std::swap(LHSCC, RHSCC);
4078 }
4079
Reid Spencer266e42b2006-12-23 06:05:41 +00004080 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00004081 // comparing a value against two constants and and'ing the result
4082 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004083 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4084 // (from the FoldICmpLogical check above), that the two constants
4085 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00004086 assert(LHSCst != RHSCst && "Compares not folded above?");
4087
4088 switch (LHSCC) {
4089 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004090 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00004091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004093 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4094 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4095 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004096 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004097 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4098 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4099 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00004100 return ReplaceInstUsesWith(I, LHS);
4101 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004102 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00004103 switch (RHSCC) {
4104 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004105 case ICmpInst::ICMP_ULT:
4106 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4107 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4108 break; // (X != 13 & X u< 15) -> no change
4109 case ICmpInst::ICMP_SLT:
4110 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4111 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4112 break; // (X != 13 & X s< 15) -> no change
4113 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4114 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4115 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00004116 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004117 case ICmpInst::ICMP_NE:
4118 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00004119 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4120 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4121 LHSVal->getName()+".off");
4122 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00004123 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4124 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00004125 }
4126 break; // (X != 13 & X != 15) -> no change
4127 }
4128 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004129 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00004130 switch (RHSCC) {
4131 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004132 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4133 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004135 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4136 break;
4137 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4138 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00004139 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4141 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004142 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004143 break;
4144 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00004145 switch (RHSCC) {
4146 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004147 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4148 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004149 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004150 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4151 break;
4152 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4153 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00004154 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004155 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4156 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004157 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004158 break;
4159 case ICmpInst::ICMP_UGT:
4160 switch (RHSCC) {
4161 default: assert(0 && "Unknown integer condition code!");
4162 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4163 return ReplaceInstUsesWith(I, LHS);
4164 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4165 return ReplaceInstUsesWith(I, RHS);
4166 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4167 break;
4168 case ICmpInst::ICMP_NE:
4169 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4170 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4171 break; // (X u> 13 & X != 15) -> no change
4172 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4173 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4174 true, I);
4175 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4176 break;
4177 }
4178 break;
4179 case ICmpInst::ICMP_SGT:
4180 switch (RHSCC) {
4181 default: assert(0 && "Unknown integer condition code!");
4182 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
4183 return ReplaceInstUsesWith(I, LHS);
4184 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4185 return ReplaceInstUsesWith(I, RHS);
4186 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4187 break;
4188 case ICmpInst::ICMP_NE:
4189 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4190 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4191 break; // (X s> 13 & X != 15) -> no change
4192 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4193 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4194 true, I);
4195 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4196 break;
4197 }
4198 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004199 }
4200 }
4201 }
4202
Chris Lattner3af10532006-05-05 06:39:07 +00004203 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004204 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4205 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4206 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4207 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004208 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004209 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4211 I.getType(), TD) &&
4212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4213 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004214 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4215 Op1C->getOperand(0),
4216 I.getName());
4217 InsertNewInstBefore(NewOp, I);
4218 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4219 }
Chris Lattner3af10532006-05-05 06:39:07 +00004220 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004221
4222 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004223 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4224 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4225 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004226 SI0->getOperand(1) == SI1->getOperand(1) &&
4227 (SI0->hasOneUse() || SI1->hasOneUse())) {
4228 Instruction *NewOp =
4229 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4230 SI1->getOperand(0),
4231 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004232 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4233 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004234 }
Chris Lattner3af10532006-05-05 06:39:07 +00004235 }
4236
Chris Lattner113f4f42002-06-25 16:13:24 +00004237 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004238}
4239
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004240/// CollectBSwapParts - Look to see if the specified value defines a single byte
4241/// in the result. If it does, and if the specified byte hasn't been filled in
4242/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004243static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004244 Instruction *I = dyn_cast<Instruction>(V);
4245 if (I == 0) return true;
4246
4247 // If this is an or instruction, it is an inner node of the bswap.
4248 if (I->getOpcode() == Instruction::Or)
4249 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4250 CollectBSwapParts(I->getOperand(1), ByteValues);
4251
4252 // If this is a shift by a constant int, and it is "24", then its operand
4253 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00004254 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004255 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00004256 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004257 8*(ByteValues.size()-1))
4258 return true;
4259
4260 unsigned DestNo;
4261 if (I->getOpcode() == Instruction::Shl) {
4262 // X << 24 defines the top byte with the lowest of the input bytes.
4263 DestNo = ByteValues.size()-1;
4264 } else {
4265 // X >>u 24 defines the low byte with the highest of the input bytes.
4266 DestNo = 0;
4267 }
4268
4269 // If the destination byte value is already defined, the values are or'd
4270 // together, which isn't a bswap (unless it's an or of the same bits).
4271 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4272 return true;
4273 ByteValues[DestNo] = I->getOperand(0);
4274 return false;
4275 }
4276
4277 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4278 // don't have this.
4279 Value *Shift = 0, *ShiftLHS = 0;
4280 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4281 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4282 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4283 return true;
4284 Instruction *SI = cast<Instruction>(Shift);
4285
4286 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004287 if (ShiftAmt->getZExtValue() & 7 ||
4288 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004289 return true;
4290
4291 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4292 unsigned DestByte;
4293 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004294 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004295 break;
4296 // Unknown mask for bswap.
4297 if (DestByte == ByteValues.size()) return true;
4298
Reid Spencere0fc4df2006-10-20 07:07:24 +00004299 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004300 unsigned SrcByte;
4301 if (SI->getOpcode() == Instruction::Shl)
4302 SrcByte = DestByte - ShiftBytes;
4303 else
4304 SrcByte = DestByte + ShiftBytes;
4305
4306 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4307 if (SrcByte != ByteValues.size()-DestByte-1)
4308 return true;
4309
4310 // If the destination byte value is already defined, the values are or'd
4311 // together, which isn't a bswap (unless it's an or of the same bits).
4312 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4313 return true;
4314 ByteValues[DestByte] = SI->getOperand(0);
4315 return false;
4316}
4317
4318/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4319/// If so, insert the new bswap intrinsic and return it.
4320Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00004321 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00004322 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004323 return 0;
4324
4325 /// ByteValues - For each byte of the result, we keep track of which value
4326 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004327 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00004328 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004329
4330 // Try to find all the pieces corresponding to the bswap.
4331 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4332 CollectBSwapParts(I.getOperand(1), ByteValues))
4333 return 0;
4334
4335 // Check to see if all of the bytes come from the same value.
4336 Value *V = ByteValues[0];
4337 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4338
4339 // Check to make sure that all of the bytes come from the same value.
4340 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4341 if (ByteValues[i] != V)
4342 return 0;
4343
4344 // If they do then *success* we can turn this into a bswap. Figure out what
4345 // bswap to make it into.
4346 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00004347 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00004348 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004349 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00004350 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004351 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00004352 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004353 FnName = "llvm.bswap.i64";
4354 else
4355 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00004356 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004357 return new CallInst(F, V);
4358}
4359
4360
Chris Lattner113f4f42002-06-25 16:13:24 +00004361Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004362 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004364
Chris Lattner81a7a232004-10-16 18:11:37 +00004365 if (isa<UndefValue>(Op1))
4366 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004367 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004368
Chris Lattner5b2edb12006-02-12 08:02:11 +00004369 // or X, X = X
4370 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004371 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004372
Chris Lattner5b2edb12006-02-12 08:02:11 +00004373 // See if we can simplify any instructions used by the instruction whose sole
4374 // purpose is to compute bits we don't care about.
4375 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004376 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00004377 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004378 KnownZero, KnownOne))
4379 return &I;
4380
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004381 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004382 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004383 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004384 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4385 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004386 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004387 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004388 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004389 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4390 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004391
Chris Lattnerd4252a72004-07-30 07:50:03 +00004392 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4393 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004394 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004395 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004396 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004397 return BinaryOperator::createXor(Or,
4398 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004399 }
Chris Lattner183b3362004-04-09 19:05:30 +00004400
4401 // Try to fold constant and into select arguments.
4402 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004403 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004404 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004405 if (isa<PHINode>(Op0))
4406 if (Instruction *NV = FoldOpIntoPhi(I))
4407 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004408 }
4409
Chris Lattner330628a2006-01-06 17:59:59 +00004410 Value *A = 0, *B = 0;
4411 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004412
4413 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4414 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4415 return ReplaceInstUsesWith(I, Op1);
4416 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4417 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4418 return ReplaceInstUsesWith(I, Op0);
4419
Chris Lattnerb7845d62006-07-10 20:25:24 +00004420 // (A | B) | C and A | (B | C) -> bswap if possible.
4421 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004422 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00004423 match(Op1, m_Or(m_Value(), m_Value())) ||
4424 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4425 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004426 if (Instruction *BSwap = MatchBSwap(I))
4427 return BSwap;
4428 }
4429
Chris Lattnerb62f5082005-05-09 04:58:36 +00004430 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4431 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004432 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004433 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4434 InsertNewInstBefore(NOr, I);
4435 NOr->takeName(Op0);
4436 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004437 }
4438
4439 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4440 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004441 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004442 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4443 InsertNewInstBefore(NOr, I);
4444 NOr->takeName(Op0);
4445 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004446 }
4447
Chris Lattner15212982005-09-18 03:42:07 +00004448 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00004449 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00004450 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4451
4452 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
4453 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4454
4455
Chris Lattner01f56c62005-09-18 06:02:59 +00004456 // If we have: ((V + N) & C1) | (V & C2)
4457 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4458 // replace with V+N.
4459 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004460 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00004461 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00004462 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4463 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004464 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004465 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004466 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004467 return ReplaceInstUsesWith(I, A);
4468 }
4469 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004470 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00004471 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4472 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004473 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004474 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004475 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004476 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00004477 }
4478 }
4479 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004480
4481 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004482 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4483 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4484 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004485 SI0->getOperand(1) == SI1->getOperand(1) &&
4486 (SI0->hasOneUse() || SI1->hasOneUse())) {
4487 Instruction *NewOp =
4488 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4489 SI1->getOperand(0),
4490 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004491 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4492 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004493 }
4494 }
Chris Lattner812aab72003-08-12 19:11:07 +00004495
Chris Lattnerd4252a72004-07-30 07:50:03 +00004496 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4497 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00004498 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004499 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004500 } else {
4501 A = 0;
4502 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004503 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00004504 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4505 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00004506 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004507 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004508
Misha Brukman9c003d82004-07-30 12:50:08 +00004509 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004510 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4511 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4512 I.getName()+".demorgan"), I);
4513 return BinaryOperator::createNot(And);
4514 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004515 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004516
Reid Spencer266e42b2006-12-23 06:05:41 +00004517 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4518 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4519 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004520 return R;
4521
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004522 Value *LHSVal, *RHSVal;
4523 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004524 ICmpInst::Predicate LHSCC, RHSCC;
4525 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4526 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4527 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4528 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4529 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4530 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4531 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4532 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004533 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004534 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4535 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4536 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4537 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00004538 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004539 std::swap(LHS, RHS);
4540 std::swap(LHSCst, RHSCst);
4541 std::swap(LHSCC, RHSCC);
4542 }
4543
Reid Spencer266e42b2006-12-23 06:05:41 +00004544 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004545 // comparing a value against two constants and or'ing the result
4546 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004547 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4548 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004549 // equal.
4550 assert(LHSCst != RHSCst && "Compares not folded above?");
4551
4552 switch (LHSCC) {
4553 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004555 switch (RHSCC) {
4556 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004557 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004558 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4559 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4560 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4561 LHSVal->getName()+".off");
4562 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004563 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00004564 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004565 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004566 break; // (X == 13 | X == 15) -> no change
4567 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4568 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00004569 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004570 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4571 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4572 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004573 return ReplaceInstUsesWith(I, RHS);
4574 }
4575 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004576 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004577 switch (RHSCC) {
4578 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004579 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4580 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4581 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004582 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004583 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4584 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4585 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004586 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004587 }
4588 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004589 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004590 switch (RHSCC) {
4591 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004592 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004593 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004594 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4595 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4596 false, I);
4597 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4598 break;
4599 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4600 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004601 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004602 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4603 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004604 }
4605 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004606 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004607 switch (RHSCC) {
4608 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004609 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4610 break;
4611 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4612 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4613 false, I);
4614 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4615 break;
4616 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4617 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4618 return ReplaceInstUsesWith(I, RHS);
4619 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4620 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004621 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004622 break;
4623 case ICmpInst::ICMP_UGT:
4624 switch (RHSCC) {
4625 default: assert(0 && "Unknown integer condition code!");
4626 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4627 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4628 return ReplaceInstUsesWith(I, LHS);
4629 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4632 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004633 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004634 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4635 break;
4636 }
4637 break;
4638 case ICmpInst::ICMP_SGT:
4639 switch (RHSCC) {
4640 default: assert(0 && "Unknown integer condition code!");
4641 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4642 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4645 break;
4646 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4647 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004649 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4650 break;
4651 }
4652 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004653 }
4654 }
4655 }
Chris Lattner3af10532006-05-05 06:39:07 +00004656
4657 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004658 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004659 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004660 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4661 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004662 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004663 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004664 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4665 I.getType(), TD) &&
4666 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4667 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004668 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4669 Op1C->getOperand(0),
4670 I.getName());
4671 InsertNewInstBefore(NewOp, I);
4672 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4673 }
Chris Lattner3af10532006-05-05 06:39:07 +00004674 }
Chris Lattner3af10532006-05-05 06:39:07 +00004675
Chris Lattner15212982005-09-18 03:42:07 +00004676
Chris Lattner113f4f42002-06-25 16:13:24 +00004677 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004678}
4679
Chris Lattnerc2076352004-02-16 01:20:27 +00004680// XorSelf - Implements: X ^ X --> 0
4681struct XorSelf {
4682 Value *RHS;
4683 XorSelf(Value *rhs) : RHS(rhs) {}
4684 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4685 Instruction *apply(BinaryOperator &Xor) const {
4686 return &Xor;
4687 }
4688};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004689
4690
Chris Lattner113f4f42002-06-25 16:13:24 +00004691Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004692 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004694
Chris Lattner81a7a232004-10-16 18:11:37 +00004695 if (isa<UndefValue>(Op1))
4696 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4697
Chris Lattnerc2076352004-02-16 01:20:27 +00004698 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4699 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4700 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004701 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004702 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004703
4704 // See if we can simplify any instructions used by the instruction whose sole
4705 // purpose is to compute bits we don't care about.
4706 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004707 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00004708 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004709 KnownZero, KnownOne))
4710 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004711
Zhou Sheng75b871f2007-01-11 12:24:14 +00004712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004713 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4714 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004715 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004716 return new ICmpInst(ICI->getInversePredicate(),
4717 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004718
Reid Spencer266e42b2006-12-23 06:05:41 +00004719 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004720 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004721 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4722 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004723 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4724 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004725 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004726 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004727 }
Chris Lattner023a4832004-06-18 06:07:51 +00004728
4729 // ~(~X & Y) --> (X | ~Y)
4730 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4731 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4732 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4733 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004734 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004735 Op0I->getOperand(1)->getName()+".not");
4736 InsertNewInstBefore(NotY, I);
4737 return BinaryOperator::createOr(Op0NotVal, NotY);
4738 }
4739 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004740
Chris Lattner97638592003-07-23 21:37:07 +00004741 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004742 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004743 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004744 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004745 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4746 return BinaryOperator::createSub(
4747 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004748 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004749 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004750 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004751 } else if (Op0I->getOpcode() == Instruction::Or) {
4752 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4753 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4754 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4755 // Anything in both C1 and C2 is known to be zero, remove it from
4756 // NewRHS.
4757 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4758 NewRHS = ConstantExpr::getAnd(NewRHS,
4759 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004760 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004761 I.setOperand(0, Op0I->getOperand(0));
4762 I.setOperand(1, NewRHS);
4763 return &I;
4764 }
Chris Lattner97638592003-07-23 21:37:07 +00004765 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004766 }
Chris Lattner183b3362004-04-09 19:05:30 +00004767
4768 // Try to fold constant and into select arguments.
4769 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004770 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004771 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004772 if (isa<PHINode>(Op0))
4773 if (Instruction *NV = FoldOpIntoPhi(I))
4774 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004775 }
4776
Chris Lattnerbb74e222003-03-10 23:06:50 +00004777 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004778 if (X == Op1)
4779 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004780 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004781
Chris Lattnerbb74e222003-03-10 23:06:50 +00004782 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004783 if (X == Op0)
4784 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004785 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004786
Chris Lattnerdcd07922006-04-01 08:03:55 +00004787 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00004788 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004789 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004790 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004791 I.swapOperands();
4792 std::swap(Op0, Op1);
4793 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004794 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004795 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004796 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004797 } else if (Op1I->getOpcode() == Instruction::Xor) {
4798 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4799 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4800 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4801 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004802 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4803 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4804 Op1I->swapOperands();
4805 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4806 I.swapOperands(); // Simplified below.
4807 std::swap(Op0, Op1);
4808 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004809 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004810
Chris Lattnerdcd07922006-04-01 08:03:55 +00004811 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004812 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004813 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004814 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004815 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004816 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4817 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004818 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004819 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004820 } else if (Op0I->getOpcode() == Instruction::Xor) {
4821 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4822 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4823 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4824 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004825 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4826 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4827 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004828 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4829 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004830 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4831 InsertNewInstBefore(N, I);
4832 return BinaryOperator::createAnd(N, Op1);
4833 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004834 }
4835
Reid Spencer266e42b2006-12-23 06:05:41 +00004836 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4837 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4838 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004839 return R;
4840
Chris Lattner3af10532006-05-05 06:39:07 +00004841 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004842 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004843 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004844 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4845 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004846 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004847 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004848 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4849 I.getType(), TD) &&
4850 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4851 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004852 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4853 Op1C->getOperand(0),
4854 I.getName());
4855 InsertNewInstBefore(NewOp, I);
4856 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4857 }
Chris Lattner3af10532006-05-05 06:39:07 +00004858 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004859
4860 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004861 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4862 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4863 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004864 SI0->getOperand(1) == SI1->getOperand(1) &&
4865 (SI0->hasOneUse() || SI1->hasOneUse())) {
4866 Instruction *NewOp =
4867 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4868 SI1->getOperand(0),
4869 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004870 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4871 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004872 }
4873 }
Chris Lattner3af10532006-05-05 06:39:07 +00004874
Chris Lattner113f4f42002-06-25 16:13:24 +00004875 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004876}
4877
Chris Lattner6862fbd2004-09-29 17:40:11 +00004878static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004879 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004880}
4881
4882/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4883/// overflowed for this type.
4884static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4885 ConstantInt *In2) {
4886 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4887
Reid Spencerc635f472006-12-31 05:48:39 +00004888 return cast<ConstantInt>(Result)->getZExtValue() <
4889 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004890}
4891
Chris Lattner0798af32005-01-13 20:14:25 +00004892/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4893/// code necessary to compute the offset from the base pointer (without adding
4894/// in the base pointer). Return the result as a signed integer of intptr size.
4895static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4896 TargetData &TD = IC.getTargetData();
4897 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004898 const Type *IntPtrTy = TD.getIntPtrType();
4899 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004900
4901 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004902 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004903
Chris Lattner0798af32005-01-13 20:14:25 +00004904 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4905 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004906 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004907 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004908 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4909 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004910 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004911 Scale = ConstantExpr::getMul(OpC, Scale);
4912 if (Constant *RC = dyn_cast<Constant>(Result))
4913 Result = ConstantExpr::getAdd(RC, Scale);
4914 else {
4915 // Emit an add instruction.
4916 Result = IC.InsertNewInstBefore(
4917 BinaryOperator::createAdd(Result, Scale,
4918 GEP->getName()+".offs"), I);
4919 }
4920 }
4921 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004922 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004923 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004924 Op->getName()+".c"), I);
4925 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004926 // We'll let instcombine(mul) convert this to a shl if possible.
4927 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4928 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004929
4930 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004931 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004932 GEP->getName()+".offs"), I);
4933 }
4934 }
4935 return Result;
4936}
4937
Reid Spencer266e42b2006-12-23 06:05:41 +00004938/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004939/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004940Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4941 ICmpInst::Predicate Cond,
4942 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004943 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004944
4945 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4946 if (isa<PointerType>(CI->getOperand(0)->getType()))
4947 RHS = CI->getOperand(0);
4948
Chris Lattner0798af32005-01-13 20:14:25 +00004949 Value *PtrBase = GEPLHS->getOperand(0);
4950 if (PtrBase == RHS) {
4951 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004952 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4953 // each index is zero or not.
4954 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004955 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004956 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4957 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004958 bool EmitIt = true;
4959 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4960 if (isa<UndefValue>(C)) // undef index -> undef.
4961 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4962 if (C->isNullValue())
4963 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004964 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4965 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004966 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004967 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004968 ConstantInt::get(Type::Int1Ty,
4969 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004970 }
4971
4972 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004973 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004974 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004975 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4976 if (InVal == 0)
4977 InVal = Comp;
4978 else {
4979 InVal = InsertNewInstBefore(InVal, I);
4980 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004981 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004982 InVal = BinaryOperator::createOr(InVal, Comp);
4983 else // True if all are equal
4984 InVal = BinaryOperator::createAnd(InVal, Comp);
4985 }
4986 }
4987 }
4988
4989 if (InVal)
4990 return InVal;
4991 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004992 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004993 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4994 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004995 }
Chris Lattner0798af32005-01-13 20:14:25 +00004996
Reid Spencer266e42b2006-12-23 06:05:41 +00004997 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004998 // the result to fold to a constant!
4999 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5000 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5001 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005002 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5003 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005004 }
5005 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005006 // If the base pointers are different, but the indices are the same, just
5007 // compare the base pointer.
5008 if (PtrBase != GEPRHS->getOperand(0)) {
5009 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005010 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005011 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005012 if (IndicesTheSame)
5013 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5014 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5015 IndicesTheSame = false;
5016 break;
5017 }
5018
5019 // If all indices are the same, just compare the base pointers.
5020 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00005021 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5022 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005023
5024 // Otherwise, the base pointers are different and the indices are
5025 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005026 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005027 }
Chris Lattner0798af32005-01-13 20:14:25 +00005028
Chris Lattner81e84172005-01-13 22:25:21 +00005029 // If one of the GEPs has all zero indices, recurse.
5030 bool AllZeros = true;
5031 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5032 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5033 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5034 AllZeros = false;
5035 break;
5036 }
5037 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005038 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5039 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005040
5041 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005042 AllZeros = true;
5043 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5044 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5045 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5046 AllZeros = false;
5047 break;
5048 }
5049 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005050 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005051
Chris Lattner4fa89822005-01-14 00:20:05 +00005052 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5053 // If the GEPs only differ by one index, compare it.
5054 unsigned NumDifferences = 0; // Keep track of # differences.
5055 unsigned DiffOperand = 0; // The operand that differs.
5056 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5057 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005058 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5059 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005060 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005061 NumDifferences = 2;
5062 break;
5063 } else {
5064 if (NumDifferences++) break;
5065 DiffOperand = i;
5066 }
5067 }
5068
5069 if (NumDifferences == 0) // SAME GEP?
5070 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00005071 ConstantInt::get(Type::Int1Ty,
5072 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00005073 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005074 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5075 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005076 // Make sure we do a signed comparison here.
5077 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005078 }
5079 }
5080
Reid Spencer266e42b2006-12-23 06:05:41 +00005081 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005082 // the result to fold to a constant!
5083 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5084 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5085 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5086 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5087 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005088 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005089 }
5090 }
5091 return 0;
5092}
5093
Reid Spencer266e42b2006-12-23 06:05:41 +00005094Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5095 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005096 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005097
Chris Lattner6ee923f2007-01-14 19:42:17 +00005098 // Fold trivial predicates.
5099 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5100 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5101 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5102 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5103
5104 // Simplify 'fcmp pred X, X'
5105 if (Op0 == Op1) {
5106 switch (I.getPredicate()) {
5107 default: assert(0 && "Unknown predicate!");
5108 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5109 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5110 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5111 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5112 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5113 case FCmpInst::FCMP_OLT: // True if ordered and less than
5114 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5115 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5116
5117 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5118 case FCmpInst::FCMP_ULT: // True if unordered or less than
5119 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5120 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5121 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5122 I.setPredicate(FCmpInst::FCMP_UNO);
5123 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5124 return &I;
5125
5126 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5127 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5128 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5129 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5130 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5131 I.setPredicate(FCmpInst::FCMP_ORD);
5132 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5133 return &I;
5134 }
5135 }
5136
Reid Spencer266e42b2006-12-23 06:05:41 +00005137 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005138 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005139
Reid Spencer266e42b2006-12-23 06:05:41 +00005140 // Handle fcmp with constant RHS
5141 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5142 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5143 switch (LHSI->getOpcode()) {
5144 case Instruction::PHI:
5145 if (Instruction *NV = FoldOpIntoPhi(I))
5146 return NV;
5147 break;
5148 case Instruction::Select:
5149 // If either operand of the select is a constant, we can fold the
5150 // comparison into the select arms, which will cause one to be
5151 // constant folded and the select turned into a bitwise or.
5152 Value *Op1 = 0, *Op2 = 0;
5153 if (LHSI->hasOneUse()) {
5154 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5155 // Fold the known value into the constant operand.
5156 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5157 // Insert a new FCmp of the other select operand.
5158 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5159 LHSI->getOperand(2), RHSC,
5160 I.getName()), I);
5161 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5162 // Fold the known value into the constant operand.
5163 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5164 // Insert a new FCmp of the other select operand.
5165 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5166 LHSI->getOperand(1), RHSC,
5167 I.getName()), I);
5168 }
5169 }
5170
5171 if (Op1)
5172 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5173 break;
5174 }
5175 }
5176
5177 return Changed ? &I : 0;
5178}
5179
5180Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5181 bool Changed = SimplifyCompare(I);
5182 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5183 const Type *Ty = Op0->getType();
5184
5185 // icmp X, X
5186 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00005187 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5188 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005189
5190 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005191 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00005192
5193 // icmp of GlobalValues can never equal each other as long as they aren't
5194 // external weak linkage type.
5195 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5196 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5197 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00005198 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5199 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005200
5201 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005202 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005203 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5204 isa<ConstantPointerNull>(Op0)) &&
5205 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00005206 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00005207 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5208 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005209
Reid Spencer266e42b2006-12-23 06:05:41 +00005210 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00005211 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005212 switch (I.getPredicate()) {
5213 default: assert(0 && "Invalid icmp instruction!");
5214 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005215 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005216 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00005217 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005218 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005219 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00005220 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005221
Reid Spencer266e42b2006-12-23 06:05:41 +00005222 case ICmpInst::ICMP_UGT:
5223 case ICmpInst::ICMP_SGT:
5224 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00005225 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005226 case ICmpInst::ICMP_ULT:
5227 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00005228 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5229 InsertNewInstBefore(Not, I);
5230 return BinaryOperator::createAnd(Not, Op1);
5231 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005232 case ICmpInst::ICMP_UGE:
5233 case ICmpInst::ICMP_SGE:
5234 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00005235 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005236 case ICmpInst::ICMP_ULE:
5237 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00005238 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5239 InsertNewInstBefore(Not, I);
5240 return BinaryOperator::createOr(Not, Op1);
5241 }
5242 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005243 }
5244
Chris Lattner2dd01742004-06-09 04:24:29 +00005245 // See if we are doing a comparison between a constant and an instruction that
5246 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005247 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005248 switch (I.getPredicate()) {
5249 default: break;
5250 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5251 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005252 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005253 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5254 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5255 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5256 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5257 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005258
Reid Spencer266e42b2006-12-23 06:05:41 +00005259 case ICmpInst::ICMP_SLT:
5260 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005261 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005262 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5263 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5264 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5265 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5266 break;
5267
5268 case ICmpInst::ICMP_UGT:
5269 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005270 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005271 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5272 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5273 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5274 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5275 break;
5276
5277 case ICmpInst::ICMP_SGT:
5278 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005279 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005280 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5281 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5282 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5283 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5284 break;
5285
5286 case ICmpInst::ICMP_ULE:
5287 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005288 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005289 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5290 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5291 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5292 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5293 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005294
Reid Spencer266e42b2006-12-23 06:05:41 +00005295 case ICmpInst::ICMP_SLE:
5296 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005297 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005298 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5299 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5300 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5301 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5302 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005303
Reid Spencer266e42b2006-12-23 06:05:41 +00005304 case ICmpInst::ICMP_UGE:
5305 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005306 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005307 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5308 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5309 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5310 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5311 break;
5312
5313 case ICmpInst::ICMP_SGE:
5314 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005315 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005316 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5317 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5318 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5319 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5320 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005321 }
5322
Reid Spencer266e42b2006-12-23 06:05:41 +00005323 // If we still have a icmp le or icmp ge instruction, turn it into the
5324 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00005325 // already been handled above, this requires little checking.
5326 //
Reid Spencer266e42b2006-12-23 06:05:41 +00005327 if (I.getPredicate() == ICmpInst::ICMP_ULE)
5328 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5329 if (I.getPredicate() == ICmpInst::ICMP_SLE)
5330 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5331 if (I.getPredicate() == ICmpInst::ICMP_UGE)
5332 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5333 if (I.getPredicate() == ICmpInst::ICMP_SGE)
5334 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00005335
5336 // See if we can fold the comparison based on bits known to be zero or one
5337 // in the input.
5338 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005339 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00005340 KnownZero, KnownOne, 0))
5341 return &I;
5342
5343 // Given the known and unknown bits, compute a range that the LHS could be
5344 // in.
5345 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005346 // Compute the Min, Max and RHS values based on the known bits. For the
5347 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00005348 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
5349 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00005350 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5351 SRHSVal = CI->getSExtValue();
5352 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
5353 SMax);
5354 } else {
5355 URHSVal = CI->getZExtValue();
5356 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
5357 UMax);
5358 }
5359 switch (I.getPredicate()) { // LE/GE have been folded already.
5360 default: assert(0 && "Unknown icmp opcode!");
5361 case ICmpInst::ICMP_EQ:
5362 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005363 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005364 break;
5365 case ICmpInst::ICMP_NE:
5366 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005367 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005368 break;
5369 case ICmpInst::ICMP_ULT:
5370 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005371 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005372 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005373 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005374 break;
5375 case ICmpInst::ICMP_UGT:
5376 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005377 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005378 if (UMax < 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_SLT:
5382 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005383 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005384 if (SMin > SRHSVal)
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_SGT:
5388 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005389 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005390 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005391 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005392 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00005393 }
5394 }
5395
Reid Spencer266e42b2006-12-23 06:05:41 +00005396 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005397 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00005398 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00005399 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005400 switch (LHSI->getOpcode()) {
5401 case Instruction::And:
5402 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5403 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00005404 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5405
Reid Spencer266e42b2006-12-23 06:05:41 +00005406 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00005407 // and/compare to be the input width without changing the value
5408 // produced, eliminating a cast.
5409 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5410 // We can do this transformation if either the AND constant does not
5411 // have its sign bit set or if it is an equality comparison.
5412 // Extending a relational comparison when we're checking the sign
5413 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005414 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00005415 (I.isEquality() ||
5416 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
5417 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
5418 ConstantInt *NewCST;
5419 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00005420 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
5421 AndCST->getZExtValue());
5422 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
5423 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00005424 Instruction *NewAnd =
5425 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
5426 LHSI->getName());
5427 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005428 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00005429 }
5430 }
5431
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005432 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5433 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5434 // happens a LOT in code produced by the C front-end, for bitfield
5435 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00005436 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5437 if (Shift && !Shift->isShift())
5438 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00005439
Reid Spencere0fc4df2006-10-20 07:07:24 +00005440 ConstantInt *ShAmt;
5441 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00005442 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5443 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005444
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005445 // We can fold this as long as we can't shift unknown bits
5446 // into the mask. This can only happen with signed shift
5447 // rights, as they sign-extend.
5448 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005449 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005450 if (!CanFold) {
5451 // To test for the bad case of the signed shr, see if any
5452 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005453 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00005454 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5455
Reid Spencer2341c222007-02-02 02:16:23 +00005456 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005457 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00005458 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
5459 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005460 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5461 CanFold = true;
5462 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005463
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005464 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00005465 Constant *NewCst;
5466 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00005467 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005468 else
5469 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005470
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005471 // Check to see if we are shifting out any of the bits being
5472 // compared.
5473 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5474 // If we shifted bits out, the fold is not going to work out.
5475 // As a special case, check to see if this means that the
5476 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00005477 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005478 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005479 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005480 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005481 } else {
5482 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005483 Constant *NewAndCST;
5484 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00005485 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005486 else
5487 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5488 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00005489 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005490 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005491 AddUsesToWorkList(I);
5492 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00005493 }
5494 }
Chris Lattner35167c32004-06-09 07:59:58 +00005495 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005496
5497 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5498 // preferable because it allows the C<<Y expression to be hoisted out
5499 // of a loop if Y is invariant and X is not.
5500 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00005501 I.isEquality() && !Shift->isArithmeticShift() &&
5502 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005503 // Compute C << Y.
5504 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00005505 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005506 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00005507 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005508 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00005509 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00005510 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00005511 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005512 }
5513 InsertNewInstBefore(cast<Instruction>(NS), I);
5514
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005515 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00005516 Instruction *NewAnd = BinaryOperator::createAnd(
5517 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005518 InsertNewInstBefore(NewAnd, I);
5519
5520 I.setOperand(0, NewAnd);
5521 return &I;
5522 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005523 }
5524 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005525
Reid Spencer266e42b2006-12-23 06:05:41 +00005526 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005527 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005528 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005529 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5530
5531 // Check that the shift amount is in range. If not, don't perform
5532 // undefined shifts. When the shift is visited it will be
5533 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005534 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005535 break;
5536
Chris Lattner272d5ca2004-09-28 18:22:15 +00005537 // If we are comparing against bits always shifted out, the
5538 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005539 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00005540 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00005541 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005542 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005543 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00005544 return ReplaceInstUsesWith(I, Cst);
5545 }
5546
5547 if (LHSI->hasOneUse()) {
5548 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005549 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005550 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00005551 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005552
Chris Lattner272d5ca2004-09-28 18:22:15 +00005553 Instruction *AndI =
5554 BinaryOperator::createAnd(LHSI->getOperand(0),
5555 Mask, LHSI->getName()+".mask");
5556 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005557 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00005558 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00005559 }
5560 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00005561 }
5562 break;
5563
Reid Spencer266e42b2006-12-23 06:05:41 +00005564 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00005565 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00005566 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005567 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005568 // Check that the shift amount is in range. If not, don't perform
5569 // undefined shifts. When the shift is visited it will be
5570 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00005571 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005572 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005573 break;
5574
Chris Lattner1023b872004-09-27 16:18:50 +00005575 // If we are comparing against bits always shifted out, the
5576 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00005577 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00005578 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00005579 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5580 ShAmt);
5581 else
5582 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5583 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005584
Chris Lattner1023b872004-09-27 16:18:50 +00005585 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005586 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005587 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00005588 return ReplaceInstUsesWith(I, Cst);
5589 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005590
Chris Lattner1023b872004-09-27 16:18:50 +00005591 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005592 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005593
Chris Lattner1023b872004-09-27 16:18:50 +00005594 // Otherwise strength reduce the shift into an and.
5595 uint64_t Val = ~0ULL; // All ones.
5596 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00005597 Val &= ~0ULL >> (64-TypeBits);
5598 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005599
Chris Lattner1023b872004-09-27 16:18:50 +00005600 Instruction *AndI =
5601 BinaryOperator::createAnd(LHSI->getOperand(0),
5602 Mask, LHSI->getName()+".mask");
5603 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005604 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00005605 ConstantExpr::getShl(CI, ShAmt));
5606 }
Chris Lattner1023b872004-09-27 16:18:50 +00005607 }
5608 }
5609 break;
Chris Lattner7e794272004-09-24 15:21:34 +00005610
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005611 case Instruction::SDiv:
5612 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00005613 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005614 // Fold this div into the comparison, producing a range check.
5615 // Determine, based on the divide type, what the range is being
5616 // checked. If there is an overflow on the low or high side, remember
5617 // it, otherwise compute the range [low, hi) bounding the new value.
5618 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005619 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005620 // FIXME: If the operand types don't match the type of the divide
5621 // then don't attempt this transform. The code below doesn't have the
5622 // logic to deal with a signed divide and an unsigned compare (and
5623 // vice versa). This is because (x /s C1) <s C2 produces different
5624 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5625 // (x /u C1) <u C2. Simply casting the operands and result won't
5626 // work. :( The if statement below tests that condition and bails
5627 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00005628 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5629 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005630 break;
5631
5632 // Initialize the variables that will indicate the nature of the
5633 // range check.
5634 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005635 ConstantInt *LoBound = 0, *HiBound = 0;
5636
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005637 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5638 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5639 // C2 (CI). By solving for X we can turn this into a range check
5640 // instead of computing a divide.
5641 ConstantInt *Prod =
5642 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00005643
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005644 // Determine if the product overflows by seeing if the product is
5645 // not equal to the divide. Make sure we do the same kind of divide
5646 // as in the LHS instruction that we're folding.
5647 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00005648 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005649 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5650
Reid Spencer266e42b2006-12-23 06:05:41 +00005651 // Get the ICmp opcode
5652 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00005653
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005654 if (DivRHS->isNullValue()) {
5655 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00005656 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00005657 LoBound = Prod;
5658 LoOverflow = ProdOV;
5659 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005660 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005661 if (CI->isNullValue()) { // (X / pos) op 0
5662 // Can't overflow.
5663 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5664 HiBound = DivRHS;
5665 } else if (isPositive(CI)) { // (X / pos) op pos
5666 LoBound = Prod;
5667 LoOverflow = ProdOV;
5668 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5669 } else { // (X / pos) op neg
5670 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5671 LoOverflow = AddWithOverflow(LoBound, Prod,
5672 cast<ConstantInt>(DivRHSH));
5673 HiBound = Prod;
5674 HiOverflow = ProdOV;
5675 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005676 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005677 if (CI->isNullValue()) { // (X / neg) op 0
5678 LoBound = AddOne(DivRHS);
5679 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005680 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005681 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00005682 } else if (isPositive(CI)) { // (X / neg) op pos
5683 HiOverflow = LoOverflow = ProdOV;
5684 if (!LoOverflow)
5685 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5686 HiBound = AddOne(Prod);
5687 } else { // (X / neg) op neg
5688 LoBound = Prod;
5689 LoOverflow = HiOverflow = ProdOV;
5690 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5691 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005692
Chris Lattnera92af962004-10-11 19:40:04 +00005693 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005694 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005695 }
5696
5697 if (LoBound) {
5698 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005699 switch (predicate) {
5700 default: assert(0 && "Unhandled icmp opcode!");
5701 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005702 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005703 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005704 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005705 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5706 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005707 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005708 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5709 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005710 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005711 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5712 true, I);
5713 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005714 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005715 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005716 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005717 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5718 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005719 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005720 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5721 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005722 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005723 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5724 false, I);
5725 case ICmpInst::ICMP_ULT:
5726 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005727 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005728 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005729 return new ICmpInst(predicate, X, LoBound);
5730 case ICmpInst::ICMP_UGT:
5731 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005732 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005734 if (predicate == ICmpInst::ICMP_UGT)
5735 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5736 else
5737 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005738 }
5739 }
5740 }
5741 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005742 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005743
Reid Spencer266e42b2006-12-23 06:05:41 +00005744 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005745 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005746 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005747
Reid Spencere0fc4df2006-10-20 07:07:24 +00005748 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5749 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005750 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5751 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005752 case Instruction::SRem:
5753 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5754 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5755 BO->hasOneUse()) {
5756 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5757 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005758 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5759 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005760 return new ICmpInst(I.getPredicate(), NewRem,
5761 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005762 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005763 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005764 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005765 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005766 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5767 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005768 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005769 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5770 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005771 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005772 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5773 // efficiently invertible, or if the add has just this one use.
5774 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005775
Chris Lattnerc992add2003-08-13 05:33:12 +00005776 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005777 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005778 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005779 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005780 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005781 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005782 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005783 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005784 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005785 }
5786 }
5787 break;
5788 case Instruction::Xor:
5789 // For the xor case, we can xor two constants together, eliminating
5790 // the explicit xor.
5791 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005792 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5793 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005794
5795 // FALLTHROUGH
5796 case Instruction::Sub:
5797 // Replace (([sub|xor] A, B) != 0) with (A != B)
5798 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005799 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5800 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005801 break;
5802
5803 case Instruction::Or:
5804 // If bits are being or'd in that are not present in the constant we
5805 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005806 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005807 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005808 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005809 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5810 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005811 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005812 break;
5813
5814 case Instruction::And:
5815 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005816 // If bits are being compared against that are and'd out, then the
5817 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005818 if (!ConstantExpr::getAnd(CI,
5819 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005820 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5821 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005822
Chris Lattner35167c32004-06-09 07:59:58 +00005823 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005824 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005825 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5826 ICmpInst::ICMP_NE, Op0,
5827 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005828
Reid Spencer266e42b2006-12-23 06:05:41 +00005829 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005830 if (isSignBit(BOC)) {
5831 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005832 Constant *Zero = Constant::getNullValue(X->getType());
5833 ICmpInst::Predicate pred = isICMP_NE ?
5834 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5835 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005836 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005837
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005838 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005839 if (CI->isNullValue() && isHighOnes(BOC)) {
5840 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005841 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005842 ICmpInst::Predicate pred = isICMP_NE ?
5843 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5844 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005845 }
5846
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005847 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005848 default: break;
5849 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005850 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5851 // Handle set{eq|ne} <intrinsic>, intcst.
5852 switch (II->getIntrinsicID()) {
5853 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005854 case Intrinsic::bswap_i16:
5855 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005856 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005857 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005858 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005859 ByteSwap_16(CI->getZExtValue())));
5860 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005861 case Intrinsic::bswap_i32:
5862 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005863 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005864 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005865 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005866 ByteSwap_32(CI->getZExtValue())));
5867 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005868 case Intrinsic::bswap_i64:
5869 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005870 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005871 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005872 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005873 ByteSwap_64(CI->getZExtValue())));
5874 return &I;
5875 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005876 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005877 } else { // Not a ICMP_EQ/ICMP_NE
5878 // If the LHS is a cast from an integral value of the same size, then
5879 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005880 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5881 Value *CastOp = Cast->getOperand(0);
5882 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005883 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005884 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005885 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005886 // If this is an unsigned comparison, try to make the comparison use
5887 // smaller constant values.
5888 switch (I.getPredicate()) {
5889 default: break;
5890 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5891 ConstantInt *CUI = cast<ConstantInt>(CI);
5892 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5893 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer24f1a0e2007-03-01 19:33:52 +00005894 ConstantInt::get(SrcTy, -1ULL));
Reid Spencer266e42b2006-12-23 06:05:41 +00005895 break;
5896 }
5897 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5898 ConstantInt *CUI = cast<ConstantInt>(CI);
5899 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5900 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5901 Constant::getNullValue(SrcTy));
5902 break;
5903 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005904 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005905
Chris Lattner2b55ea32004-02-23 07:16:20 +00005906 }
5907 }
Chris Lattnere967b342003-06-04 05:10:11 +00005908 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005909 }
5910
Reid Spencer266e42b2006-12-23 06:05:41 +00005911 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005912 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5913 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5914 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005915 case Instruction::GetElementPtr:
5916 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005917 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005918 bool isAllZeros = true;
5919 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5920 if (!isa<Constant>(LHSI->getOperand(i)) ||
5921 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5922 isAllZeros = false;
5923 break;
5924 }
5925 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005926 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005927 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5928 }
5929 break;
5930
Chris Lattner77c32c32005-04-23 15:31:55 +00005931 case Instruction::PHI:
5932 if (Instruction *NV = FoldOpIntoPhi(I))
5933 return NV;
5934 break;
5935 case Instruction::Select:
5936 // If either operand of the select is a constant, we can fold the
5937 // comparison into the select arms, which will cause one to be
5938 // constant folded and the select turned into a bitwise or.
5939 Value *Op1 = 0, *Op2 = 0;
5940 if (LHSI->hasOneUse()) {
5941 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5942 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005943 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5944 // Insert a new ICmp of the other select operand.
5945 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5946 LHSI->getOperand(2), RHSC,
5947 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005948 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5949 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005950 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5951 // Insert a new ICmp of the other select operand.
5952 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5953 LHSI->getOperand(1), RHSC,
5954 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005955 }
5956 }
Jeff Cohen82639852005-04-23 21:38:35 +00005957
Chris Lattner77c32c32005-04-23 15:31:55 +00005958 if (Op1)
5959 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5960 break;
5961 }
5962 }
5963
Reid Spencer266e42b2006-12-23 06:05:41 +00005964 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005965 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005966 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005967 return NI;
5968 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005969 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5970 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005971 return NI;
5972
Reid Spencer266e42b2006-12-23 06:05:41 +00005973 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005974 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5975 // now.
5976 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5977 if (isa<PointerType>(Op0->getType()) &&
5978 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005979 // We keep moving the cast from the left operand over to the right
5980 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005981 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005982
Chris Lattner64d87b02007-01-06 01:45:59 +00005983 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5984 // so eliminate it as well.
5985 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5986 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005987
Chris Lattner16930792003-11-03 04:25:02 +00005988 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005989 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005990 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005991 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005992 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005993 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005994 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005995 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005996 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005997 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005998 }
5999
6000 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006001 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00006002 // This comes up when you have code like
6003 // int X = A < B;
6004 // if (X) ...
6005 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006006 // with a constant or another cast from the same type.
6007 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006008 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006009 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00006010 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006011
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006012 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006013 Value *A, *B, *C, *D;
6014 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6015 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6016 Value *OtherVal = A == Op1 ? B : A;
6017 return new ICmpInst(I.getPredicate(), OtherVal,
6018 Constant::getNullValue(A->getType()));
6019 }
6020
6021 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6022 // A^c1 == C^c2 --> A == C^(c1^c2)
6023 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6024 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6025 if (Op1->hasOneUse()) {
6026 Constant *NC = ConstantExpr::getXor(C1, C2);
6027 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6028 return new ICmpInst(I.getPredicate(), A,
6029 InsertNewInstBefore(Xor, I));
6030 }
6031
6032 // A^B == A^D -> B == D
6033 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6034 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6035 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6036 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6037 }
6038 }
6039
6040 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6041 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006042 // A == (A^B) -> B == 0
6043 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00006044 return new ICmpInst(I.getPredicate(), OtherVal,
6045 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006046 }
6047 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006048 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006049 return new ICmpInst(I.getPredicate(), B,
6050 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006051 }
6052 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006053 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006054 return new ICmpInst(I.getPredicate(), B,
6055 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006056 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006057
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006058 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6059 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6060 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6061 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6062 Value *X = 0, *Y = 0, *Z = 0;
6063
6064 if (A == C) {
6065 X = B; Y = D; Z = A;
6066 } else if (A == D) {
6067 X = B; Y = C; Z = A;
6068 } else if (B == C) {
6069 X = A; Y = D; Z = B;
6070 } else if (B == D) {
6071 X = A; Y = C; Z = B;
6072 }
6073
6074 if (X) { // Build (X^Y) & Z
6075 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6076 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6077 I.setOperand(0, Op1);
6078 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6079 return &I;
6080 }
6081 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006082 }
Chris Lattner113f4f42002-06-25 16:13:24 +00006083 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006084}
6085
Reid Spencer266e42b2006-12-23 06:05:41 +00006086// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006087// We only handle extending casts so far.
6088//
Reid Spencer266e42b2006-12-23 06:05:41 +00006089Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6090 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006091 Value *LHSCIOp = LHSCI->getOperand(0);
6092 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00006093 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006094 Value *RHSCIOp;
6095
Reid Spencer266e42b2006-12-23 06:05:41 +00006096 // We only handle extension cast instructions, so far. Enforce this.
6097 if (LHSCI->getOpcode() != Instruction::ZExt &&
6098 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00006099 return 0;
6100
Reid Spencer266e42b2006-12-23 06:05:41 +00006101 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6102 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006103
Reid Spencer266e42b2006-12-23 06:05:41 +00006104 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006105 // Not an extension from the same type?
6106 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006107 if (RHSCIOp->getType() != LHSCIOp->getType())
6108 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00006109
6110 // If the signedness of the two compares doesn't agree (i.e. one is a sext
6111 // and the other is a zext), then we can't handle this.
6112 if (CI->getOpcode() != LHSCI->getOpcode())
6113 return 0;
6114
6115 // Likewise, if the signedness of the [sz]exts and the compare don't match,
6116 // then we can't handle this.
6117 if (isSignedExt != isSignedCmp && !ICI.isEquality())
6118 return 0;
6119
6120 // Okay, just insert a compare of the reduced operands now!
6121 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00006122 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006123
Reid Spencer266e42b2006-12-23 06:05:41 +00006124 // If we aren't dealing with a constant on the RHS, exit early
6125 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6126 if (!CI)
6127 return 0;
6128
6129 // Compute the constant that would happen if we truncated to SrcTy then
6130 // reextended to DestTy.
6131 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6132 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6133
6134 // If the re-extended constant didn't change...
6135 if (Res2 == CI) {
6136 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6137 // For example, we might have:
6138 // %A = sext short %X to uint
6139 // %B = icmp ugt uint %A, 1330
6140 // It is incorrect to transform this into
6141 // %B = icmp ugt short %X, 1330
6142 // because %A may have negative value.
6143 //
6144 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6145 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00006146 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00006147 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6148 else
6149 return 0;
6150 }
6151
6152 // The re-extended constant changed so the constant cannot be represented
6153 // in the shorter type. Consequently, we cannot emit a simple comparison.
6154
6155 // First, handle some easy cases. We know the result cannot be equal at this
6156 // point so handle the ICI.isEquality() cases
6157 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006158 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00006159 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006160 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00006161
6162 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6163 // should have been folded away previously and not enter in here.
6164 Value *Result;
6165 if (isSignedCmp) {
6166 // We're performing a signed comparison.
6167 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006168 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00006169 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00006170 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006171 } else {
6172 // We're performing an unsigned comparison.
6173 if (isSignedExt) {
6174 // We're performing an unsigned comp with a sign extended value.
6175 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00006176 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00006177 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6178 NegOne, ICI.getName()), ICI);
6179 } else {
6180 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006181 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006182 }
6183 }
6184
6185 // Finally, return the value computed.
6186 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6187 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6188 return ReplaceInstUsesWith(ICI, Result);
6189 } else {
6190 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6191 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6192 "ICmp should be folded!");
6193 if (Constant *CI = dyn_cast<Constant>(Result))
6194 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6195 else
6196 return BinaryOperator::createNot(Result);
6197 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006198}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006199
Reid Spencer2341c222007-02-02 02:16:23 +00006200Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6201 return commonShiftTransforms(I);
6202}
6203
6204Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6205 return commonShiftTransforms(I);
6206}
6207
6208Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6209 return commonShiftTransforms(I);
6210}
6211
6212Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6213 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00006214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006215
6216 // shl X, 0 == X and shr X, 0 == X
6217 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00006218 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00006219 Op0 == Constant::getNullValue(Op0->getType()))
6220 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006221
Reid Spencer266e42b2006-12-23 06:05:41 +00006222 if (isa<UndefValue>(Op0)) {
6223 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00006224 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006225 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006226 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6227 }
6228 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006229 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6230 return ReplaceInstUsesWith(I, Op0);
6231 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00006233 }
6234
Chris Lattnerd4dee402006-11-10 23:38:52 +00006235 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6236 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00006237 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00006238 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006239 return ReplaceInstUsesWith(I, CSI);
6240
Chris Lattner183b3362004-04-09 19:05:30 +00006241 // Try to fold constant and into select arguments.
6242 if (isa<Constant>(Op0))
6243 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00006244 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00006245 return R;
6246
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00006247 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006248 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00006249 if (MaskedValueIsZero(Op0,
6250 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006251 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00006252 }
6253 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006254
Reid Spencere0fc4df2006-10-20 07:07:24 +00006255 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00006256 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6257 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00006258 return 0;
6259}
6260
Reid Spencere0fc4df2006-10-20 07:07:24 +00006261Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00006262 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006263 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00006264
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006265 // See if we can simplify any instructions used by the instruction whose sole
6266 // purpose is to compute bits we don't care about.
6267 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006268 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006269 KnownZero, KnownOne))
6270 return &I;
6271
Chris Lattner14553932006-01-06 07:12:35 +00006272 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6273 // of a signed value.
6274 //
6275 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006276 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006277 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00006278 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6279 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006280 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00006281 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00006282 }
Chris Lattner14553932006-01-06 07:12:35 +00006283 }
6284
6285 // ((X*C1) << C2) == (X * (C1 << C2))
6286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6287 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6288 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6289 return BinaryOperator::createMul(BO->getOperand(0),
6290 ConstantExpr::getShl(BOOp, Op1));
6291
6292 // Try to fold constant and into select arguments.
6293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6295 return R;
6296 if (isa<PHINode>(Op0))
6297 if (Instruction *NV = FoldOpIntoPhi(I))
6298 return NV;
6299
6300 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00006301 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6302 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6303 Value *V1, *V2;
6304 ConstantInt *CC;
6305 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006306 default: break;
6307 case Instruction::Add:
6308 case Instruction::And:
6309 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00006310 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006311 // These operators commute.
6312 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006313 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6314 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00006315 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006316 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00006317 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00006318 Op0BO->getName());
6319 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006320 Instruction *X =
6321 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6322 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006323 InsertNewInstBefore(X, I); // (X + (Y << C))
6324 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00006325 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00006326 return BinaryOperator::createAnd(X, C2);
6327 }
Chris Lattner14553932006-01-06 07:12:35 +00006328
Chris Lattner797dee72005-09-18 06:30:59 +00006329 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00006330 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006331 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00006332 match(Op0BOOp1,
6333 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006334 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6335 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006336 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006337 Op0BO->getOperand(0), Op1,
6338 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006339 InsertNewInstBefore(YS, I); // (Y << C)
6340 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006341 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006342 V1->getName()+".mask");
6343 InsertNewInstBefore(XM, I); // X & (CC << C)
6344
6345 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6346 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006347 }
Chris Lattner14553932006-01-06 07:12:35 +00006348
Reid Spencer2f34b982007-02-02 14:41:37 +00006349 // FALL THROUGH.
6350 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006351 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006352 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6353 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00006354 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006355 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006356 Op0BO->getOperand(1), Op1,
6357 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006358 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006359 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00006360 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006361 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006362 InsertNewInstBefore(X, I); // (X + (Y << C))
6363 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00006364 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00006365 return BinaryOperator::createAnd(X, C2);
6366 }
Chris Lattner14553932006-01-06 07:12:35 +00006367
Chris Lattner1df0e982006-05-31 21:14:00 +00006368 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006369 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6370 match(Op0BO->getOperand(0),
6371 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00006372 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006373 cast<BinaryOperator>(Op0BO->getOperand(0))
6374 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006375 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006376 Op0BO->getOperand(1), Op1,
6377 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006378 InsertNewInstBefore(YS, I); // (Y << C)
6379 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006380 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006381 V1->getName()+".mask");
6382 InsertNewInstBefore(XM, I); // X & (CC << C)
6383
Chris Lattner1df0e982006-05-31 21:14:00 +00006384 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00006385 }
Chris Lattner14553932006-01-06 07:12:35 +00006386
Chris Lattner27cb9db2005-09-18 05:12:10 +00006387 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00006388 }
Chris Lattner14553932006-01-06 07:12:35 +00006389 }
6390
6391
6392 // If the operand is an bitwise operator with a constant RHS, and the
6393 // shift is the only use, we can pull it out of the shift.
6394 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6395 bool isValid = true; // Valid only for And, Or, Xor
6396 bool highBitSet = false; // Transform if high bit of constant set?
6397
6398 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006399 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00006400 case Instruction::Add:
6401 isValid = isLeftShift;
6402 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006403 case Instruction::Or:
6404 case Instruction::Xor:
6405 highBitSet = false;
6406 break;
6407 case Instruction::And:
6408 highBitSet = true;
6409 break;
Chris Lattner14553932006-01-06 07:12:35 +00006410 }
6411
6412 // If this is a signed shift right, and the high bit is modified
6413 // by the logical operation, do not perform the transformation.
6414 // The highBitSet boolean indicates the value of the high bit of
6415 // the constant which would cause it to be modified for this
6416 // operation.
6417 //
Chris Lattner3e009e82007-02-05 00:57:54 +00006418 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006419 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00006420 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
6421 }
6422
6423 if (isValid) {
6424 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6425
6426 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006427 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00006428 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006429 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00006430
6431 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6432 NewRHS);
6433 }
6434 }
6435 }
6436 }
6437
Chris Lattnereb372a02006-01-06 07:52:12 +00006438 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00006439 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6440 if (ShiftOp && !ShiftOp->isShift())
6441 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00006442
Reid Spencere0fc4df2006-10-20 07:07:24 +00006443 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006444 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006445 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6446 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00006447 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6448 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6449 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00006450
Chris Lattner3e009e82007-02-05 00:57:54 +00006451 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6452 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
6453 AmtSum = I.getType()->getPrimitiveSizeInBits();
6454
6455 const IntegerType *Ty = cast<IntegerType>(I.getType());
6456
6457 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00006458 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00006459 return BinaryOperator::create(I.getOpcode(), X,
6460 ConstantInt::get(Ty, AmtSum));
6461 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6462 I.getOpcode() == Instruction::AShr) {
6463 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6464 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6465 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6466 I.getOpcode() == Instruction::LShr) {
6467 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6468 Instruction *Shift =
6469 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6470 InsertNewInstBefore(Shift, I);
6471
6472 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6473 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006474 }
6475
Chris Lattner3e009e82007-02-05 00:57:54 +00006476 // Okay, if we get here, one shift must be left, and the other shift must be
6477 // right. See if the amounts are equal.
6478 if (ShiftAmt1 == ShiftAmt2) {
6479 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6480 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00006481 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00006482 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6483 }
6484 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6485 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00006486 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00006487 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6488 }
6489 // We can simplify ((X << C) >>s C) into a trunc + sext.
6490 // NOTE: we could do this for any C, but that would make 'unusual' integer
6491 // types. For now, just stick to ones well-supported by the code
6492 // generators.
6493 const Type *SExtType = 0;
6494 switch (Ty->getBitWidth() - ShiftAmt1) {
6495 case 8 : SExtType = Type::Int8Ty; break;
6496 case 16: SExtType = Type::Int16Ty; break;
6497 case 32: SExtType = Type::Int32Ty; break;
6498 default: break;
6499 }
6500 if (SExtType) {
6501 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6502 InsertNewInstBefore(NewTrunc, I);
6503 return new SExtInst(NewTrunc, Ty);
6504 }
6505 // Otherwise, we can't handle it yet.
6506 } else if (ShiftAmt1 < ShiftAmt2) {
6507 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00006508
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006509 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006510 if (I.getOpcode() == Instruction::Shl) {
6511 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6512 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006513 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00006514 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006515 InsertNewInstBefore(Shift, I);
6516
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006517 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006518 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006519 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006520
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006521 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006522 if (I.getOpcode() == Instruction::LShr) {
6523 assert(ShiftOp->getOpcode() == Instruction::Shl);
6524 Instruction *Shift =
6525 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6526 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00006527
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006528 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006529 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006530 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006531
6532 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6533 } else {
6534 assert(ShiftAmt2 < ShiftAmt1);
6535 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6536
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006537 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006538 if (I.getOpcode() == Instruction::Shl) {
6539 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6540 ShiftOp->getOpcode() == Instruction::AShr);
6541 Instruction *Shift =
6542 BinaryOperator::create(ShiftOp->getOpcode(), X,
6543 ConstantInt::get(Ty, ShiftDiff));
6544 InsertNewInstBefore(Shift, I);
6545
6546 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6547 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6548 }
6549
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006550 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006551 if (I.getOpcode() == Instruction::LShr) {
6552 assert(ShiftOp->getOpcode() == Instruction::Shl);
6553 Instruction *Shift =
6554 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6555 InsertNewInstBefore(Shift, I);
6556
6557 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6558 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6559 }
6560
6561 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006562 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006563 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006564 return 0;
6565}
6566
Chris Lattner48a44f72002-05-02 17:06:02 +00006567
Chris Lattner8f663e82005-10-29 04:36:15 +00006568/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6569/// expression. If so, decompose it, returning some value X, such that Val is
6570/// X*Scale+Offset.
6571///
6572static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6573 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006574 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006575 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006576 Offset = CI->getZExtValue();
6577 Scale = 1;
6578 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006579 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6580 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006581 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006582 if (I->getOpcode() == Instruction::Shl) {
6583 // This is a value scaled by '1 << the shift amt'.
6584 Scale = 1U << CUI->getZExtValue();
6585 Offset = 0;
6586 return I->getOperand(0);
6587 } else if (I->getOpcode() == Instruction::Mul) {
6588 // This value is scaled by 'CUI'.
6589 Scale = CUI->getZExtValue();
6590 Offset = 0;
6591 return I->getOperand(0);
6592 } else if (I->getOpcode() == Instruction::Add) {
6593 // We have X+C. Check to see if we really have (X*C2)+C1,
6594 // where C1 is divisible by C2.
6595 unsigned SubScale;
6596 Value *SubVal =
6597 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6598 Offset += CUI->getZExtValue();
6599 if (SubScale > 1 && (Offset % SubScale == 0)) {
6600 Scale = SubScale;
6601 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006602 }
6603 }
6604 }
6605 }
6606 }
6607
6608 // Otherwise, we can't look past this.
6609 Scale = 1;
6610 Offset = 0;
6611 return Val;
6612}
6613
6614
Chris Lattner216be912005-10-24 06:03:58 +00006615/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6616/// try to eliminate the cast by moving the type information into the alloc.
6617Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6618 AllocationInst &AI) {
6619 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006620 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006621
Chris Lattnerac87beb2005-10-24 06:22:12 +00006622 // Remove any uses of AI that are dead.
6623 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006624
Chris Lattnerac87beb2005-10-24 06:22:12 +00006625 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6626 Instruction *User = cast<Instruction>(*UI++);
6627 if (isInstructionTriviallyDead(User)) {
6628 while (UI != E && *UI == User)
6629 ++UI; // If this instruction uses AI more than once, don't break UI.
6630
Chris Lattnerac87beb2005-10-24 06:22:12 +00006631 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006632 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006633 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006634 }
6635 }
6636
Chris Lattner216be912005-10-24 06:03:58 +00006637 // Get the type really allocated and the type casted to.
6638 const Type *AllocElTy = AI.getAllocatedType();
6639 const Type *CastElTy = PTy->getElementType();
6640 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006641
Chris Lattner945e4372007-02-14 05:52:17 +00006642 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6643 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006644 if (CastElTyAlign < AllocElTyAlign) return 0;
6645
Chris Lattner46705b22005-10-24 06:35:18 +00006646 // If the allocation has multiple uses, only promote it if we are strictly
6647 // increasing the alignment of the resultant allocation. If we keep it the
6648 // same, we open the door to infinite loops of various kinds.
6649 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6650
Chris Lattner216be912005-10-24 06:03:58 +00006651 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6652 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006653 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006654
Chris Lattner8270c332005-10-29 03:19:53 +00006655 // See if we can satisfy the modulus by pulling a scale out of the array
6656 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00006657 unsigned ArraySizeScale, ArrayOffset;
6658 Value *NumElements = // See if the array size is a decomposable linear expr.
6659 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6660
Chris Lattner8270c332005-10-29 03:19:53 +00006661 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6662 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006663 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6664 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006665
Chris Lattner8270c332005-10-29 03:19:53 +00006666 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6667 Value *Amt = 0;
6668 if (Scale == 1) {
6669 Amt = NumElements;
6670 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006671 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006672 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6673 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006674 Amt = ConstantExpr::getMul(
6675 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6676 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006677 else if (Scale != 1) {
6678 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6679 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006680 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006681 }
6682
Chris Lattner8f663e82005-10-29 04:36:15 +00006683 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006684 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006685 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6686 Amt = InsertNewInstBefore(Tmp, AI);
6687 }
6688
Chris Lattner216be912005-10-24 06:03:58 +00006689 AllocationInst *New;
6690 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006691 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006692 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006693 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006694 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006695 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006696
6697 // If the allocation has multiple uses, insert a cast and change all things
6698 // that used it to use the new cast. This will also hack on CI, but it will
6699 // die soon.
6700 if (!AI.hasOneUse()) {
6701 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006702 // New is the allocation instruction, pointer typed. AI is the original
6703 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6704 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006705 InsertNewInstBefore(NewCast, AI);
6706 AI.replaceAllUsesWith(NewCast);
6707 }
Chris Lattner216be912005-10-24 06:03:58 +00006708 return ReplaceInstUsesWith(CI, New);
6709}
6710
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006711/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006712/// and return it as type Ty without inserting any new casts and without
6713/// changing the computed value. This is used by code that tries to decide
6714/// whether promoting or shrinking integer operations to wider or smaller types
6715/// will allow us to eliminate a truncate or extend.
6716///
6717/// This is a truncation operation if Ty is smaller than V->getType(), or an
6718/// extension operation if Ty is larger.
6719static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006720 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006721 // We can always evaluate constants in another type.
6722 if (isa<ConstantInt>(V))
6723 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006724
6725 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006726 if (!I) return false;
6727
6728 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006729
6730 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006731 case Instruction::Add:
6732 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006733 case Instruction::And:
6734 case Instruction::Or:
6735 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006736 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006737 // These operators can all arbitrarily be extended or truncated.
6738 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6739 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006740
Chris Lattner960acb02006-11-29 07:18:39 +00006741 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006742 if (!I->hasOneUse()) return false;
6743 // If we are truncating the result of this SHL, and if it's a shift of a
6744 // constant amount, we can always perform a SHL in a smaller type.
6745 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6746 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6747 CI->getZExtValue() < Ty->getBitWidth())
6748 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6749 }
6750 break;
6751 case Instruction::LShr:
6752 if (!I->hasOneUse()) return false;
6753 // If this is a truncate of a logical shr, we can truncate it to a smaller
6754 // lshr iff we know that the bits we would otherwise be shifting in are
6755 // already zeros.
6756 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6757 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6758 MaskedValueIsZero(I->getOperand(0),
6759 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6760 CI->getZExtValue() < Ty->getBitWidth()) {
6761 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6762 }
6763 }
Chris Lattner960acb02006-11-29 07:18:39 +00006764 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006765 case Instruction::Trunc:
6766 case Instruction::ZExt:
6767 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006768 // If this is a cast from the destination type, we can trivially eliminate
6769 // it, and this will remove a cast overall.
6770 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006771 // If the first operand is itself a cast, and is eliminable, do not count
6772 // this as an eliminable cast. We would prefer to eliminate those two
6773 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006774 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006775 return true;
6776
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006777 ++NumCastsRemoved;
6778 return true;
6779 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006780 break;
6781 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006782 // TODO: Can handle more cases here.
6783 break;
6784 }
6785
6786 return false;
6787}
6788
6789/// EvaluateInDifferentType - Given an expression that
6790/// CanEvaluateInDifferentType returns true for, actually insert the code to
6791/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006792Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006793 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006794 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006795 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006796
6797 // Otherwise, it must be an instruction.
6798 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006799 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006800 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006801 case Instruction::Add:
6802 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006803 case Instruction::And:
6804 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006805 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006806 case Instruction::AShr:
6807 case Instruction::LShr:
6808 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006809 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006810 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6811 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6812 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006813 break;
6814 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006815 case Instruction::Trunc:
6816 case Instruction::ZExt:
6817 case Instruction::SExt:
6818 case Instruction::BitCast:
6819 // If the source type of the cast is the type we're trying for then we can
6820 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006821 if (I->getOperand(0)->getType() == Ty)
6822 return I->getOperand(0);
6823
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006824 // Some other kind of cast, which shouldn't happen, so just ..
6825 // FALL THROUGH
6826 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006827 // TODO: Can handle more cases here.
6828 assert(0 && "Unreachable!");
6829 break;
6830 }
6831
6832 return InsertNewInstBefore(Res, *I);
6833}
6834
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006835/// @brief Implement the transforms common to all CastInst visitors.
6836Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006837 Value *Src = CI.getOperand(0);
6838
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006839 // Casting undef to anything results in undef so might as just replace it and
6840 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006841 if (isa<UndefValue>(Src)) // cast undef -> undef
6842 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6843
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006844 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6845 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006846 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006847 if (Instruction::CastOps opc =
6848 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6849 // The first cast (CSrc) is eliminable so we need to fix up or replace
6850 // the second cast (CI). CSrc will then have a good chance of being dead.
6851 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006852 }
6853 }
Chris Lattner03841652004-05-25 04:29:21 +00006854
Chris Lattnerd0d51602003-06-21 23:12:02 +00006855 // If casting the result of a getelementptr instruction with no offset, turn
6856 // this into a cast of the original pointer!
6857 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006858 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006859 bool AllZeroOperands = true;
6860 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6861 if (!isa<Constant>(GEP->getOperand(i)) ||
6862 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6863 AllZeroOperands = false;
6864 break;
6865 }
6866 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006867 // Changing the cast operand is usually not a good idea but it is safe
6868 // here because the pointer operand is being replaced with another
6869 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006870 CI.setOperand(0, GEP->getOperand(0));
6871 return &CI;
6872 }
6873 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006874
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006875 // If we are casting a malloc or alloca to a pointer to a type of the same
6876 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006877 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006878 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6879 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006880
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006881 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006882 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6883 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6884 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006885
6886 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006887 if (isa<PHINode>(Src))
6888 if (Instruction *NV = FoldOpIntoPhi(CI))
6889 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006890
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006891 return 0;
6892}
6893
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006894/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6895/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006896/// cases.
6897/// @brief Implement the transforms common to CastInst with integer operands
6898Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6899 if (Instruction *Result = commonCastTransforms(CI))
6900 return Result;
6901
6902 Value *Src = CI.getOperand(0);
6903 const Type *SrcTy = Src->getType();
6904 const Type *DestTy = CI.getType();
6905 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6906 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6907
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006908 // See if we can simplify any instructions used by the LHS whose sole
6909 // purpose is to compute bits we don't care about.
6910 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006911 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006912 KnownZero, KnownOne))
6913 return &CI;
6914
6915 // If the source isn't an instruction or has more than one use then we
6916 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006917 Instruction *SrcI = dyn_cast<Instruction>(Src);
6918 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006919 return 0;
6920
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006921 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006922 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006923 if (!isa<BitCastInst>(CI) &&
6924 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6925 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006926 // If this cast is a truncate, evaluting in a different type always
6927 // eliminates the cast, so it is always a win. If this is a noop-cast
6928 // this just removes a noop cast which isn't pointful, but simplifies
6929 // the code. If this is a zero-extension, we need to do an AND to
6930 // maintain the clear top-part of the computation, so we require that
6931 // the input have eliminated at least one cast. If this is a sign
6932 // extension, we insert two new casts (to do the extension) so we
6933 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006934 bool DoXForm;
6935 switch (CI.getOpcode()) {
6936 default:
6937 // All the others use floating point so we shouldn't actually
6938 // get here because of the check above.
6939 assert(0 && "Unknown cast type");
6940 case Instruction::Trunc:
6941 DoXForm = true;
6942 break;
6943 case Instruction::ZExt:
6944 DoXForm = NumCastsRemoved >= 1;
6945 break;
6946 case Instruction::SExt:
6947 DoXForm = NumCastsRemoved >= 2;
6948 break;
6949 case Instruction::BitCast:
6950 DoXForm = false;
6951 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006952 }
6953
6954 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006955 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6956 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006957 assert(Res->getType() == DestTy);
6958 switch (CI.getOpcode()) {
6959 default: assert(0 && "Unknown cast type!");
6960 case Instruction::Trunc:
6961 case Instruction::BitCast:
6962 // Just replace this cast with the result.
6963 return ReplaceInstUsesWith(CI, Res);
6964 case Instruction::ZExt: {
6965 // We need to emit an AND to clear the high bits.
6966 assert(SrcBitSize < DestBitSize && "Not a zext?");
6967 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006968 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006969 if (DestBitSize < 64)
6970 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006971 return BinaryOperator::createAnd(Res, C);
6972 }
6973 case Instruction::SExt:
6974 // We need to emit a cast to truncate, then a cast to sext.
6975 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006976 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6977 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006978 }
6979 }
6980 }
6981
6982 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6983 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6984
6985 switch (SrcI->getOpcode()) {
6986 case Instruction::Add:
6987 case Instruction::Mul:
6988 case Instruction::And:
6989 case Instruction::Or:
6990 case Instruction::Xor:
6991 // If we are discarding information, or just changing the sign,
6992 // rewrite.
6993 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6994 // Don't insert two casts if they cannot be eliminated. We allow
6995 // two casts to be inserted if the sizes are the same. This could
6996 // only be converting signedness, which is a noop.
6997 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006998 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6999 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007000 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007001 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7002 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7003 return BinaryOperator::create(
7004 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007005 }
7006 }
7007
7008 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7009 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7010 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00007011 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007012 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007013 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007014 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7015 }
7016 break;
7017 case Instruction::SDiv:
7018 case Instruction::UDiv:
7019 case Instruction::SRem:
7020 case Instruction::URem:
7021 // If we are just changing the sign, rewrite.
7022 if (DestBitSize == SrcBitSize) {
7023 // Don't insert two casts if they cannot be eliminated. We allow
7024 // two casts to be inserted if the sizes are the same. This could
7025 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00007026 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7027 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007028 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7029 Op0, DestTy, SrcI);
7030 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7031 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007032 return BinaryOperator::create(
7033 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7034 }
7035 }
7036 break;
7037
7038 case Instruction::Shl:
7039 // Allow changing the sign of the source operand. Do not allow
7040 // changing the size of the shift, UNLESS the shift amount is a
7041 // constant. We must not change variable sized shifts to a smaller
7042 // size, because it is undefined to shift more bits out than exist
7043 // in the value.
7044 if (DestBitSize == SrcBitSize ||
7045 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007046 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7047 Instruction::BitCast : Instruction::Trunc);
7048 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00007049 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007050 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007051 }
7052 break;
7053 case Instruction::AShr:
7054 // If this is a signed shr, and if all bits shifted in are about to be
7055 // truncated off, turn it into an unsigned shr to allow greater
7056 // simplifications.
7057 if (DestBitSize < SrcBitSize &&
7058 isa<ConstantInt>(Op1)) {
7059 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7060 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7061 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00007062 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007063 }
7064 }
7065 break;
7066
Reid Spencer266e42b2006-12-23 06:05:41 +00007067 case Instruction::ICmp:
7068 // If we are just checking for a icmp eq of a single bit and casting it
7069 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007070 // cast to integer to avoid the comparison.
7071 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
7072 uint64_t Op1CV = Op1C->getZExtValue();
7073 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
7074 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7075 // cast (X == 1) to int --> X iff X has only the low bit set.
7076 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
7077 // cast (X != 0) to int --> X iff X has only the low bit set.
7078 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
7079 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
7080 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7081 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
7082 // If Op1C some other power of two, convert:
7083 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00007084 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007085 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00007086
7087 // This only works for EQ and NE
7088 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7089 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7090 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007091
7092 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00007093 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007094 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
7095 // (X&4) == 2 --> false
7096 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00007097 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007098 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007099 return ReplaceInstUsesWith(CI, Res);
7100 }
7101
7102 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
7103 Value *In = Op0;
7104 if (ShiftAmt) {
7105 // Perform a logical shr by shiftamt.
7106 // Insert the shift to put the result in the low bit.
7107 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007108 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00007109 ConstantInt::get(In->getType(), ShiftAmt),
7110 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007111 }
7112
Reid Spencer266e42b2006-12-23 06:05:41 +00007113 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007114 Constant *One = ConstantInt::get(In->getType(), 1);
7115 In = BinaryOperator::createXor(In, One, "tmp");
7116 InsertNewInstBefore(cast<Instruction>(In), CI);
7117 }
7118
7119 if (CI.getType() == In->getType())
7120 return ReplaceInstUsesWith(CI, In);
7121 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007122 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007123 }
7124 }
7125 }
7126 break;
7127 }
7128 return 0;
7129}
7130
7131Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007132 if (Instruction *Result = commonIntCastTransforms(CI))
7133 return Result;
7134
7135 Value *Src = CI.getOperand(0);
7136 const Type *Ty = CI.getType();
7137 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
7138
7139 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7140 switch (SrcI->getOpcode()) {
7141 default: break;
7142 case Instruction::LShr:
7143 // We can shrink lshr to something smaller if we know the bits shifted in
7144 // are already zeros.
7145 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7146 unsigned ShAmt = ShAmtV->getZExtValue();
7147
7148 // Get a mask for the bits shifting in.
7149 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00007150 Value* SrcIOp0 = SrcI->getOperand(0);
7151 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007152 if (ShAmt >= DestBitWidth) // All zeros.
7153 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7154
7155 // Okay, we can shrink this. Truncate the input, then return a new
7156 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00007157 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7158 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7159 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007160 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00007161 }
Chris Lattnerc209b582006-12-05 01:26:29 +00007162 } else { // This is a variable shr.
7163
7164 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7165 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7166 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00007167 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00007168 Value *One = ConstantInt::get(SrcI->getType(), 1);
7169
Reid Spencer2341c222007-02-02 02:16:23 +00007170 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007171 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00007172 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00007173 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7174 SrcI->getOperand(0),
7175 "tmp"), CI);
7176 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00007177 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00007178 }
Chris Lattnerd747f012006-11-29 07:04:07 +00007179 }
7180 break;
7181 }
7182 }
7183
7184 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007185}
7186
7187Instruction *InstCombiner::visitZExt(CastInst &CI) {
7188 // If one of the common conversion will work ..
7189 if (Instruction *Result = commonIntCastTransforms(CI))
7190 return Result;
7191
7192 Value *Src = CI.getOperand(0);
7193
7194 // If this is a cast of a cast
7195 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007196 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7197 // types and if the sizes are just right we can convert this into a logical
7198 // 'and' which will be much cheaper than the pair of casts.
7199 if (isa<TruncInst>(CSrc)) {
7200 // Get the sizes of the types involved
7201 Value *A = CSrc->getOperand(0);
7202 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7203 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7204 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7205 // If we're actually extending zero bits and the trunc is a no-op
7206 if (MidSize < DstSize && SrcSize == DstSize) {
7207 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00007208 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007209 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
7210 Instruction *And =
7211 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7212 // Unfortunately, if the type changed, we need to cast it back.
7213 if (And->getType() != CI.getType()) {
7214 And->setName(CSrc->getName()+".mask");
7215 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007216 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007217 }
7218 return And;
7219 }
7220 }
7221 }
7222
7223 return 0;
7224}
7225
7226Instruction *InstCombiner::visitSExt(CastInst &CI) {
7227 return commonIntCastTransforms(CI);
7228}
7229
7230Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7231 return commonCastTransforms(CI);
7232}
7233
7234Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7235 return commonCastTransforms(CI);
7236}
7237
7238Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007239 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007240}
7241
7242Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007243 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007244}
7245
7246Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7247 return commonCastTransforms(CI);
7248}
7249
7250Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7251 return commonCastTransforms(CI);
7252}
7253
7254Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007255 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007256}
7257
7258Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7259 return commonCastTransforms(CI);
7260}
7261
7262Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7263
7264 // If the operands are integer typed then apply the integer transforms,
7265 // otherwise just apply the common ones.
7266 Value *Src = CI.getOperand(0);
7267 const Type *SrcTy = Src->getType();
7268 const Type *DestTy = CI.getType();
7269
Chris Lattner03c49532007-01-15 02:27:26 +00007270 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007271 if (Instruction *Result = commonIntCastTransforms(CI))
7272 return Result;
7273 } else {
7274 if (Instruction *Result = commonCastTransforms(CI))
7275 return Result;
7276 }
7277
7278
7279 // Get rid of casts from one type to the same type. These are useless and can
7280 // be replaced by the operand.
7281 if (DestTy == Src->getType())
7282 return ReplaceInstUsesWith(CI, Src);
7283
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007284 // If the source and destination are pointers, and this cast is equivalent to
7285 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
7286 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007287 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7288 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7289 const Type *DstElTy = DstPTy->getElementType();
7290 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007291
Reid Spencerc635f472006-12-31 05:48:39 +00007292 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007293 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007294 while (SrcElTy != DstElTy &&
7295 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7296 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7297 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007298 ++NumZeros;
7299 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007300
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007301 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007302 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00007303 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7304 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007305 }
7306 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007307 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00007308
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007309 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7310 if (SVI->hasOneUse()) {
7311 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7312 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007313 if (isa<VectorType>(DestTy) &&
7314 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007315 SVI->getType()->getNumElements()) {
7316 CastInst *Tmp;
7317 // If either of the operands is a cast from CI.getType(), then
7318 // evaluating the shuffle in the casted destination's type will allow
7319 // us to eliminate at least one cast.
7320 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7321 Tmp->getOperand(0)->getType() == DestTy) ||
7322 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7323 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007324 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7325 SVI->getOperand(0), DestTy, &CI);
7326 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7327 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007328 // Return a new shuffle vector. Use the same element ID's, as we
7329 // know the vector types match #elts.
7330 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00007331 }
7332 }
7333 }
7334 }
Chris Lattner260ab202002-04-18 17:39:14 +00007335 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00007336}
7337
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007338/// GetSelectFoldableOperands - We want to turn code that looks like this:
7339/// %C = or %A, %B
7340/// %D = select %cond, %C, %A
7341/// into:
7342/// %C = select %cond, %B, 0
7343/// %D = or %A, %C
7344///
7345/// Assuming that the specified instruction is an operand to the select, return
7346/// a bitmask indicating which operands of this instruction are foldable if they
7347/// equal the other incoming value of the select.
7348///
7349static unsigned GetSelectFoldableOperands(Instruction *I) {
7350 switch (I->getOpcode()) {
7351 case Instruction::Add:
7352 case Instruction::Mul:
7353 case Instruction::And:
7354 case Instruction::Or:
7355 case Instruction::Xor:
7356 return 3; // Can fold through either operand.
7357 case Instruction::Sub: // Can only fold on the amount subtracted.
7358 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00007359 case Instruction::LShr:
7360 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00007361 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007362 default:
7363 return 0; // Cannot fold
7364 }
7365}
7366
7367/// GetSelectFoldableConstant - For the same transformation as the previous
7368/// function, return the identity constant that goes into the select.
7369static Constant *GetSelectFoldableConstant(Instruction *I) {
7370 switch (I->getOpcode()) {
7371 default: assert(0 && "This cannot happen!"); abort();
7372 case Instruction::Add:
7373 case Instruction::Sub:
7374 case Instruction::Or:
7375 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007376 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00007377 case Instruction::LShr:
7378 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00007379 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007380 case Instruction::And:
7381 return ConstantInt::getAllOnesValue(I->getType());
7382 case Instruction::Mul:
7383 return ConstantInt::get(I->getType(), 1);
7384 }
7385}
7386
Chris Lattner411336f2005-01-19 21:50:18 +00007387/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7388/// have the same opcode and only one use each. Try to simplify this.
7389Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7390 Instruction *FI) {
7391 if (TI->getNumOperands() == 1) {
7392 // If this is a non-volatile load or a cast from the same type,
7393 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007394 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00007395 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7396 return 0;
7397 } else {
7398 return 0; // unknown unary op.
7399 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007400
Chris Lattner411336f2005-01-19 21:50:18 +00007401 // Fold this by inserting a select from the input values.
7402 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7403 FI->getOperand(0), SI.getName()+".v");
7404 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007405 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7406 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00007407 }
7408
Reid Spencer2341c222007-02-02 02:16:23 +00007409 // Only handle binary operators here.
7410 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00007411 return 0;
7412
7413 // Figure out if the operations have any operands in common.
7414 Value *MatchOp, *OtherOpT, *OtherOpF;
7415 bool MatchIsOpZero;
7416 if (TI->getOperand(0) == FI->getOperand(0)) {
7417 MatchOp = TI->getOperand(0);
7418 OtherOpT = TI->getOperand(1);
7419 OtherOpF = FI->getOperand(1);
7420 MatchIsOpZero = true;
7421 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7422 MatchOp = TI->getOperand(1);
7423 OtherOpT = TI->getOperand(0);
7424 OtherOpF = FI->getOperand(0);
7425 MatchIsOpZero = false;
7426 } else if (!TI->isCommutative()) {
7427 return 0;
7428 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7429 MatchOp = TI->getOperand(0);
7430 OtherOpT = TI->getOperand(1);
7431 OtherOpF = FI->getOperand(0);
7432 MatchIsOpZero = true;
7433 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7434 MatchOp = TI->getOperand(1);
7435 OtherOpT = TI->getOperand(0);
7436 OtherOpF = FI->getOperand(1);
7437 MatchIsOpZero = true;
7438 } else {
7439 return 0;
7440 }
7441
7442 // If we reach here, they do have operations in common.
7443 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7444 OtherOpF, SI.getName()+".v");
7445 InsertNewInstBefore(NewSI, SI);
7446
7447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7448 if (MatchIsOpZero)
7449 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7450 else
7451 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00007452 }
Reid Spencer2f34b982007-02-02 14:41:37 +00007453 assert(0 && "Shouldn't get here");
7454 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00007455}
7456
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007457Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00007458 Value *CondVal = SI.getCondition();
7459 Value *TrueVal = SI.getTrueValue();
7460 Value *FalseVal = SI.getFalseValue();
7461
7462 // select true, X, Y -> X
7463 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00007464 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00007465 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00007466
7467 // select C, X, X -> X
7468 if (TrueVal == FalseVal)
7469 return ReplaceInstUsesWith(SI, TrueVal);
7470
Chris Lattner81a7a232004-10-16 18:11:37 +00007471 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7472 return ReplaceInstUsesWith(SI, FalseVal);
7473 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7474 return ReplaceInstUsesWith(SI, TrueVal);
7475 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7476 if (isa<Constant>(TrueVal))
7477 return ReplaceInstUsesWith(SI, TrueVal);
7478 else
7479 return ReplaceInstUsesWith(SI, FalseVal);
7480 }
7481
Reid Spencer542964f2007-01-11 18:21:29 +00007482 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007483 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007484 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007485 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007486 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007487 } else {
7488 // Change: A = select B, false, C --> A = and !B, C
7489 Value *NotCond =
7490 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7491 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007492 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007493 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007494 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007495 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007496 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007497 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007498 } else {
7499 // Change: A = select B, C, true --> A = or !B, C
7500 Value *NotCond =
7501 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7502 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007503 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007504 }
7505 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00007506 }
Chris Lattner1c631e82004-04-08 04:43:23 +00007507
Chris Lattner183b3362004-04-09 19:05:30 +00007508 // Selecting between two integer constants?
7509 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7510 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7511 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00007512 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007513 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00007514 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00007515 // select C, 0, 1 -> cast !C to int
7516 Value *NotCond =
7517 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00007518 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007519 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00007520 }
Chris Lattner35167c32004-06-09 07:59:58 +00007521
Reid Spencer266e42b2006-12-23 06:05:41 +00007522 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007523
Reid Spencer266e42b2006-12-23 06:05:41 +00007524 // (x <s 0) ? -1 : 0 -> ashr x, 31
7525 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00007526 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7527 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7528 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00007529 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00007530 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007531 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00007532 else {
7533 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00007534 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007535 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00007536 }
7537
7538 if (CanXForm) {
7539 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007540 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00007541 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00007542 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00007543 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7544 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7545 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00007546 InsertNewInstBefore(SRA, SI);
7547
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007548 // Finally, convert to the type of the select RHS. We figure out
7549 // if this requires a SExt, Trunc or BitCast based on the sizes.
7550 Instruction::CastOps opc = Instruction::BitCast;
7551 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7552 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
7553 if (SRASize < SISize)
7554 opc = Instruction::SExt;
7555 else if (SRASize > SISize)
7556 opc = Instruction::Trunc;
7557 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007558 }
7559 }
7560
7561
7562 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00007563 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007564 // non-constant value, eliminate this whole mess. This corresponds to
7565 // cases like this: ((X & 27) ? 27 : 0)
7566 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007567 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007568 cast<Constant>(IC->getOperand(1))->isNullValue())
7569 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7570 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007571 isa<ConstantInt>(ICA->getOperand(1)) &&
7572 (ICA->getOperand(1) == TrueValC ||
7573 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007574 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7575 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007576 // know whether we have a icmp_ne or icmp_eq and whether the
7577 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00007578 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007579 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007580 Value *V = ICA;
7581 if (ShouldNotVal)
7582 V = InsertNewInstBefore(BinaryOperator::create(
7583 Instruction::Xor, V, ICA->getOperand(1)), SI);
7584 return ReplaceInstUsesWith(SI, V);
7585 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007586 }
Chris Lattner533bc492004-03-30 19:37:13 +00007587 }
Chris Lattner623fba12004-04-10 22:21:27 +00007588
7589 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007590 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7591 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007592 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007593 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007594 return ReplaceInstUsesWith(SI, FalseVal);
7595 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007596 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007597 return ReplaceInstUsesWith(SI, TrueVal);
7598 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7599
Reid Spencer266e42b2006-12-23 06:05:41 +00007600 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007601 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007602 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007603 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007604 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007605 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7606 return ReplaceInstUsesWith(SI, TrueVal);
7607 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7608 }
7609 }
7610
7611 // See if we are selecting two values based on a comparison of the two values.
7612 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7613 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7614 // Transform (X == Y) ? X : Y -> Y
7615 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7616 return ReplaceInstUsesWith(SI, FalseVal);
7617 // Transform (X != Y) ? X : Y -> X
7618 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7619 return ReplaceInstUsesWith(SI, TrueVal);
7620 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7621
7622 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7623 // Transform (X == Y) ? Y : X -> X
7624 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7625 return ReplaceInstUsesWith(SI, FalseVal);
7626 // Transform (X != Y) ? Y : X -> Y
7627 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007628 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007629 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7630 }
7631 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007632
Chris Lattnera04c9042005-01-13 22:52:24 +00007633 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7634 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7635 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007636 Instruction *AddOp = 0, *SubOp = 0;
7637
Chris Lattner411336f2005-01-19 21:50:18 +00007638 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7639 if (TI->getOpcode() == FI->getOpcode())
7640 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7641 return IV;
7642
7643 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7644 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007645 if (TI->getOpcode() == Instruction::Sub &&
7646 FI->getOpcode() == Instruction::Add) {
7647 AddOp = FI; SubOp = TI;
7648 } else if (FI->getOpcode() == Instruction::Sub &&
7649 TI->getOpcode() == Instruction::Add) {
7650 AddOp = TI; SubOp = FI;
7651 }
7652
7653 if (AddOp) {
7654 Value *OtherAddOp = 0;
7655 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7656 OtherAddOp = AddOp->getOperand(1);
7657 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7658 OtherAddOp = AddOp->getOperand(0);
7659 }
7660
7661 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007662 // So at this point we know we have (Y -> OtherAddOp):
7663 // select C, (add X, Y), (sub X, Z)
7664 Value *NegVal; // Compute -Z
7665 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7666 NegVal = ConstantExpr::getNeg(C);
7667 } else {
7668 NegVal = InsertNewInstBefore(
7669 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007670 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007671
7672 Value *NewTrueOp = OtherAddOp;
7673 Value *NewFalseOp = NegVal;
7674 if (AddOp != TI)
7675 std::swap(NewTrueOp, NewFalseOp);
7676 Instruction *NewSel =
7677 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7678
7679 NewSel = InsertNewInstBefore(NewSel, SI);
7680 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007681 }
7682 }
7683 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007684
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007685 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007686 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007687 // See the comment above GetSelectFoldableOperands for a description of the
7688 // transformation we are doing here.
7689 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7690 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7691 !isa<Constant>(FalseVal))
7692 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7693 unsigned OpToFold = 0;
7694 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7695 OpToFold = 1;
7696 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7697 OpToFold = 2;
7698 }
7699
7700 if (OpToFold) {
7701 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007702 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007703 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007704 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007705 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007706 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7707 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007708 else {
7709 assert(0 && "Unknown instruction!!");
7710 }
7711 }
7712 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007713
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007714 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7715 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7716 !isa<Constant>(TrueVal))
7717 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7718 unsigned OpToFold = 0;
7719 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7720 OpToFold = 1;
7721 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7722 OpToFold = 2;
7723 }
7724
7725 if (OpToFold) {
7726 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007727 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007728 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007729 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007730 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007731 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7732 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007733 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007734 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007735 }
7736 }
7737 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007738
7739 if (BinaryOperator::isNot(CondVal)) {
7740 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7741 SI.setOperand(1, FalseVal);
7742 SI.setOperand(2, TrueVal);
7743 return &SI;
7744 }
7745
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007746 return 0;
7747}
7748
Chris Lattner82f2ef22006-03-06 20:18:44 +00007749/// GetKnownAlignment - If the specified pointer has an alignment that we can
7750/// determine, return it, otherwise return 0.
7751static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7752 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7753 unsigned Align = GV->getAlignment();
7754 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007755 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007756 return Align;
7757 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7758 unsigned Align = AI->getAlignment();
7759 if (Align == 0 && TD) {
7760 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007761 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007762 else if (isa<MallocInst>(AI)) {
7763 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007764 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007765 Align =
7766 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007767 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007768 Align =
7769 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007770 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007771 }
7772 }
7773 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007774 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007775 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007776 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007777 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007778 if (isa<PointerType>(CI->getOperand(0)->getType()))
7779 return GetKnownAlignment(CI->getOperand(0), TD);
7780 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007781 } else if (isa<GetElementPtrInst>(V) ||
7782 (isa<ConstantExpr>(V) &&
7783 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7784 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007785 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7786 if (BaseAlignment == 0) return 0;
7787
7788 // If all indexes are zero, it is just the alignment of the base pointer.
7789 bool AllZeroOperands = true;
7790 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7791 if (!isa<Constant>(GEPI->getOperand(i)) ||
7792 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7793 AllZeroOperands = false;
7794 break;
7795 }
7796 if (AllZeroOperands)
7797 return BaseAlignment;
7798
7799 // Otherwise, if the base alignment is >= the alignment we expect for the
7800 // base pointer type, then we know that the resultant pointer is aligned at
7801 // least as much as its type requires.
7802 if (!TD) return 0;
7803
7804 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007805 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007806 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007807 <= BaseAlignment) {
7808 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007809 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007810 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007811 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007812 return 0;
7813 }
7814 return 0;
7815}
7816
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007817
Chris Lattnerc66b2232006-01-13 20:11:04 +00007818/// visitCallInst - CallInst simplification. This mostly only handles folding
7819/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7820/// the heavy lifting.
7821///
Chris Lattner970c33a2003-06-19 17:00:31 +00007822Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007823 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7824 if (!II) return visitCallSite(&CI);
7825
Chris Lattner51ea1272004-02-28 05:22:00 +00007826 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7827 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007828 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007829 bool Changed = false;
7830
7831 // memmove/cpy/set of zero bytes is a noop.
7832 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7833 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7834
Chris Lattner00648e12004-10-12 04:52:52 +00007835 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007836 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007837 // Replace the instruction with just byte operations. We would
7838 // transform other cases to loads/stores, but we don't know if
7839 // alignment is sufficient.
7840 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007841 }
7842
Chris Lattner00648e12004-10-12 04:52:52 +00007843 // If we have a memmove and the source operation is a constant global,
7844 // then the source and dest pointers can't alias, so we can change this
7845 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007846 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007847 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7848 if (GVSrc->isConstant()) {
7849 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007850 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007851 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007852 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007853 Name = "llvm.memcpy.i32";
7854 else
7855 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007856 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007857 CI.getCalledFunction()->getFunctionType());
7858 CI.setOperand(0, MemCpy);
7859 Changed = true;
7860 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007861 }
Chris Lattner00648e12004-10-12 04:52:52 +00007862
Chris Lattner82f2ef22006-03-06 20:18:44 +00007863 // If we can determine a pointer alignment that is bigger than currently
7864 // set, update the alignment.
7865 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7866 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7867 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7868 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007869 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007870 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007871 Changed = true;
7872 }
7873 } else if (isa<MemSetInst>(MI)) {
7874 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007875 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007876 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007877 Changed = true;
7878 }
7879 }
7880
Chris Lattnerc66b2232006-01-13 20:11:04 +00007881 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007882 } else {
7883 switch (II->getIntrinsicID()) {
7884 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007885 case Intrinsic::ppc_altivec_lvx:
7886 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007887 case Intrinsic::x86_sse_loadu_ps:
7888 case Intrinsic::x86_sse2_loadu_pd:
7889 case Intrinsic::x86_sse2_loadu_dq:
7890 // Turn PPC lvx -> load if the pointer is known aligned.
7891 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007892 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007893 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007894 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007895 return new LoadInst(Ptr);
7896 }
7897 break;
7898 case Intrinsic::ppc_altivec_stvx:
7899 case Intrinsic::ppc_altivec_stvxl:
7900 // Turn stvx -> store if the pointer is known aligned.
7901 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007902 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007903 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7904 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007905 return new StoreInst(II->getOperand(1), Ptr);
7906 }
7907 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007908 case Intrinsic::x86_sse_storeu_ps:
7909 case Intrinsic::x86_sse2_storeu_pd:
7910 case Intrinsic::x86_sse2_storeu_dq:
7911 case Intrinsic::x86_sse2_storel_dq:
7912 // Turn X86 storeu -> store if the pointer is known aligned.
7913 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7914 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007915 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7916 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007917 return new StoreInst(II->getOperand(2), Ptr);
7918 }
7919 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007920
7921 case Intrinsic::x86_sse_cvttss2si: {
7922 // These intrinsics only demands the 0th element of its input vector. If
7923 // we can simplify the input based on that, do so now.
7924 uint64_t UndefElts;
7925 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7926 UndefElts)) {
7927 II->setOperand(1, V);
7928 return II;
7929 }
7930 break;
7931 }
7932
Chris Lattnere79d2492006-04-06 19:19:17 +00007933 case Intrinsic::ppc_altivec_vperm:
7934 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007935 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007936 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7937
7938 // Check that all of the elements are integer constants or undefs.
7939 bool AllEltsOk = true;
7940 for (unsigned i = 0; i != 16; ++i) {
7941 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7942 !isa<UndefValue>(Mask->getOperand(i))) {
7943 AllEltsOk = false;
7944 break;
7945 }
7946 }
7947
7948 if (AllEltsOk) {
7949 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007950 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7951 II->getOperand(1), Mask->getType(), CI);
7952 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7953 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007954 Value *Result = UndefValue::get(Op0->getType());
7955
7956 // Only extract each element once.
7957 Value *ExtractedElts[32];
7958 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7959
7960 for (unsigned i = 0; i != 16; ++i) {
7961 if (isa<UndefValue>(Mask->getOperand(i)))
7962 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007963 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007964 Idx &= 31; // Match the hardware behavior.
7965
7966 if (ExtractedElts[Idx] == 0) {
7967 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007968 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007969 InsertNewInstBefore(Elt, CI);
7970 ExtractedElts[Idx] = Elt;
7971 }
7972
7973 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007974 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007975 InsertNewInstBefore(cast<Instruction>(Result), CI);
7976 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007977 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007978 }
7979 }
7980 break;
7981
Chris Lattner503221f2006-01-13 21:28:09 +00007982 case Intrinsic::stackrestore: {
7983 // If the save is right next to the restore, remove the restore. This can
7984 // happen when variable allocas are DCE'd.
7985 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7986 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7987 BasicBlock::iterator BI = SS;
7988 if (&*++BI == II)
7989 return EraseInstFromFunction(CI);
7990 }
7991 }
7992
7993 // If the stack restore is in a return/unwind block and if there are no
7994 // allocas or calls between the restore and the return, nuke the restore.
7995 TerminatorInst *TI = II->getParent()->getTerminator();
7996 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7997 BasicBlock::iterator BI = II;
7998 bool CannotRemove = false;
7999 for (++BI; &*BI != TI; ++BI) {
8000 if (isa<AllocaInst>(BI) ||
8001 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8002 CannotRemove = true;
8003 break;
8004 }
8005 }
8006 if (!CannotRemove)
8007 return EraseInstFromFunction(CI);
8008 }
8009 break;
8010 }
8011 }
Chris Lattner00648e12004-10-12 04:52:52 +00008012 }
8013
Chris Lattnerc66b2232006-01-13 20:11:04 +00008014 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008015}
8016
8017// InvokeInst simplification
8018//
8019Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00008020 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008021}
8022
Chris Lattneraec3d942003-10-07 22:32:43 +00008023// visitCallSite - Improvements for call and invoke instructions.
8024//
8025Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008026 bool Changed = false;
8027
8028 // If the callee is a constexpr cast of a function, attempt to move the cast
8029 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00008030 if (transformConstExprCastCall(CS)) return 0;
8031
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008032 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00008033
Chris Lattner61d9d812005-05-13 07:09:09 +00008034 if (Function *CalleeF = dyn_cast<Function>(Callee))
8035 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8036 Instruction *OldCall = CS.getInstruction();
8037 // If the call and callee calling conventions don't match, this call must
8038 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008039 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008040 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00008041 if (!OldCall->use_empty())
8042 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8043 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8044 return EraseInstFromFunction(*OldCall);
8045 return 0;
8046 }
8047
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008048 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8049 // This instruction is not reachable, just remove it. We insert a store to
8050 // undef so that we know that this code is not reachable, despite the fact
8051 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008052 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008053 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008054 CS.getInstruction());
8055
8056 if (!CS.getInstruction()->use_empty())
8057 CS.getInstruction()->
8058 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8059
8060 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8061 // Don't break the CFG, insert a dummy cond branch.
8062 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00008063 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00008064 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008065 return EraseInstFromFunction(*CS.getInstruction());
8066 }
Chris Lattner81a7a232004-10-16 18:11:37 +00008067
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008068 const PointerType *PTy = cast<PointerType>(Callee->getType());
8069 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8070 if (FTy->isVarArg()) {
8071 // See if we can optimize any arguments passed through the varargs area of
8072 // the call.
8073 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8074 E = CS.arg_end(); I != E; ++I)
8075 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8076 // If this cast does not effect the value passed through the varargs
8077 // area, we can eliminate the use of the cast.
8078 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008079 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008080 *I = Op;
8081 Changed = true;
8082 }
8083 }
8084 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008085
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008086 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00008087}
8088
Chris Lattner970c33a2003-06-19 17:00:31 +00008089// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8090// attempt to move the cast to the arguments of the call/invoke.
8091//
8092bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8093 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8094 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008095 if (CE->getOpcode() != Instruction::BitCast ||
8096 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00008097 return false;
Reid Spencer87436872004-07-18 00:38:32 +00008098 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00008099 Instruction *Caller = CS.getInstruction();
8100
8101 // Okay, this is a cast from a function to a different type. Unless doing so
8102 // would cause a type conversion of one of our arguments, change this call to
8103 // be a direct call with arguments casted to the appropriate types.
8104 //
8105 const FunctionType *FT = Callee->getFunctionType();
8106 const Type *OldRetTy = Caller->getType();
8107
Chris Lattner1f7942f2004-01-14 06:06:08 +00008108 // Check to see if we are changing the return type...
8109 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00008110 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00008111 OldRetTy != FT->getReturnType() &&
8112 // Conversion is ok if changing from pointer to int of same size.
8113 !(isa<PointerType>(FT->getReturnType()) &&
8114 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00008115 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00008116
8117 // If the callsite is an invoke instruction, and the return value is used by
8118 // a PHI node in a successor, we cannot change the return type of the call
8119 // because there is no place to put the cast instruction (without breaking
8120 // the critical edge). Bail out in this case.
8121 if (!Caller->use_empty())
8122 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8123 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8124 UI != E; ++UI)
8125 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8126 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008127 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00008128 return false;
8129 }
Chris Lattner970c33a2003-06-19 17:00:31 +00008130
8131 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8132 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008133
Chris Lattner970c33a2003-06-19 17:00:31 +00008134 CallSite::arg_iterator AI = CS.arg_begin();
8135 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8136 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008137 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008138 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008139 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00008140 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00008141 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00008142 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00008143 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8144 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8145 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00008146 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00008147 }
8148
8149 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00008150 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00008151 return false; // Do not delete arguments unless we have a function body...
8152
8153 // Okay, we decided that this is a safe thing to do: go ahead and start
8154 // inserting cast instructions as necessary...
8155 std::vector<Value*> Args;
8156 Args.reserve(NumActualArgs);
8157
8158 AI = CS.arg_begin();
8159 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8160 const Type *ParamTy = FT->getParamType(i);
8161 if ((*AI)->getType() == ParamTy) {
8162 Args.push_back(*AI);
8163 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00008164 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00008165 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008166 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008167 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00008168 }
8169 }
8170
8171 // If the function takes more arguments than the call was taking, add them
8172 // now...
8173 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8174 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8175
8176 // If we are removing arguments to the function, emit an obnoxious warning...
8177 if (FT->getNumParams() < NumActualArgs)
8178 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00008179 cerr << "WARNING: While resolving call to function '"
8180 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00008181 } else {
8182 // Add all of the arguments in their promoted form to the arg list...
8183 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8184 const Type *PTy = getPromotedType((*AI)->getType());
8185 if (PTy != (*AI)->getType()) {
8186 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00008187 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8188 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008189 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00008190 InsertNewInstBefore(Cast, *Caller);
8191 Args.push_back(Cast);
8192 } else {
8193 Args.push_back(*AI);
8194 }
8195 }
8196 }
8197
8198 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00008199 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00008200
8201 Instruction *NC;
8202 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008203 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00008204 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00008205 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00008206 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00008207 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00008208 if (cast<CallInst>(Caller)->isTailCall())
8209 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00008210 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00008211 }
8212
Chris Lattner6e0123b2007-02-11 01:23:03 +00008213 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00008214 Value *NV = NC;
8215 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8216 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00008217 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00008218 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8219 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008220 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00008221
8222 // If this is an invoke instruction, we should insert it after the first
8223 // non-phi, instruction in the normal successor block.
8224 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8225 BasicBlock::iterator I = II->getNormalDest()->begin();
8226 while (isa<PHINode>(I)) ++I;
8227 InsertNewInstBefore(NC, *I);
8228 } else {
8229 // Otherwise, it's a call, just insert cast right after the call instr
8230 InsertNewInstBefore(NC, *Caller);
8231 }
Chris Lattner51ea1272004-02-28 05:22:00 +00008232 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00008233 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00008234 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00008235 }
8236 }
8237
8238 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8239 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00008240 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008241 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00008242 return true;
8243}
8244
Chris Lattnercadac0c2006-11-01 04:51:18 +00008245/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8246/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8247/// and a single binop.
8248Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8249 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00008250 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8251 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008252 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00008253 Value *LHSVal = FirstInst->getOperand(0);
8254 Value *RHSVal = FirstInst->getOperand(1);
8255
8256 const Type *LHSType = LHSVal->getType();
8257 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00008258
8259 // Scan to see if all operands are the same opcode, all have one use, and all
8260 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00008261 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00008262 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00008263 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00008264 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00008265 // types or GEP's with different index types.
8266 I->getOperand(0)->getType() != LHSType ||
8267 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00008268 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00008269
8270 // If they are CmpInst instructions, check their predicates
8271 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8272 if (cast<CmpInst>(I)->getPredicate() !=
8273 cast<CmpInst>(FirstInst)->getPredicate())
8274 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00008275
8276 // Keep track of which operand needs a phi node.
8277 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8278 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00008279 }
8280
Chris Lattner4f218d52006-11-08 19:42:28 +00008281 // Otherwise, this is safe to transform, determine if it is profitable.
8282
8283 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8284 // Indexes are often folded into load/store instructions, so we don't want to
8285 // hide them behind a phi.
8286 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8287 return 0;
8288
Chris Lattnercadac0c2006-11-01 04:51:18 +00008289 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00008290 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00008291 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00008292 if (LHSVal == 0) {
8293 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8294 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8295 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00008296 InsertNewInstBefore(NewLHS, PN);
8297 LHSVal = NewLHS;
8298 }
Chris Lattnercd62f112006-11-08 19:29:23 +00008299
8300 if (RHSVal == 0) {
8301 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8302 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8303 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00008304 InsertNewInstBefore(NewRHS, PN);
8305 RHSVal = NewRHS;
8306 }
8307
Chris Lattnercd62f112006-11-08 19:29:23 +00008308 // Add all operands to the new PHIs.
8309 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8310 if (NewLHS) {
8311 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8312 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8313 }
8314 if (NewRHS) {
8315 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8316 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8317 }
8318 }
8319
Chris Lattnercadac0c2006-11-01 04:51:18 +00008320 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00008321 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00008322 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8323 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8324 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00008325 else {
8326 assert(isa<GetElementPtrInst>(FirstInst));
8327 return new GetElementPtrInst(LHSVal, RHSVal);
8328 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00008329}
8330
Chris Lattner14f82c72006-11-01 07:13:54 +00008331/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8332/// of the block that defines it. This means that it must be obvious the value
8333/// of the load is not changed from the point of the load to the end of the
8334/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00008335///
8336/// Finally, it is safe, but not profitable, to sink a load targetting a
8337/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8338/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00008339static bool isSafeToSinkLoad(LoadInst *L) {
8340 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8341
8342 for (++BBI; BBI != E; ++BBI)
8343 if (BBI->mayWriteToMemory())
8344 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00008345
8346 // Check for non-address taken alloca. If not address-taken already, it isn't
8347 // profitable to do this xform.
8348 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8349 bool isAddressTaken = false;
8350 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8351 UI != E; ++UI) {
8352 if (isa<LoadInst>(UI)) continue;
8353 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8354 // If storing TO the alloca, then the address isn't taken.
8355 if (SI->getOperand(1) == AI) continue;
8356 }
8357 isAddressTaken = true;
8358 break;
8359 }
8360
8361 if (!isAddressTaken)
8362 return false;
8363 }
8364
Chris Lattner14f82c72006-11-01 07:13:54 +00008365 return true;
8366}
8367
Chris Lattner970c33a2003-06-19 17:00:31 +00008368
Chris Lattner7515cab2004-11-14 19:13:23 +00008369// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8370// operator and they all are only used by the PHI, PHI together their
8371// inputs, and do the operation once, to the result of the PHI.
8372Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8373 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8374
8375 // Scan the instruction, looking for input operations that can be folded away.
8376 // If all input operands to the phi are the same instruction (e.g. a cast from
8377 // the same type or "+42") we can pull the operation through the PHI, reducing
8378 // code size and simplifying code.
8379 Constant *ConstantOp = 0;
8380 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00008381 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00008382 if (isa<CastInst>(FirstInst)) {
8383 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00008384 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008385 // Can fold binop, compare or shift here if the RHS is a constant,
8386 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00008387 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008388 if (ConstantOp == 0)
8389 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00008390 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8391 isVolatile = LI->isVolatile();
8392 // We can't sink the load if the loaded value could be modified between the
8393 // load and the PHI.
8394 if (LI->getParent() != PN.getIncomingBlock(0) ||
8395 !isSafeToSinkLoad(LI))
8396 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00008397 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00008398 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00008399 return FoldPHIArgBinOpIntoPHI(PN);
8400 // Can't handle general GEPs yet.
8401 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008402 } else {
8403 return 0; // Cannot fold this operation.
8404 }
8405
8406 // Check to see if all arguments are the same operation.
8407 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8408 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8409 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00008410 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00008411 return 0;
8412 if (CastSrcTy) {
8413 if (I->getOperand(0)->getType() != CastSrcTy)
8414 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00008415 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008416 // We can't sink the load if the loaded value could be modified between
8417 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00008418 if (LI->isVolatile() != isVolatile ||
8419 LI->getParent() != PN.getIncomingBlock(i) ||
8420 !isSafeToSinkLoad(LI))
8421 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008422 } else if (I->getOperand(1) != ConstantOp) {
8423 return 0;
8424 }
8425 }
8426
8427 // Okay, they are all the same operation. Create a new PHI node of the
8428 // correct type, and PHI together all of the LHS's of the instructions.
8429 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8430 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00008431 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00008432
8433 Value *InVal = FirstInst->getOperand(0);
8434 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00008435
8436 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00008437 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8438 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8439 if (NewInVal != InVal)
8440 InVal = 0;
8441 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8442 }
8443
8444 Value *PhiVal;
8445 if (InVal) {
8446 // The new PHI unions all of the same values together. This is really
8447 // common, so we handle it intelligently here for compile-time speed.
8448 PhiVal = InVal;
8449 delete NewPN;
8450 } else {
8451 InsertNewInstBefore(NewPN, PN);
8452 PhiVal = NewPN;
8453 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008454
Chris Lattner7515cab2004-11-14 19:13:23 +00008455 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008456 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8457 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00008458 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00008459 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00008460 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00008461 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00008462 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8463 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8464 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00008465 else
Reid Spencer2341c222007-02-02 02:16:23 +00008466 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00008467 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008468}
Chris Lattner48a44f72002-05-02 17:06:02 +00008469
Chris Lattner71536432005-01-17 05:10:15 +00008470/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8471/// that is dead.
8472static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8473 if (PN->use_empty()) return true;
8474 if (!PN->hasOneUse()) return false;
8475
8476 // Remember this node, and if we find the cycle, return.
8477 if (!PotentiallyDeadPHIs.insert(PN).second)
8478 return true;
8479
8480 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8481 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008482
Chris Lattner71536432005-01-17 05:10:15 +00008483 return false;
8484}
8485
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008486// PHINode simplification
8487//
Chris Lattner113f4f42002-06-25 16:13:24 +00008488Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00008489 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00008490 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00008491
Owen Andersonae8aa642006-07-10 22:03:18 +00008492 if (Value *V = PN.hasConstantValue())
8493 return ReplaceInstUsesWith(PN, V);
8494
Owen Andersonae8aa642006-07-10 22:03:18 +00008495 // If all PHI operands are the same operation, pull them through the PHI,
8496 // reducing code size.
8497 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8498 PN.getIncomingValue(0)->hasOneUse())
8499 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8500 return Result;
8501
8502 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8503 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8504 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008505 if (PN.hasOneUse()) {
8506 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8507 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00008508 std::set<PHINode*> PotentiallyDeadPHIs;
8509 PotentiallyDeadPHIs.insert(&PN);
8510 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8511 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8512 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008513
8514 // If this phi has a single use, and if that use just computes a value for
8515 // the next iteration of a loop, delete the phi. This occurs with unused
8516 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8517 // common case here is good because the only other things that catch this
8518 // are induction variable analysis (sometimes) and ADCE, which is only run
8519 // late.
8520 if (PHIUser->hasOneUse() &&
8521 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8522 PHIUser->use_back() == &PN) {
8523 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8524 }
8525 }
Owen Andersonae8aa642006-07-10 22:03:18 +00008526
Chris Lattner91daeb52003-12-19 05:58:40 +00008527 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008528}
8529
Reid Spencer13bc5d72006-12-12 09:18:51 +00008530static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8531 Instruction *InsertPoint,
8532 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00008533 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8534 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008535 // We must cast correctly to the pointer type. Ensure that we
8536 // sign extend the integer value if it is smaller as this is
8537 // used for address computation.
8538 Instruction::CastOps opcode =
8539 (VTySize < PtrSize ? Instruction::SExt :
8540 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8541 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00008542}
8543
Chris Lattner48a44f72002-05-02 17:06:02 +00008544
Chris Lattner113f4f42002-06-25 16:13:24 +00008545Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008546 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00008547 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00008548 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008549 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00008550 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008551
Chris Lattner81a7a232004-10-16 18:11:37 +00008552 if (isa<UndefValue>(GEP.getOperand(0)))
8553 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8554
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008555 bool HasZeroPointerIndex = false;
8556 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8557 HasZeroPointerIndex = C->isNullValue();
8558
8559 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008560 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008561
Chris Lattner69193f92004-04-05 01:30:19 +00008562 // Eliminate unneeded casts for indices.
8563 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00008564 gep_type_iterator GTI = gep_type_begin(GEP);
8565 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8566 if (isa<SequentialType>(*GTI)) {
8567 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008568 if (CI->getOpcode() == Instruction::ZExt ||
8569 CI->getOpcode() == Instruction::SExt) {
8570 const Type *SrcTy = CI->getOperand(0)->getType();
8571 // We can eliminate a cast from i32 to i64 iff the target
8572 // is a 32-bit pointer target.
8573 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8574 MadeChange = true;
8575 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008576 }
8577 }
8578 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008579 // If we are using a wider index than needed for this platform, shrink it
8580 // to what we need. If the incoming value needs a cast instruction,
8581 // insert it. This explicit cast can make subsequent optimizations more
8582 // obvious.
8583 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008584 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008585 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008586 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008587 MadeChange = true;
8588 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008589 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8590 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008591 GEP.setOperand(i, Op);
8592 MadeChange = true;
8593 }
Chris Lattner69193f92004-04-05 01:30:19 +00008594 }
8595 if (MadeChange) return &GEP;
8596
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008597 // Combine Indices - If the source pointer to this getelementptr instruction
8598 // is a getelementptr instruction, combine the indices of the two
8599 // getelementptr instructions into a single instruction.
8600 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008601 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008602 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008603 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008604
8605 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008606 // Note that if our source is a gep chain itself that we wait for that
8607 // chain to be resolved before we perform this transformation. This
8608 // avoids us creating a TON of code in some cases.
8609 //
8610 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8611 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8612 return 0; // Wait until our source is folded to completion.
8613
Chris Lattneraf6094f2007-02-15 22:48:32 +00008614 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008615
8616 // Find out whether the last index in the source GEP is a sequential idx.
8617 bool EndsWithSequential = false;
8618 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8619 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008620 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008621
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008622 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008623 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008624 // Replace: gep (gep %P, long B), long A, ...
8625 // With: T = long A+B; gep %P, T, ...
8626 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008627 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008628 if (SO1 == Constant::getNullValue(SO1->getType())) {
8629 Sum = GO1;
8630 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8631 Sum = SO1;
8632 } else {
8633 // If they aren't the same type, convert both to an integer of the
8634 // target's pointer size.
8635 if (SO1->getType() != GO1->getType()) {
8636 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008637 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008638 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008639 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008640 } else {
8641 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008642 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008643 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008644 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008645
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008646 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008647 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008648 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008649 } else {
8650 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008651 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8652 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008653 }
8654 }
8655 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008656 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8657 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8658 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008659 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8660 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008661 }
Chris Lattner69193f92004-04-05 01:30:19 +00008662 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008663
8664 // Recycle the GEP we already have if possible.
8665 if (SrcGEPOperands.size() == 2) {
8666 GEP.setOperand(0, SrcGEPOperands[0]);
8667 GEP.setOperand(1, Sum);
8668 return &GEP;
8669 } else {
8670 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8671 SrcGEPOperands.end()-1);
8672 Indices.push_back(Sum);
8673 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8674 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008675 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008676 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008677 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008678 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008679 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8680 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008681 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8682 }
8683
8684 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008685 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8686 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008687
Chris Lattner5f667a62004-05-07 22:09:22 +00008688 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008689 // GEP of global variable. If all of the indices for this GEP are
8690 // constants, we can promote this to a constexpr instead of an instruction.
8691
8692 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008693 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008694 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8695 for (; I != E && isa<Constant>(*I); ++I)
8696 Indices.push_back(cast<Constant>(*I));
8697
8698 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008699 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8700 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008701
8702 // Replace all uses of the GEP with the new constexpr...
8703 return ReplaceInstUsesWith(GEP, CE);
8704 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008705 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008706 if (!isa<PointerType>(X->getType())) {
8707 // Not interesting. Source pointer must be a cast from pointer.
8708 } else if (HasZeroPointerIndex) {
8709 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8710 // into : GEP [10 x ubyte]* X, long 0, ...
8711 //
8712 // This occurs when the program declares an array extern like "int X[];"
8713 //
8714 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8715 const PointerType *XTy = cast<PointerType>(X->getType());
8716 if (const ArrayType *XATy =
8717 dyn_cast<ArrayType>(XTy->getElementType()))
8718 if (const ArrayType *CATy =
8719 dyn_cast<ArrayType>(CPTy->getElementType()))
8720 if (CATy->getElementType() == XATy->getElementType()) {
8721 // At this point, we know that the cast source type is a pointer
8722 // to an array of the same type as the destination pointer
8723 // array. Because the array type is never stepped over (there
8724 // is a leading zero) we can fold the cast into this GEP.
8725 GEP.setOperand(0, X);
8726 return &GEP;
8727 }
8728 } else if (GEP.getNumOperands() == 2) {
8729 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008730 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8731 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008732 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8733 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8734 if (isa<ArrayType>(SrcElTy) &&
8735 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8736 TD->getTypeSize(ResElTy)) {
8737 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008738 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008739 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008740 // V and GEP are both pointer types --> BitCast
8741 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008742 }
Chris Lattner2a893292005-09-13 18:36:04 +00008743
8744 // Transform things like:
8745 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8746 // (where tmp = 8*tmp2) into:
8747 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8748
8749 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008750 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008751 uint64_t ArrayEltSize =
8752 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8753
8754 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8755 // allow either a mul, shift, or constant here.
8756 Value *NewIdx = 0;
8757 ConstantInt *Scale = 0;
8758 if (ArrayEltSize == 1) {
8759 NewIdx = GEP.getOperand(1);
8760 Scale = ConstantInt::get(NewIdx->getType(), 1);
8761 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008762 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008763 Scale = CI;
8764 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8765 if (Inst->getOpcode() == Instruction::Shl &&
8766 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008767 unsigned ShAmt =
8768 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008769 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008770 NewIdx = Inst->getOperand(0);
8771 } else if (Inst->getOpcode() == Instruction::Mul &&
8772 isa<ConstantInt>(Inst->getOperand(1))) {
8773 Scale = cast<ConstantInt>(Inst->getOperand(1));
8774 NewIdx = Inst->getOperand(0);
8775 }
8776 }
8777
8778 // If the index will be to exactly the right offset with the scale taken
8779 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008780 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008781 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008782 Scale = ConstantInt::get(Scale->getType(),
8783 Scale->getZExtValue() / ArrayEltSize);
8784 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008785 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8786 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008787 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8788 NewIdx = InsertNewInstBefore(Sc, GEP);
8789 }
8790
8791 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008792 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008793 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008794 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008795 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8796 // The NewGEP must be pointer typed, so must the old one -> BitCast
8797 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008798 }
8799 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008800 }
Chris Lattnerca081252001-12-14 16:52:21 +00008801 }
8802
Chris Lattnerca081252001-12-14 16:52:21 +00008803 return 0;
8804}
8805
Chris Lattner1085bdf2002-11-04 16:18:53 +00008806Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8807 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8808 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008809 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8810 const Type *NewTy =
8811 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008812 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008813
8814 // Create and insert the replacement instruction...
8815 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008816 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008817 else {
8818 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008819 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008820 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008821
8822 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008823
Chris Lattner1085bdf2002-11-04 16:18:53 +00008824 // Scan to the end of the allocation instructions, to skip over a block of
8825 // allocas if possible...
8826 //
8827 BasicBlock::iterator It = New;
8828 while (isa<AllocationInst>(*It)) ++It;
8829
8830 // Now that I is pointing to the first non-allocation-inst in the block,
8831 // insert our getelementptr instruction...
8832 //
Reid Spencerc635f472006-12-31 05:48:39 +00008833 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008834 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8835 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008836
8837 // Now make everything use the getelementptr instead of the original
8838 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008839 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008840 } else if (isa<UndefValue>(AI.getArraySize())) {
8841 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008842 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008843
8844 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8845 // Note that we only do this for alloca's, because malloc should allocate and
8846 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008847 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008848 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008849 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8850
Chris Lattner1085bdf2002-11-04 16:18:53 +00008851 return 0;
8852}
8853
Chris Lattner8427bff2003-12-07 01:24:23 +00008854Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8855 Value *Op = FI.getOperand(0);
8856
8857 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8858 if (CastInst *CI = dyn_cast<CastInst>(Op))
8859 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8860 FI.setOperand(0, CI->getOperand(0));
8861 return &FI;
8862 }
8863
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008864 // free undef -> unreachable.
8865 if (isa<UndefValue>(Op)) {
8866 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008867 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008868 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008869 return EraseInstFromFunction(FI);
8870 }
8871
Chris Lattnerf3a36602004-02-28 04:57:37 +00008872 // If we have 'free null' delete the instruction. This can happen in stl code
8873 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008874 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008875 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008876
Chris Lattner8427bff2003-12-07 01:24:23 +00008877 return 0;
8878}
8879
8880
Chris Lattner72684fe2005-01-31 05:51:45 +00008881/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008882static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8883 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008884 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008885
8886 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008887 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008888 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008889
Reid Spencer31a4ef42007-01-22 05:51:25 +00008890 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008891 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008892 // If the source is an array, the code below will not succeed. Check to
8893 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8894 // constants.
8895 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8896 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8897 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008898 Value *Idxs[2];
8899 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8900 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008901 SrcTy = cast<PointerType>(CastOp->getType());
8902 SrcPTy = SrcTy->getElementType();
8903 }
8904
Reid Spencer31a4ef42007-01-22 05:51:25 +00008905 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008906 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008907 // Do not allow turning this into a load of an integer, which is then
8908 // casted to a pointer, this pessimizes pointer analysis a lot.
8909 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008910 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8911 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008912
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008913 // Okay, we are casting from one integer or pointer type to another of
8914 // the same size. Instead of casting the pointer before the load, cast
8915 // the result of the loaded value.
8916 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8917 CI->getName(),
8918 LI.isVolatile()),LI);
8919 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008920 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008921 }
Chris Lattner35e24772004-07-13 01:49:43 +00008922 }
8923 }
8924 return 0;
8925}
8926
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008927/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008928/// from this value cannot trap. If it is not obviously safe to load from the
8929/// specified pointer, we do a quick local scan of the basic block containing
8930/// ScanFrom, to determine if the address is already accessed.
8931static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8932 // If it is an alloca or global variable, it is always safe to load from.
8933 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8934
8935 // Otherwise, be a little bit agressive by scanning the local block where we
8936 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008937 // from/to. If so, the previous load or store would have already trapped,
8938 // so there is no harm doing an extra load (also, CSE will later eliminate
8939 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008940 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8941
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008942 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008943 --BBI;
8944
8945 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8946 if (LI->getOperand(0) == V) return true;
8947 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8948 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008949
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008950 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008951 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008952}
8953
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008954Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8955 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008956
Chris Lattnera9d84e32005-05-01 04:24:53 +00008957 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008958 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008959 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8960 return Res;
8961
8962 // None of the following transforms are legal for volatile loads.
8963 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008964
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008965 if (&LI.getParent()->front() != &LI) {
8966 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008967 // If the instruction immediately before this is a store to the same
8968 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008969 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8970 if (SI->getOperand(1) == LI.getOperand(0))
8971 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008972 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8973 if (LIB->getOperand(0) == LI.getOperand(0))
8974 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008975 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008976
8977 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8978 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8979 isa<UndefValue>(GEPI->getOperand(0))) {
8980 // Insert a new store to null instruction before the load to indicate
8981 // that this code is not reachable. We do this instead of inserting
8982 // an unreachable instruction directly because we cannot modify the
8983 // CFG.
8984 new StoreInst(UndefValue::get(LI.getType()),
8985 Constant::getNullValue(Op->getType()), &LI);
8986 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8987 }
8988
Chris Lattner81a7a232004-10-16 18:11:37 +00008989 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008990 // load null/undef -> undef
8991 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008992 // Insert a new store to null instruction before the load to indicate that
8993 // this code is not reachable. We do this instead of inserting an
8994 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008995 new StoreInst(UndefValue::get(LI.getType()),
8996 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008997 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008998 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008999
Chris Lattner81a7a232004-10-16 18:11:37 +00009000 // Instcombine load (constant global) into the value loaded.
9001 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00009002 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00009003 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00009004
Chris Lattner81a7a232004-10-16 18:11:37 +00009005 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9006 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9007 if (CE->getOpcode() == Instruction::GetElementPtr) {
9008 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00009009 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00009010 if (Constant *V =
9011 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00009012 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00009013 if (CE->getOperand(0)->isNullValue()) {
9014 // Insert a new store to null instruction before the load to indicate
9015 // that this code is not reachable. We do this instead of inserting
9016 // an unreachable instruction directly because we cannot modify the
9017 // CFG.
9018 new StoreInst(UndefValue::get(LI.getType()),
9019 Constant::getNullValue(Op->getType()), &LI);
9020 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9021 }
9022
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009023 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00009024 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9025 return Res;
9026 }
9027 }
Chris Lattnere228ee52004-04-08 20:39:49 +00009028
Chris Lattnera9d84e32005-05-01 04:24:53 +00009029 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009030 // Change select and PHI nodes to select values instead of addresses: this
9031 // helps alias analysis out a lot, allows many others simplifications, and
9032 // exposes redundancy in the code.
9033 //
9034 // Note that we cannot do the transformation unless we know that the
9035 // introduced loads cannot trap! Something like this is valid as long as
9036 // the condition is always false: load (select bool %C, int* null, int* %G),
9037 // but it would not be valid if we transformed it to load from null
9038 // unconditionally.
9039 //
9040 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9041 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00009042 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9043 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009044 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00009045 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009046 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00009047 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009048 return new SelectInst(SI->getCondition(), V1, V2);
9049 }
9050
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00009051 // load (select (cond, null, P)) -> load P
9052 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9053 if (C->isNullValue()) {
9054 LI.setOperand(0, SI->getOperand(2));
9055 return &LI;
9056 }
9057
9058 // load (select (cond, P, null)) -> load P
9059 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9060 if (C->isNullValue()) {
9061 LI.setOperand(0, SI->getOperand(1));
9062 return &LI;
9063 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009064 }
9065 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00009066 return 0;
9067}
9068
Reid Spencere928a152007-01-19 21:20:31 +00009069/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00009070/// when possible.
9071static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9072 User *CI = cast<User>(SI.getOperand(1));
9073 Value *CastOp = CI->getOperand(0);
9074
9075 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9076 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9077 const Type *SrcPTy = SrcTy->getElementType();
9078
Reid Spencer31a4ef42007-01-22 05:51:25 +00009079 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00009080 // If the source is an array, the code below will not succeed. Check to
9081 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9082 // constants.
9083 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9084 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9085 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00009086 Value* Idxs[2];
9087 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9088 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00009089 SrcTy = cast<PointerType>(CastOp->getType());
9090 SrcPTy = SrcTy->getElementType();
9091 }
9092
Reid Spencer9a4bed02007-01-20 23:35:48 +00009093 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9094 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9095 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00009096
9097 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00009098 // the same size. Instead of casting the pointer before
9099 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00009100 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009101 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00009102 Instruction::CastOps opcode = Instruction::BitCast;
9103 const Type* CastSrcTy = SIOp0->getType();
9104 const Type* CastDstTy = SrcPTy;
9105 if (isa<PointerType>(CastDstTy)) {
9106 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009107 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00009108 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00009109 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009110 opcode = Instruction::PtrToInt;
9111 }
9112 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00009113 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00009114 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009115 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00009116 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9117 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00009118 return new StoreInst(NewCast, CastOp);
9119 }
9120 }
9121 }
9122 return 0;
9123}
9124
Chris Lattner31f486c2005-01-31 05:36:43 +00009125Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9126 Value *Val = SI.getOperand(0);
9127 Value *Ptr = SI.getOperand(1);
9128
9129 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00009130 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00009131 ++NumCombined;
9132 return 0;
9133 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00009134
9135 // If the RHS is an alloca with a single use, zapify the store, making the
9136 // alloca dead.
9137 if (Ptr->hasOneUse()) {
9138 if (isa<AllocaInst>(Ptr)) {
9139 EraseInstFromFunction(SI);
9140 ++NumCombined;
9141 return 0;
9142 }
9143
9144 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9145 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9146 GEP->getOperand(0)->hasOneUse()) {
9147 EraseInstFromFunction(SI);
9148 ++NumCombined;
9149 return 0;
9150 }
9151 }
Chris Lattner31f486c2005-01-31 05:36:43 +00009152
Chris Lattner5997cf92006-02-08 03:25:32 +00009153 // Do really simple DSE, to catch cases where there are several consequtive
9154 // stores to the same location, separated by a few arithmetic operations. This
9155 // situation often occurs with bitfield accesses.
9156 BasicBlock::iterator BBI = &SI;
9157 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9158 --ScanInsts) {
9159 --BBI;
9160
9161 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9162 // Prev store isn't volatile, and stores to the same location?
9163 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9164 ++NumDeadStore;
9165 ++BBI;
9166 EraseInstFromFunction(*PrevSI);
9167 continue;
9168 }
9169 break;
9170 }
9171
Chris Lattnerdab43b22006-05-26 19:19:20 +00009172 // If this is a load, we have to stop. However, if the loaded value is from
9173 // the pointer we're loading and is producing the pointer we're storing,
9174 // then *this* store is dead (X = load P; store X -> P).
9175 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9176 if (LI == Val && LI->getOperand(0) == Ptr) {
9177 EraseInstFromFunction(SI);
9178 ++NumCombined;
9179 return 0;
9180 }
9181 // Otherwise, this is a load from some other location. Stores before it
9182 // may not be dead.
9183 break;
9184 }
9185
Chris Lattner5997cf92006-02-08 03:25:32 +00009186 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00009187 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00009188 break;
9189 }
9190
9191
9192 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00009193
9194 // store X, null -> turns into 'unreachable' in SimplifyCFG
9195 if (isa<ConstantPointerNull>(Ptr)) {
9196 if (!isa<UndefValue>(Val)) {
9197 SI.setOperand(0, UndefValue::get(Val->getType()));
9198 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009199 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00009200 ++NumCombined;
9201 }
9202 return 0; // Do not modify these!
9203 }
9204
9205 // store undef, Ptr -> noop
9206 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00009207 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00009208 ++NumCombined;
9209 return 0;
9210 }
9211
Chris Lattner72684fe2005-01-31 05:51:45 +00009212 // If the pointer destination is a cast, see if we can fold the cast into the
9213 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00009214 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00009215 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9216 return Res;
9217 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009218 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00009219 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9220 return Res;
9221
Chris Lattner219175c2005-09-12 23:23:25 +00009222
9223 // If this store is the last instruction in the basic block, and if the block
9224 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00009225 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00009226 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9227 if (BI->isUnconditional()) {
9228 // Check to see if the successor block has exactly two incoming edges. If
9229 // so, see if the other predecessor contains a store to the same location.
9230 // if so, insert a PHI node (if needed) and move the stores down.
9231 BasicBlock *Dest = BI->getSuccessor(0);
9232
9233 pred_iterator PI = pred_begin(Dest);
9234 BasicBlock *Other = 0;
9235 if (*PI != BI->getParent())
9236 Other = *PI;
9237 ++PI;
9238 if (PI != pred_end(Dest)) {
9239 if (*PI != BI->getParent())
9240 if (Other)
9241 Other = 0;
9242 else
9243 Other = *PI;
9244 if (++PI != pred_end(Dest))
9245 Other = 0;
9246 }
9247 if (Other) { // If only one other pred...
9248 BBI = Other->getTerminator();
9249 // Make sure this other block ends in an unconditional branch and that
9250 // there is an instruction before the branch.
9251 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9252 BBI != Other->begin()) {
9253 --BBI;
9254 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9255
9256 // If this instruction is a store to the same location.
9257 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9258 // Okay, we know we can perform this transformation. Insert a PHI
9259 // node now if we need it.
9260 Value *MergedVal = OtherStore->getOperand(0);
9261 if (MergedVal != SI.getOperand(0)) {
9262 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9263 PN->reserveOperandSpace(2);
9264 PN->addIncoming(SI.getOperand(0), SI.getParent());
9265 PN->addIncoming(OtherStore->getOperand(0), Other);
9266 MergedVal = InsertNewInstBefore(PN, Dest->front());
9267 }
9268
9269 // Advance to a place where it is safe to insert the new store and
9270 // insert it.
9271 BBI = Dest->begin();
9272 while (isa<PHINode>(BBI)) ++BBI;
9273 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9274 OtherStore->isVolatile()), *BBI);
9275
9276 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00009277 EraseInstFromFunction(SI);
9278 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00009279 ++NumCombined;
9280 return 0;
9281 }
9282 }
9283 }
9284 }
9285
Chris Lattner31f486c2005-01-31 05:36:43 +00009286 return 0;
9287}
9288
9289
Chris Lattner9eef8a72003-06-04 04:46:00 +00009290Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9291 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00009292 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00009293 BasicBlock *TrueDest;
9294 BasicBlock *FalseDest;
9295 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9296 !isa<Constant>(X)) {
9297 // Swap Destinations and condition...
9298 BI.setCondition(X);
9299 BI.setSuccessor(0, FalseDest);
9300 BI.setSuccessor(1, TrueDest);
9301 return &BI;
9302 }
9303
Reid Spencer266e42b2006-12-23 06:05:41 +00009304 // Cannonicalize fcmp_one -> fcmp_oeq
9305 FCmpInst::Predicate FPred; Value *Y;
9306 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9307 TrueDest, FalseDest)))
9308 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9309 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9310 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009311 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009312 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9313 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00009314 // Swap Destinations and condition...
9315 BI.setCondition(NewSCC);
9316 BI.setSuccessor(0, FalseDest);
9317 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009318 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009319 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009320 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00009321 return &BI;
9322 }
9323
9324 // Cannonicalize icmp_ne -> icmp_eq
9325 ICmpInst::Predicate IPred;
9326 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9327 TrueDest, FalseDest)))
9328 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9329 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9330 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9331 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009332 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009333 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9334 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00009335 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00009336 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009337 BI.setSuccessor(0, FalseDest);
9338 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009339 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009340 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009341 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009342 return &BI;
9343 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009344
Chris Lattner9eef8a72003-06-04 04:46:00 +00009345 return 0;
9346}
Chris Lattner1085bdf2002-11-04 16:18:53 +00009347
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009348Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9349 Value *Cond = SI.getCondition();
9350 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9351 if (I->getOpcode() == Instruction::Add)
9352 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9353 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9354 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00009355 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009356 AddRHS));
9357 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009358 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009359 return &SI;
9360 }
9361 }
9362 return 0;
9363}
9364
Chris Lattner6bc98652006-03-05 00:22:33 +00009365/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9366/// is to leave as a vector operation.
9367static bool CheapToScalarize(Value *V, bool isConstant) {
9368 if (isa<ConstantAggregateZero>(V))
9369 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009370 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009371 if (isConstant) return true;
9372 // If all elts are the same, we can extract.
9373 Constant *Op0 = C->getOperand(0);
9374 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9375 if (C->getOperand(i) != Op0)
9376 return false;
9377 return true;
9378 }
9379 Instruction *I = dyn_cast<Instruction>(V);
9380 if (!I) return false;
9381
9382 // Insert element gets simplified to the inserted element or is deleted if
9383 // this is constant idx extract element and its a constant idx insertelt.
9384 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9385 isa<ConstantInt>(I->getOperand(2)))
9386 return true;
9387 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9388 return true;
9389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9390 if (BO->hasOneUse() &&
9391 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9392 CheapToScalarize(BO->getOperand(1), isConstant)))
9393 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00009394 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9395 if (CI->hasOneUse() &&
9396 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9397 CheapToScalarize(CI->getOperand(1), isConstant)))
9398 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00009399
9400 return false;
9401}
9402
Chris Lattner945e4372007-02-14 05:52:17 +00009403/// Read and decode a shufflevector mask.
9404///
9405/// It turns undef elements into values that are larger than the number of
9406/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00009407static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9408 unsigned NElts = SVI->getType()->getNumElements();
9409 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9410 return std::vector<unsigned>(NElts, 0);
9411 if (isa<UndefValue>(SVI->getOperand(2)))
9412 return std::vector<unsigned>(NElts, 2*NElts);
9413
9414 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009415 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00009416 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9417 if (isa<UndefValue>(CP->getOperand(i)))
9418 Result.push_back(NElts*2); // undef -> 8
9419 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00009420 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00009421 return Result;
9422}
9423
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009424/// FindScalarElement - Given a vector and an element number, see if the scalar
9425/// value is already around as a register, for example if it were inserted then
9426/// extracted from the vector.
9427static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009428 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9429 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00009430 unsigned Width = PTy->getNumElements();
9431 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009432 return UndefValue::get(PTy->getElementType());
9433
9434 if (isa<UndefValue>(V))
9435 return UndefValue::get(PTy->getElementType());
9436 else if (isa<ConstantAggregateZero>(V))
9437 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00009438 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009439 return CP->getOperand(EltNo);
9440 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9441 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009442 if (!isa<ConstantInt>(III->getOperand(2)))
9443 return 0;
9444 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009445
9446 // If this is an insert to the element we are looking for, return the
9447 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009448 if (EltNo == IIElt)
9449 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009450
9451 // Otherwise, the insertelement doesn't modify the value, recurse on its
9452 // vector input.
9453 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00009454 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00009455 unsigned InEl = getShuffleMask(SVI)[EltNo];
9456 if (InEl < Width)
9457 return FindScalarElement(SVI->getOperand(0), InEl);
9458 else if (InEl < Width*2)
9459 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9460 else
9461 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009462 }
9463
9464 // Otherwise, we don't know.
9465 return 0;
9466}
9467
Robert Bocchinoa8352962006-01-13 22:48:06 +00009468Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009469
Chris Lattner92346c32006-03-31 18:25:14 +00009470 // If packed val is undef, replace extract with scalar undef.
9471 if (isa<UndefValue>(EI.getOperand(0)))
9472 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9473
9474 // If packed val is constant 0, replace extract with scalar 0.
9475 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9476 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9477
Reid Spencerd84d35b2007-02-15 02:26:10 +00009478 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009479 // If packed val is constant with uniform operands, replace EI
9480 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00009481 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009482 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00009483 if (C->getOperand(i) != op0) {
9484 op0 = 0;
9485 break;
9486 }
9487 if (op0)
9488 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009489 }
Chris Lattner6bc98652006-03-05 00:22:33 +00009490
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009491 // If extracting a specified index from the vector, see if we can recursively
9492 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009493 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00009494 // This instruction only demands the single element from the input vector.
9495 // If the input vector has a single use, simplify it based on this use
9496 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009497 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00009498 if (EI.getOperand(0)->hasOneUse()) {
9499 uint64_t UndefElts;
9500 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00009501 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00009502 UndefElts)) {
9503 EI.setOperand(0, V);
9504 return &EI;
9505 }
9506 }
9507
Reid Spencere0fc4df2006-10-20 07:07:24 +00009508 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009509 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00009510 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009511
Chris Lattner83f65782006-05-25 22:53:38 +00009512 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009513 if (I->hasOneUse()) {
9514 // Push extractelement into predecessor operation if legal and
9515 // profitable to do so
9516 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009517 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9518 if (CheapToScalarize(BO, isConstantElt)) {
9519 ExtractElementInst *newEI0 =
9520 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9521 EI.getName()+".lhs");
9522 ExtractElementInst *newEI1 =
9523 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9524 EI.getName()+".rhs");
9525 InsertNewInstBefore(newEI0, EI);
9526 InsertNewInstBefore(newEI1, EI);
9527 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9528 }
Reid Spencerde46e482006-11-02 20:25:50 +00009529 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009530 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00009531 PointerType::get(EI.getType()), EI);
9532 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00009533 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00009534 InsertNewInstBefore(GEP, EI);
9535 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00009536 }
9537 }
9538 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9539 // Extracting the inserted element?
9540 if (IE->getOperand(2) == EI.getOperand(1))
9541 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9542 // If the inserted and extracted elements are constants, they must not
9543 // be the same value, extract from the pre-inserted value instead.
9544 if (isa<Constant>(IE->getOperand(2)) &&
9545 isa<Constant>(EI.getOperand(1))) {
9546 AddUsesToWorkList(EI);
9547 EI.setOperand(0, IE->getOperand(0));
9548 return &EI;
9549 }
9550 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9551 // If this is extracting an element from a shufflevector, figure out where
9552 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009553 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9554 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00009555 Value *Src;
9556 if (SrcIdx < SVI->getType()->getNumElements())
9557 Src = SVI->getOperand(0);
9558 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9559 SrcIdx -= SVI->getType()->getNumElements();
9560 Src = SVI->getOperand(1);
9561 } else {
9562 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009563 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009564 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009565 }
9566 }
Chris Lattner83f65782006-05-25 22:53:38 +00009567 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009568 return 0;
9569}
9570
Chris Lattner90951862006-04-16 00:51:47 +00009571/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9572/// elements from either LHS or RHS, return the shuffle mask and true.
9573/// Otherwise, return false.
9574static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9575 std::vector<Constant*> &Mask) {
9576 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9577 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009578 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009579
9580 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009581 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009582 return true;
9583 } else if (V == LHS) {
9584 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009585 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009586 return true;
9587 } else if (V == RHS) {
9588 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009589 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009590 return true;
9591 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9592 // If this is an insert of an extract from some other vector, include it.
9593 Value *VecOp = IEI->getOperand(0);
9594 Value *ScalarOp = IEI->getOperand(1);
9595 Value *IdxOp = IEI->getOperand(2);
9596
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009597 if (!isa<ConstantInt>(IdxOp))
9598 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009599 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009600
9601 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9602 // Okay, we can handle this if the vector we are insertinting into is
9603 // transitively ok.
9604 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9605 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009606 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009607 return true;
9608 }
9609 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9610 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009611 EI->getOperand(0)->getType() == V->getType()) {
9612 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009613 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009614
9615 // This must be extracting from either LHS or RHS.
9616 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9617 // Okay, we can handle this if the vector we are insertinting into is
9618 // transitively ok.
9619 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9620 // If so, update the mask to reflect the inserted value.
9621 if (EI->getOperand(0) == LHS) {
9622 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009623 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009624 } else {
9625 assert(EI->getOperand(0) == RHS);
9626 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009627 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009628
9629 }
9630 return true;
9631 }
9632 }
9633 }
9634 }
9635 }
9636 // TODO: Handle shufflevector here!
9637
9638 return false;
9639}
9640
9641/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9642/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9643/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009644static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009645 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009646 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009647 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009648 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009649 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009650
9651 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009652 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009653 return V;
9654 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009655 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009656 return V;
9657 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9658 // If this is an insert of an extract from some other vector, include it.
9659 Value *VecOp = IEI->getOperand(0);
9660 Value *ScalarOp = IEI->getOperand(1);
9661 Value *IdxOp = IEI->getOperand(2);
9662
9663 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9664 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9665 EI->getOperand(0)->getType() == V->getType()) {
9666 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009667 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9668 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009669
9670 // Either the extracted from or inserted into vector must be RHSVec,
9671 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009672 if (EI->getOperand(0) == RHS || RHS == 0) {
9673 RHS = EI->getOperand(0);
9674 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009675 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009676 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009677 return V;
9678 }
9679
Chris Lattner90951862006-04-16 00:51:47 +00009680 if (VecOp == RHS) {
9681 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009682 // Everything but the extracted element is replaced with the RHS.
9683 for (unsigned i = 0; i != NumElts; ++i) {
9684 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009685 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009686 }
9687 return V;
9688 }
Chris Lattner90951862006-04-16 00:51:47 +00009689
9690 // If this insertelement is a chain that comes from exactly these two
9691 // vectors, return the vector and the effective shuffle.
9692 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9693 return EI->getOperand(0);
9694
Chris Lattner39fac442006-04-15 01:39:45 +00009695 }
9696 }
9697 }
Chris Lattner90951862006-04-16 00:51:47 +00009698 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009699
9700 // Otherwise, can't do anything fancy. Return an identity vector.
9701 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009702 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009703 return V;
9704}
9705
9706Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9707 Value *VecOp = IE.getOperand(0);
9708 Value *ScalarOp = IE.getOperand(1);
9709 Value *IdxOp = IE.getOperand(2);
9710
9711 // If the inserted element was extracted from some other vector, and if the
9712 // indexes are constant, try to turn this into a shufflevector operation.
9713 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9714 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9715 EI->getOperand(0)->getType() == IE.getType()) {
9716 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009717 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9718 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009719
9720 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9721 return ReplaceInstUsesWith(IE, VecOp);
9722
9723 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9724 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9725
9726 // If we are extracting a value from a vector, then inserting it right
9727 // back into the same place, just use the input vector.
9728 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9729 return ReplaceInstUsesWith(IE, VecOp);
9730
9731 // We could theoretically do this for ANY input. However, doing so could
9732 // turn chains of insertelement instructions into a chain of shufflevector
9733 // instructions, and right now we do not merge shufflevectors. As such,
9734 // only do this in a situation where it is clear that there is benefit.
9735 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9736 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9737 // the values of VecOp, except then one read from EIOp0.
9738 // Build a new shuffle mask.
9739 std::vector<Constant*> Mask;
9740 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009741 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009742 else {
9743 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009744 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009745 NumVectorElts));
9746 }
Reid Spencerc635f472006-12-31 05:48:39 +00009747 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009748 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009749 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009750 }
9751
9752 // If this insertelement isn't used by some other insertelement, turn it
9753 // (and any insertelements it points to), into one big shuffle.
9754 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9755 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009756 Value *RHS = 0;
9757 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9758 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9759 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009760 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009761 }
9762 }
9763 }
9764
9765 return 0;
9766}
9767
9768
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009769Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9770 Value *LHS = SVI.getOperand(0);
9771 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009772 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009773
9774 bool MadeChange = false;
9775
Chris Lattner2deeaea2006-10-05 06:55:50 +00009776 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009777 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009778 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9779
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009780 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009781 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009782 if (isa<UndefValue>(SVI.getOperand(1))) {
9783 // Scan to see if there are any references to the RHS. If so, replace them
9784 // with undef element refs and set MadeChange to true.
9785 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9786 if (Mask[i] >= e && Mask[i] != 2*e) {
9787 Mask[i] = 2*e;
9788 MadeChange = true;
9789 }
9790 }
9791
9792 if (MadeChange) {
9793 // Remap any references to RHS to use LHS.
9794 std::vector<Constant*> Elts;
9795 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9796 if (Mask[i] == 2*e)
9797 Elts.push_back(UndefValue::get(Type::Int32Ty));
9798 else
9799 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9800 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009801 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009802 }
9803 }
Chris Lattner39fac442006-04-15 01:39:45 +00009804
Chris Lattner12249be2006-05-25 23:48:38 +00009805 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9806 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9807 if (LHS == RHS || isa<UndefValue>(LHS)) {
9808 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009809 // shuffle(undef,undef,mask) -> undef.
9810 return ReplaceInstUsesWith(SVI, LHS);
9811 }
9812
Chris Lattner12249be2006-05-25 23:48:38 +00009813 // Remap any references to RHS to use LHS.
9814 std::vector<Constant*> Elts;
9815 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009816 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009817 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009818 else {
9819 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9820 (Mask[i] < e && isa<UndefValue>(LHS)))
9821 Mask[i] = 2*e; // Turn into undef.
9822 else
9823 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009824 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009825 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009826 }
Chris Lattner12249be2006-05-25 23:48:38 +00009827 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009828 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009829 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009830 LHS = SVI.getOperand(0);
9831 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009832 MadeChange = true;
9833 }
9834
Chris Lattner0e477162006-05-26 00:29:06 +00009835 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009836 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009837
Chris Lattner12249be2006-05-25 23:48:38 +00009838 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9839 if (Mask[i] >= e*2) continue; // Ignore undef values.
9840 // Is this an identity shuffle of the LHS value?
9841 isLHSID &= (Mask[i] == i);
9842
9843 // Is this an identity shuffle of the RHS value?
9844 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009845 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009846
Chris Lattner12249be2006-05-25 23:48:38 +00009847 // Eliminate identity shuffles.
9848 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9849 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009850
Chris Lattner0e477162006-05-26 00:29:06 +00009851 // If the LHS is a shufflevector itself, see if we can combine it with this
9852 // one without producing an unusual shuffle. Here we are really conservative:
9853 // we are absolutely afraid of producing a shuffle mask not in the input
9854 // program, because the code gen may not be smart enough to turn a merged
9855 // shuffle into two specific shuffles: it may produce worse code. As such,
9856 // we only merge two shuffles if the result is one of the two input shuffle
9857 // masks. In this case, merging the shuffles just removes one instruction,
9858 // which we know is safe. This is good for things like turning:
9859 // (splat(splat)) -> splat.
9860 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9861 if (isa<UndefValue>(RHS)) {
9862 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9863
9864 std::vector<unsigned> NewMask;
9865 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9866 if (Mask[i] >= 2*e)
9867 NewMask.push_back(2*e);
9868 else
9869 NewMask.push_back(LHSMask[Mask[i]]);
9870
9871 // If the result mask is equal to the src shuffle or this shuffle mask, do
9872 // the replacement.
9873 if (NewMask == LHSMask || NewMask == Mask) {
9874 std::vector<Constant*> Elts;
9875 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9876 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009877 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009878 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009879 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009880 }
9881 }
9882 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9883 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009884 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009885 }
9886 }
9887 }
Chris Lattner4284f642007-01-30 22:32:46 +00009888
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009889 return MadeChange ? &SVI : 0;
9890}
9891
9892
Robert Bocchinoa8352962006-01-13 22:48:06 +00009893
Chris Lattner39c98bb2004-12-08 23:43:58 +00009894
9895/// TryToSinkInstruction - Try to move the specified instruction from its
9896/// current block into the beginning of DestBlock, which can only happen if it's
9897/// safe to move the instruction past all of the instructions between it and the
9898/// end of its block.
9899static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9900 assert(I->hasOneUse() && "Invariants didn't hold!");
9901
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009902 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9903 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009904
Chris Lattner39c98bb2004-12-08 23:43:58 +00009905 // Do not sink alloca instructions out of the entry block.
9906 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9907 return false;
9908
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009909 // We can only sink load instructions if there is nothing between the load and
9910 // the end of block that could change the value.
9911 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009912 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9913 Scan != E; ++Scan)
9914 if (Scan->mayWriteToMemory())
9915 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009916 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009917
9918 BasicBlock::iterator InsertPos = DestBlock->begin();
9919 while (isa<PHINode>(InsertPos)) ++InsertPos;
9920
Chris Lattner9f269e42005-08-08 19:11:57 +00009921 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009922 ++NumSunkInst;
9923 return true;
9924}
9925
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009926
9927/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9928/// all reachable code to the worklist.
9929///
9930/// This has a couple of tricks to make the code faster and more powerful. In
9931/// particular, we constant fold and DCE instructions as we go, to avoid adding
9932/// them to the worklist (this significantly speeds up instcombine on code where
9933/// many instructions are dead or constant). Additionally, if we find a branch
9934/// whose condition is a known constant, we only visit the reachable successors.
9935///
9936static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009937 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009938 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009939 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009940 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009941 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009942
9943 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9944 Instruction *Inst = BBI++;
9945
9946 // DCE instruction if trivially dead.
9947 if (isInstructionTriviallyDead(Inst)) {
9948 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009949 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009950 Inst->eraseFromParent();
9951 continue;
9952 }
9953
9954 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009955 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009956 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009957 Inst->replaceAllUsesWith(C);
9958 ++NumConstProp;
9959 Inst->eraseFromParent();
9960 continue;
9961 }
9962
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009963 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009964 }
9965
9966 // Recursively visit successors. If this is a branch or switch on a constant,
9967 // only visit the reachable successor.
9968 TerminatorInst *TI = BB->getTerminator();
9969 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009970 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009971 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009972 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009973 return;
9974 }
9975 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9976 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9977 // See if this is an explicit destination.
9978 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9979 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009980 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009981 return;
9982 }
9983
9984 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009985 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009986 return;
9987 }
9988 }
9989
9990 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009991 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009992}
9993
Chris Lattner960a5432007-03-03 02:04:50 +00009994bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009995 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009996 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009997
9998 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9999 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000010000
Chris Lattner4ed40f72005-07-07 20:40:38 +000010001 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010002 // Do a depth-first traversal of the function, populate the worklist with
10003 // the reachable instructions. Ignore blocks that are not reachable. Keep
10004 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000010005 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010006 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000010007
Chris Lattner4ed40f72005-07-07 20:40:38 +000010008 // Do a quick scan over the function. If we find any blocks that are
10009 // unreachable, remove any instructions inside of them. This prevents
10010 // the instcombine code from having to deal with some bad special cases.
10011 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10012 if (!Visited.count(BB)) {
10013 Instruction *Term = BB->getTerminator();
10014 while (Term != BB->begin()) { // Remove instrs bottom-up
10015 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000010016
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010017 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +000010018 ++NumDeadInst;
10019
10020 if (!I->use_empty())
10021 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10022 I->eraseFromParent();
10023 }
10024 }
10025 }
Chris Lattnerca081252001-12-14 16:52:21 +000010026
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010027 while (!Worklist.empty()) {
10028 Instruction *I = RemoveOneFromWorkList();
10029 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000010030
Chris Lattner1443bc52006-05-11 17:11:52 +000010031 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000010032 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000010033 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010034 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000010035 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000010036 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010037
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010038 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000010039
10040 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010041 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010042 continue;
10043 }
Chris Lattner99f48c62002-09-02 04:59:56 +000010044
Chris Lattner1443bc52006-05-11 17:11:52 +000010045 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +000010046 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010047 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000010048
Chris Lattner1443bc52006-05-11 17:11:52 +000010049 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000010050 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000010051 ReplaceInstUsesWith(*I, C);
10052
Chris Lattner99f48c62002-09-02 04:59:56 +000010053 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010054 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010055 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010056 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000010057 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010058
Chris Lattner39c98bb2004-12-08 23:43:58 +000010059 // See if we can trivially sink this instruction to a successor basic block.
10060 if (I->hasOneUse()) {
10061 BasicBlock *BB = I->getParent();
10062 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10063 if (UserParent != BB) {
10064 bool UserIsSuccessor = false;
10065 // See if the user is one of our successors.
10066 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10067 if (*SI == UserParent) {
10068 UserIsSuccessor = true;
10069 break;
10070 }
10071
10072 // If the user is one of our immediate successors, and if that successor
10073 // only has us as a predecessors (we'd have to split the critical edge
10074 // otherwise), we can keep going.
10075 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10076 next(pred_begin(UserParent)) == pred_end(UserParent))
10077 // Okay, the CFG is simple enough, try to sink this instruction.
10078 Changed |= TryToSinkInstruction(I, UserParent);
10079 }
10080 }
10081
Chris Lattnerca081252001-12-14 16:52:21 +000010082 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010083 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000010084 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000010085 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000010086 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010087 DOUT << "IC: Old = " << *I
10088 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000010089
Chris Lattner396dbfe2004-06-09 05:08:07 +000010090 // Everything uses the new instruction now.
10091 I->replaceAllUsesWith(Result);
10092
10093 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010094 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000010095 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010096
Chris Lattner6e0123b2007-02-11 01:23:03 +000010097 // Move the name to the new instruction first.
10098 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010099
10100 // Insert the new instruction into the basic block...
10101 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000010102 BasicBlock::iterator InsertPos = I;
10103
10104 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10105 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10106 ++InsertPos;
10107
10108 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010109
Chris Lattner63d75af2004-05-01 23:27:23 +000010110 // Make sure that we reprocess all operands now that we reduced their
10111 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010112 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000010113
Chris Lattner396dbfe2004-06-09 05:08:07 +000010114 // Instructions can end up on the worklist more than once. Make sure
10115 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010116 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010117
10118 // Erase the old instruction.
10119 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000010120 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010121 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +000010122
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010123 // If the instruction was modified, it's possible that it is now dead.
10124 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000010125 if (isInstructionTriviallyDead(I)) {
10126 // Make sure we process all operands now that we are reducing their
10127 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000010128 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010129
Chris Lattner63d75af2004-05-01 23:27:23 +000010130 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000010131 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010132 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000010133 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000010134 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000010135 AddToWorkList(I);
10136 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010137 }
Chris Lattner053c0932002-05-14 15:24:07 +000010138 }
Chris Lattner260ab202002-04-18 17:39:14 +000010139 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000010140 }
10141 }
10142
Chris Lattner960a5432007-03-03 02:04:50 +000010143 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +000010144 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000010145}
10146
Chris Lattner960a5432007-03-03 02:04:50 +000010147
10148bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000010149 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10150
Chris Lattner960a5432007-03-03 02:04:50 +000010151 bool EverMadeChange = false;
10152
10153 // Iterate while there is work to do.
10154 unsigned Iteration = 0;
10155 while (DoOneIteration(F, Iteration++))
10156 EverMadeChange = true;
10157 return EverMadeChange;
10158}
10159
Brian Gaeke38b79e82004-07-27 17:43:21 +000010160FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000010161 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000010162}
Brian Gaeke960707c2003-11-11 22:41:34 +000010163