blob: 87f96674285e3b20e28f79238d32f2672d00489b [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencer755d0e72007-03-26 17:44:01 +000059#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000062
Chris Lattner79a42ac2006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000068
Chris Lattner79a42ac2006-12-19 21:40:18 +000069namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattner260ab202002-04-18 17:39:14 +0000103
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000104
Chris Lattner51ea1272004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000113 }
114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000122 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000142
Chris Lattner260ab202002-04-18 17:39:14 +0000143 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000147
Chris Lattnerf12cc842002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000152 }
153
Chris Lattner69193f92004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattner260ab202002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000186
Reid Spencer266e42b2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224
Chris Lattner970c33a2003-06-19 17:00:31 +0000225 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner69193f92004-04-05 01:30:19 +0000229 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner623826c2004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000239 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 }
241
Chris Lattner7e794272004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000248
Chris Lattnere79d2492006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000251
Reid Spencer13bc5d72006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000274 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000275
Chris Lattner2590e512006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner51ea1272004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattner3ac7c262003-08-13 20:16:26 +0000305 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencer266e42b2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000317
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Reid Spencer959a21d2007-03-23 21:24:59 +0000322 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
323 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000324 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
325 APInt& KnownZero, APInt& KnownOne,
326 unsigned Depth = 0);
327
Chris Lattner2deeaea2006-10-05 06:55:50 +0000328 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
329 uint64_t &UndefElts, unsigned Depth = 0);
330
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000331 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
332 // PHI node as operand #0, see if we can fold the instruction into the PHI
333 // (which is only possible if all operands to the PHI are constants).
334 Instruction *FoldOpIntoPhi(Instruction &I);
335
Chris Lattner7515cab2004-11-14 19:13:23 +0000336 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
337 // operator and they all are only used by the PHI, PHI together their
338 // inputs, and do the operation once, to the result of the PHI.
339 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000340 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
341
342
Zhou Sheng75b871f2007-01-11 12:24:14 +0000343 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
344 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000345
Zhou Sheng75b871f2007-01-11 12:24:14 +0000346 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000347 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000348 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000349 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000350 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000351 Instruction *MatchBSwap(BinaryOperator &I);
352
Reid Spencer74a528b2006-12-13 18:21:21 +0000353 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000354 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000355
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000356 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000357}
358
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000360// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000361static unsigned getComplexity(Value *V) {
362 if (isa<Instruction>(V)) {
363 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000364 return 3;
365 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000366 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000367 if (isa<Argument>(V)) return 3;
368 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000369}
Chris Lattner260ab202002-04-18 17:39:14 +0000370
Chris Lattner7fb29e12003-03-11 00:12:48 +0000371// isOnlyUse - Return true if this instruction will be deleted if we stop using
372// it.
373static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000374 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375}
376
Chris Lattnere79e8542004-02-23 06:38:22 +0000377// getPromotedType - Return the specified type promoted as it would be to pass
378// though a va_arg area...
379static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000380 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
381 if (ITy->getBitWidth() < 32)
382 return Type::Int32Ty;
383 } else if (Ty == Type::FloatTy)
384 return Type::DoubleTy;
385 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000386}
387
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000388/// getBitCastOperand - If the specified operand is a CastInst or a constant
389/// expression bitcast, return the operand value, otherwise return null.
390static Value *getBitCastOperand(Value *V) {
391 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000392 return I->getOperand(0);
393 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000394 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000395 return CE->getOperand(0);
396 return 0;
397}
398
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399/// This function is a wrapper around CastInst::isEliminableCastPair. It
400/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000401static Instruction::CastOps
402isEliminableCastPair(
403 const CastInst *CI, ///< The first cast instruction
404 unsigned opcode, ///< The opcode of the second cast instruction
405 const Type *DstTy, ///< The target type for the second cast instruction
406 TargetData *TD ///< The target data for pointer size
407) {
408
409 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
410 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000411
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000412 // Get the opcodes of the two Cast instructions
413 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
414 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000415
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000416 return Instruction::CastOps(
417 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
418 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000419}
420
421/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
422/// in any code being generated. It does not require codegen if V is simple
423/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000424static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
425 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000426 if (V->getType() == Ty || isa<Constant>(V)) return false;
427
Chris Lattner99155be2006-05-25 23:24:33 +0000428 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000430 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 return false;
432 return true;
433}
434
435/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
436/// InsertBefore instruction. This is specialized a bit to avoid inserting
437/// casts that are known to not do anything...
438///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000439Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
440 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000441 Instruction *InsertBefore) {
442 if (V->getType() == DestTy) return V;
443 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445
Reid Spencer13bc5d72006-12-12 09:18:51 +0000446 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447}
448
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000449// SimplifyCommutative - This performs a few simplifications for commutative
450// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000451//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452// 1. Order operands such that they are listed from right (least complex) to
453// left (most complex). This puts constants before unary operators before
454// binary operators.
455//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000456// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
457// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000459bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 bool Changed = false;
461 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
462 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000463
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000464 if (!I.isAssociative()) return Changed;
465 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
467 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
468 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000469 Constant *Folded = ConstantExpr::get(I.getOpcode(),
470 cast<Constant>(I.getOperand(1)),
471 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000472 I.setOperand(0, Op->getOperand(0));
473 I.setOperand(1, Folded);
474 return true;
475 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
476 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
477 isOnlyUse(Op) && isOnlyUse(Op1)) {
478 Constant *C1 = cast<Constant>(Op->getOperand(1));
479 Constant *C2 = cast<Constant>(Op1->getOperand(1));
480
481 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000482 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
484 Op1->getOperand(0),
485 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000486 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487 I.setOperand(0, New);
488 I.setOperand(1, Folded);
489 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000490 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000491 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000492 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000493}
Chris Lattnerca081252001-12-14 16:52:21 +0000494
Reid Spencer266e42b2006-12-23 06:05:41 +0000495/// SimplifyCompare - For a CmpInst this function just orders the operands
496/// so that theyare listed from right (least complex) to left (most complex).
497/// This puts constants before unary operators before binary operators.
498bool InstCombiner::SimplifyCompare(CmpInst &I) {
499 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
500 return false;
501 I.swapOperands();
502 // Compare instructions are not associative so there's nothing else we can do.
503 return true;
504}
505
Chris Lattnerbb74e222003-03-10 23:06:50 +0000506// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
507// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000508//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509static inline Value *dyn_castNegVal(Value *V) {
510 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000511 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000512
Chris Lattner9ad0d552004-12-14 20:08:06 +0000513 // Constants can be considered to be negated values if they can be folded.
514 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
515 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517}
518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519static inline Value *dyn_castNotVal(Value *V) {
520 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000521 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522
523 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000524 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000525 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000526 return 0;
527}
528
Chris Lattner7fb29e12003-03-11 00:12:48 +0000529// dyn_castFoldableMul - If this value is a multiply that can be folded into
530// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000531// non-constant operand of the multiply, and set CST to point to the multiplier.
532// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000533//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000535 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000538 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000541 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000542 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000543 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000544 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000545 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000546 return I->getOperand(0);
547 }
548 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000549 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000550}
Chris Lattner31ae8632002-08-14 17:51:49 +0000551
Chris Lattner0798af32005-01-13 20:14:25 +0000552/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
553/// expression, return it.
554static User *dyn_castGetElementPtr(Value *V) {
555 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
556 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
557 if (CE->getOpcode() == Instruction::GetElementPtr)
558 return cast<User>(V);
559 return false;
560}
561
Reid Spencer80263aa2007-03-25 05:33:51 +0000562/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000563static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000564 APInt Val(C->getValue());
565 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000566}
Reid Spencer80263aa2007-03-25 05:33:51 +0000567/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000568static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000569 APInt Val(C->getValue());
570 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000571}
572/// Add - Add two ConstantInts together
573static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
574 return ConstantInt::get(C1->getValue() + C2->getValue());
575}
576/// And - Bitwise AND two ConstantInts together
577static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
578 return ConstantInt::get(C1->getValue() & C2->getValue());
579}
580/// Subtract - Subtract one ConstantInt from another
581static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
582 return ConstantInt::get(C1->getValue() - C2->getValue());
583}
584/// Multiply - Multiply two ConstantInts together
585static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
586 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000587}
588
Chris Lattner4534dd592006-02-09 07:38:58 +0000589/// ComputeMaskedBits - Determine which of the bits specified in Mask are
590/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000591/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
592/// processing.
593/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
594/// we cannot optimize based on the assumption that it is zero without changing
595/// it to be an explicit zero. If we don't change it to zero, other code could
596/// optimized based on the contradictory assumption that it is non-zero.
597/// Because instcombine aggressively folds operations with undef args anyway,
598/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000599static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000600 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000601 assert(V && "No Value?");
602 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000603 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000604 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000605 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000606 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000607 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000608 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
609 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000610 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000611 KnownZero = ~KnownOne & Mask;
612 return;
613 }
614
Reid Spenceraa696402007-03-08 01:46:38 +0000615 if (Depth == 6 || Mask == 0)
616 return; // Limit search depth.
617
618 Instruction *I = dyn_cast<Instruction>(V);
619 if (!I) return;
620
Zhou Shengaf4341d2007-03-13 02:23:10 +0000621 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000622 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000623
624 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000625 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000626 // If either the LHS or the RHS are Zero, the result is zero.
627 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000628 APInt Mask2(Mask & ~KnownZero);
629 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000630 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
631 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
632
633 // Output known-1 bits are only known if set in both the LHS & RHS.
634 KnownOne &= KnownOne2;
635 // Output known-0 are known to be clear if zero in either the LHS | RHS.
636 KnownZero |= KnownZero2;
637 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000638 }
639 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000640 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000641 APInt Mask2(Mask & ~KnownOne);
642 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000643 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
644 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
645
646 // Output known-0 bits are only known if clear in both the LHS & RHS.
647 KnownZero &= KnownZero2;
648 // Output known-1 are known to be set if set in either the LHS | RHS.
649 KnownOne |= KnownOne2;
650 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000651 }
Reid Spenceraa696402007-03-08 01:46:38 +0000652 case Instruction::Xor: {
653 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
654 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
655 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
656 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
657
658 // Output known-0 bits are known if clear or set in both the LHS & RHS.
659 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
660 // Output known-1 are known to be set if set in only one of the LHS, RHS.
661 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
662 KnownZero = KnownZeroOut;
663 return;
664 }
665 case Instruction::Select:
666 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
667 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
668 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
669 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
670
671 // Only known if known in both the LHS and RHS.
672 KnownOne &= KnownOne2;
673 KnownZero &= KnownZero2;
674 return;
675 case Instruction::FPTrunc:
676 case Instruction::FPExt:
677 case Instruction::FPToUI:
678 case Instruction::FPToSI:
679 case Instruction::SIToFP:
680 case Instruction::PtrToInt:
681 case Instruction::UIToFP:
682 case Instruction::IntToPtr:
683 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000684 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000685 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000686 uint32_t SrcBitWidth =
687 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000688 APInt MaskIn(Mask);
689 MaskIn.zext(SrcBitWidth);
690 KnownZero.zext(SrcBitWidth);
691 KnownOne.zext(SrcBitWidth);
692 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000693 KnownZero.trunc(BitWidth);
694 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000695 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000696 }
Reid Spenceraa696402007-03-08 01:46:38 +0000697 case Instruction::BitCast: {
698 const Type *SrcTy = I->getOperand(0)->getType();
699 if (SrcTy->isInteger()) {
700 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
701 return;
702 }
703 break;
704 }
705 case Instruction::ZExt: {
706 // Compute the bits in the result that are not present in the input.
707 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000708 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000709
Zhou Sheng57e3f732007-03-28 02:19:03 +0000710 APInt MaskIn(Mask);
711 MaskIn.trunc(SrcBitWidth);
712 KnownZero.trunc(SrcBitWidth);
713 KnownOne.trunc(SrcBitWidth);
714 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000715 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
716 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000717 KnownZero.zext(BitWidth);
718 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000719 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000720 return;
721 }
722 case Instruction::SExt: {
723 // Compute the bits in the result that are not present in the input.
724 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000725 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000726
Zhou Sheng57e3f732007-03-28 02:19:03 +0000727 APInt MaskIn(Mask);
728 MaskIn.trunc(SrcBitWidth);
729 KnownZero.trunc(SrcBitWidth);
730 KnownOne.trunc(SrcBitWidth);
731 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000732 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000733 KnownZero.zext(BitWidth);
734 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000735
736 // If the sign bit of the input is known set or clear, then we know the
737 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000738 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000739 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000740 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000741 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000742 return;
743 }
744 case Instruction::Shl:
745 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
746 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +0000747 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencerd8aad612007-03-25 02:03:12 +0000748 APInt Mask2(Mask.lshr(ShiftAmt));
749 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000750 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000751 KnownZero <<= ShiftAmt;
752 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000753 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000754 return;
755 }
756 break;
757 case Instruction::LShr:
758 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
759 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
760 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000761 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000762
763 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000764 APInt Mask2(Mask.shl(ShiftAmt));
765 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000766 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
767 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
768 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000769 // high bits known zero.
770 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000771 return;
772 }
773 break;
774 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000775 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000776 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
777 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000778 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000779
780 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000781 APInt Mask2(Mask.shl(ShiftAmt));
782 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000783 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
784 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
785 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
786
Zhou Sheng57e3f732007-03-28 02:19:03 +0000787 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
788 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000789 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000790 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000791 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000792 return;
793 }
794 break;
795 }
796}
797
Reid Spencerbb5741f2007-03-08 01:52:58 +0000798/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
799/// this predicate to simplify operations downstream. Mask is known to be zero
800/// for bits that V cannot have.
801static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000802 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000803 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
804 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
805 return (KnownZero & Mask) == Mask;
806}
807
Chris Lattner0157e7f2006-02-11 09:31:47 +0000808/// ShrinkDemandedConstant - Check to see if the specified operand of the
809/// specified instruction is a constant integer. If so, check to see if there
810/// are any bits set in the constant that are not demanded. If so, shrink the
811/// constant and return true.
812static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000813 APInt Demanded) {
814 assert(I && "No instruction?");
815 assert(OpNo < I->getNumOperands() && "Operand index too large");
816
817 // If the operand is not a constant integer, nothing to do.
818 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
819 if (!OpC) return false;
820
821 // If there are no bits set that aren't demanded, nothing to do.
822 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
823 if ((~Demanded & OpC->getValue()) == 0)
824 return false;
825
826 // This instruction is producing bits that are not demanded. Shrink the RHS.
827 Demanded &= OpC->getValue();
828 I->setOperand(OpNo, ConstantInt::get(Demanded));
829 return true;
830}
831
Chris Lattneree0f2802006-02-12 02:07:56 +0000832// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
833// set of known zero and one bits, compute the maximum and minimum values that
834// could have the specified known zero and known one bits, returning them in
835// min/max.
836static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000837 const APInt& KnownZero,
838 const APInt& KnownOne,
839 APInt& Min, APInt& Max) {
840 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
841 assert(KnownZero.getBitWidth() == BitWidth &&
842 KnownOne.getBitWidth() == BitWidth &&
843 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
844 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000845 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000846
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000847 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +0000848
849 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
850 // bit if it is unknown.
851 Min = KnownOne;
852 Max = KnownOne|UnknownBits;
853
Zhou Shengc2d33092007-03-28 05:15:57 +0000854 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Chris Lattneree0f2802006-02-12 02:07:56 +0000855 Min |= SignBit;
856 Max &= ~SignBit;
857 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000858}
859
860// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
861// a set of known zero and one bits, compute the maximum and minimum values that
862// could have the specified known zero and known one bits, returning them in
863// min/max.
864static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000865 const APInt& KnownZero,
866 const APInt& KnownOne,
867 APInt& Min,
868 APInt& Max) {
869 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
870 assert(KnownZero.getBitWidth() == BitWidth &&
871 KnownOne.getBitWidth() == BitWidth &&
872 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
873 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000874 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000875
876 // The minimum value is when the unknown bits are all zeros.
877 Min = KnownOne;
878 // The maximum value is when the unknown bits are all ones.
879 Max = KnownOne|UnknownBits;
880}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881
Reid Spencer1791f232007-03-12 17:25:59 +0000882/// SimplifyDemandedBits - This function attempts to replace V with a simpler
883/// value based on the demanded bits. When this function is called, it is known
884/// that only the bits set in DemandedMask of the result of V are ever used
885/// downstream. Consequently, depending on the mask and V, it may be possible
886/// to replace V with a constant or one of its operands. In such cases, this
887/// function does the replacement and returns true. In all other cases, it
888/// returns false after analyzing the expression and setting KnownOne and known
889/// to be one in the expression. KnownZero contains all the bits that are known
890/// to be zero in the expression. These are provided to potentially allow the
891/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
892/// the expression. KnownOne and KnownZero always follow the invariant that
893/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
894/// the bits in KnownOne and KnownZero may only be accurate for those bits set
895/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
896/// and KnownOne must all be the same.
897bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
898 APInt& KnownZero, APInt& KnownOne,
899 unsigned Depth) {
900 assert(V != 0 && "Null pointer of Value???");
901 assert(Depth <= 6 && "Limit Search Depth");
902 uint32_t BitWidth = DemandedMask.getBitWidth();
903 const IntegerType *VTy = cast<IntegerType>(V->getType());
904 assert(VTy->getBitWidth() == BitWidth &&
905 KnownZero.getBitWidth() == BitWidth &&
906 KnownOne.getBitWidth() == BitWidth &&
907 "Value *V, DemandedMask, KnownZero and KnownOne \
908 must have same BitWidth");
909 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
910 // We know all of the bits for a constant!
911 KnownOne = CI->getValue() & DemandedMask;
912 KnownZero = ~KnownOne & DemandedMask;
913 return false;
914 }
915
Zhou Shengb9128442007-03-14 03:21:24 +0000916 KnownZero.clear();
917 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000918 if (!V->hasOneUse()) { // Other users may use these bits.
919 if (Depth != 0) { // Not at the root.
920 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
921 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
922 return false;
923 }
924 // If this is the root being simplified, allow it to have multiple uses,
925 // just set the DemandedMask to all bits.
926 DemandedMask = APInt::getAllOnesValue(BitWidth);
927 } else if (DemandedMask == 0) { // Not demanding any bits from V.
928 if (V != UndefValue::get(VTy))
929 return UpdateValueUsesWith(V, UndefValue::get(VTy));
930 return false;
931 } else if (Depth == 6) { // Limit search depth.
932 return false;
933 }
934
935 Instruction *I = dyn_cast<Instruction>(V);
936 if (!I) return false; // Only analyze instructions.
937
Reid Spencer1791f232007-03-12 17:25:59 +0000938 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
939 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
940 switch (I->getOpcode()) {
941 default: break;
942 case Instruction::And:
943 // If either the LHS or the RHS are Zero, the result is zero.
944 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
945 RHSKnownZero, RHSKnownOne, Depth+1))
946 return true;
947 assert((RHSKnownZero & RHSKnownOne) == 0 &&
948 "Bits known to be one AND zero?");
949
950 // If something is known zero on the RHS, the bits aren't demanded on the
951 // LHS.
952 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
953 LHSKnownZero, LHSKnownOne, Depth+1))
954 return true;
955 assert((LHSKnownZero & LHSKnownOne) == 0 &&
956 "Bits known to be one AND zero?");
957
958 // If all of the demanded bits are known 1 on one side, return the other.
959 // These bits cannot contribute to the result of the 'and'.
960 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
961 (DemandedMask & ~LHSKnownZero))
962 return UpdateValueUsesWith(I, I->getOperand(0));
963 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
964 (DemandedMask & ~RHSKnownZero))
965 return UpdateValueUsesWith(I, I->getOperand(1));
966
967 // If all of the demanded bits in the inputs are known zeros, return zero.
968 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
969 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
970
971 // If the RHS is a constant, see if we can simplify it.
972 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
973 return UpdateValueUsesWith(I, I);
974
975 // Output known-1 bits are only known if set in both the LHS & RHS.
976 RHSKnownOne &= LHSKnownOne;
977 // Output known-0 are known to be clear if zero in either the LHS | RHS.
978 RHSKnownZero |= LHSKnownZero;
979 break;
980 case Instruction::Or:
981 // If either the LHS or the RHS are One, the result is One.
982 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
983 RHSKnownZero, RHSKnownOne, Depth+1))
984 return true;
985 assert((RHSKnownZero & RHSKnownOne) == 0 &&
986 "Bits known to be one AND zero?");
987 // If something is known one on the RHS, the bits aren't demanded on the
988 // LHS.
989 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
990 LHSKnownZero, LHSKnownOne, Depth+1))
991 return true;
992 assert((LHSKnownZero & LHSKnownOne) == 0 &&
993 "Bits known to be one AND zero?");
994
995 // If all of the demanded bits are known zero on one side, return the other.
996 // These bits cannot contribute to the result of the 'or'.
997 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
998 (DemandedMask & ~LHSKnownOne))
999 return UpdateValueUsesWith(I, I->getOperand(0));
1000 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1001 (DemandedMask & ~RHSKnownOne))
1002 return UpdateValueUsesWith(I, I->getOperand(1));
1003
1004 // If all of the potentially set bits on one side are known to be set on
1005 // the other side, just use the 'other' side.
1006 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1007 (DemandedMask & (~RHSKnownZero)))
1008 return UpdateValueUsesWith(I, I->getOperand(0));
1009 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1010 (DemandedMask & (~LHSKnownZero)))
1011 return UpdateValueUsesWith(I, I->getOperand(1));
1012
1013 // If the RHS is a constant, see if we can simplify it.
1014 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1015 return UpdateValueUsesWith(I, I);
1016
1017 // Output known-0 bits are only known if clear in both the LHS & RHS.
1018 RHSKnownZero &= LHSKnownZero;
1019 // Output known-1 are known to be set if set in either the LHS | RHS.
1020 RHSKnownOne |= LHSKnownOne;
1021 break;
1022 case Instruction::Xor: {
1023 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1024 RHSKnownZero, RHSKnownOne, Depth+1))
1025 return true;
1026 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1027 "Bits known to be one AND zero?");
1028 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1029 LHSKnownZero, LHSKnownOne, Depth+1))
1030 return true;
1031 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1032 "Bits known to be one AND zero?");
1033
1034 // If all of the demanded bits are known zero on one side, return the other.
1035 // These bits cannot contribute to the result of the 'xor'.
1036 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1037 return UpdateValueUsesWith(I, I->getOperand(0));
1038 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1039 return UpdateValueUsesWith(I, I->getOperand(1));
1040
1041 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1042 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1043 (RHSKnownOne & LHSKnownOne);
1044 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1045 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1046 (RHSKnownOne & LHSKnownZero);
1047
1048 // If all of the demanded bits are known to be zero on one side or the
1049 // other, turn this into an *inclusive* or.
1050 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1051 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1052 Instruction *Or =
1053 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1054 I->getName());
1055 InsertNewInstBefore(Or, *I);
1056 return UpdateValueUsesWith(I, Or);
1057 }
1058
1059 // If all of the demanded bits on one side are known, and all of the set
1060 // bits on that side are also known to be set on the other side, turn this
1061 // into an AND, as we know the bits will be cleared.
1062 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1063 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1064 // all known
1065 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1066 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1067 Instruction *And =
1068 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1069 InsertNewInstBefore(And, *I);
1070 return UpdateValueUsesWith(I, And);
1071 }
1072 }
1073
1074 // If the RHS is a constant, see if we can simplify it.
1075 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1076 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1077 return UpdateValueUsesWith(I, I);
1078
1079 RHSKnownZero = KnownZeroOut;
1080 RHSKnownOne = KnownOneOut;
1081 break;
1082 }
1083 case Instruction::Select:
1084 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1085 RHSKnownZero, RHSKnownOne, Depth+1))
1086 return true;
1087 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1088 LHSKnownZero, LHSKnownOne, Depth+1))
1089 return true;
1090 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1091 "Bits known to be one AND zero?");
1092 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1093 "Bits known to be one AND zero?");
1094
1095 // If the operands are constants, see if we can simplify them.
1096 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1097 return UpdateValueUsesWith(I, I);
1098 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1099 return UpdateValueUsesWith(I, I);
1100
1101 // Only known if known in both the LHS and RHS.
1102 RHSKnownOne &= LHSKnownOne;
1103 RHSKnownZero &= LHSKnownZero;
1104 break;
1105 case Instruction::Trunc: {
1106 uint32_t truncBf =
1107 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +00001108 DemandedMask.zext(truncBf);
1109 RHSKnownZero.zext(truncBf);
1110 RHSKnownOne.zext(truncBf);
1111 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1112 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001113 return true;
1114 DemandedMask.trunc(BitWidth);
1115 RHSKnownZero.trunc(BitWidth);
1116 RHSKnownOne.trunc(BitWidth);
1117 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1118 "Bits known to be one AND zero?");
1119 break;
1120 }
1121 case Instruction::BitCast:
1122 if (!I->getOperand(0)->getType()->isInteger())
1123 return false;
1124
1125 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1126 RHSKnownZero, RHSKnownOne, Depth+1))
1127 return true;
1128 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1129 "Bits known to be one AND zero?");
1130 break;
1131 case Instruction::ZExt: {
1132 // Compute the bits in the result that are not present in the input.
1133 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001134 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001135
1136 DemandedMask &= SrcTy->getMask().zext(BitWidth);
Zhou Sheng444af492007-03-29 04:45:55 +00001137 DemandedMask.trunc(SrcBitWidth);
1138 RHSKnownZero.trunc(SrcBitWidth);
1139 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001140 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001142 return true;
1143 DemandedMask.zext(BitWidth);
1144 RHSKnownZero.zext(BitWidth);
1145 RHSKnownOne.zext(BitWidth);
1146 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1147 "Bits known to be one AND zero?");
1148 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001149 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001150 break;
1151 }
1152 case Instruction::SExt: {
1153 // Compute the bits in the result that are not present in the input.
1154 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001155 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001156
1157 // Get the sign bit for the source type
Zhou Shenga4475572007-03-29 02:26:30 +00001158 APInt InSignBit(APInt::getSignBit(SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001159 InSignBit.zext(BitWidth);
1160 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001161 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001162
Zhou Shenga4475572007-03-29 02:26:30 +00001163 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001164 // If any of the sign extended bits are demanded, we know that the sign
1165 // bit is demanded.
1166 if ((NewBits & DemandedMask) != 0)
1167 InputDemandedBits |= InSignBit;
1168
Zhou Sheng444af492007-03-29 04:45:55 +00001169 InputDemandedBits.trunc(SrcBitWidth);
1170 RHSKnownZero.trunc(SrcBitWidth);
1171 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001172 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1173 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001174 return true;
1175 InputDemandedBits.zext(BitWidth);
1176 RHSKnownZero.zext(BitWidth);
1177 RHSKnownOne.zext(BitWidth);
1178 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1179 "Bits known to be one AND zero?");
1180
1181 // If the sign bit of the input is known set or clear, then we know the
1182 // top bits of the result.
1183
1184 // If the input sign bit is known zero, or if the NewBits are not demanded
1185 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001186 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001187 {
1188 // Convert to ZExt cast
1189 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1190 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001191 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001192 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001193 }
1194 break;
1195 }
1196 case Instruction::Add: {
1197 // Figure out what the input bits are. If the top bits of the and result
1198 // are not demanded, then the add doesn't demand them from its input
1199 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001200 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001201
1202 // If there is a constant on the RHS, there are a variety of xformations
1203 // we can do.
1204 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205 // If null, this should be simplified elsewhere. Some of the xforms here
1206 // won't work if the RHS is zero.
1207 if (RHS->isZero())
1208 break;
1209
1210 // If the top bit of the output is demanded, demand everything from the
1211 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001212 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001213
1214 // Find information about known zero/one bits in the input.
1215 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1216 LHSKnownZero, LHSKnownOne, Depth+1))
1217 return true;
1218
1219 // If the RHS of the add has bits set that can't affect the input, reduce
1220 // the constant.
1221 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1222 return UpdateValueUsesWith(I, I);
1223
1224 // Avoid excess work.
1225 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1226 break;
1227
1228 // Turn it into OR if input bits are zero.
1229 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1230 Instruction *Or =
1231 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1232 I->getName());
1233 InsertNewInstBefore(Or, *I);
1234 return UpdateValueUsesWith(I, Or);
1235 }
1236
1237 // We can say something about the output known-zero and known-one bits,
1238 // depending on potential carries from the input constant and the
1239 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1240 // bits set and the RHS constant is 0x01001, then we know we have a known
1241 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1242
1243 // To compute this, we first compute the potential carry bits. These are
1244 // the bits which may be modified. I'm not aware of a better way to do
1245 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001246 const APInt& RHSVal = RHS->getValue();
1247 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001248
1249 // Now that we know which bits have carries, compute the known-1/0 sets.
1250
1251 // Bits are known one if they are known zero in one operand and one in the
1252 // other, and there is no input carry.
1253 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1254 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1255
1256 // Bits are known zero if they are known zero in both operands and there
1257 // is no input carry.
1258 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1259 } else {
1260 // If the high-bits of this ADD are not demanded, then it does not demand
1261 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001262 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001263 // Right fill the mask of bits for this ADD to demand the most
1264 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001265 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001266 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1267 LHSKnownZero, LHSKnownOne, Depth+1))
1268 return true;
1269 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1270 LHSKnownZero, LHSKnownOne, Depth+1))
1271 return true;
1272 }
1273 }
1274 break;
1275 }
1276 case Instruction::Sub:
1277 // If the high-bits of this SUB are not demanded, then it does not demand
1278 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001279 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001280 // Right fill the mask of bits for this SUB to demand the most
1281 // significant bit and all those below it.
Reid Spencer52830322007-03-25 21:11:44 +00001282 unsigned NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001283 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001284 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1285 LHSKnownZero, LHSKnownOne, Depth+1))
1286 return true;
1287 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1288 LHSKnownZero, LHSKnownOne, Depth+1))
1289 return true;
1290 }
1291 break;
1292 case Instruction::Shl:
1293 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001294 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001295 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1296 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001297 RHSKnownZero, RHSKnownOne, Depth+1))
1298 return true;
1299 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1300 "Bits known to be one AND zero?");
1301 RHSKnownZero <<= ShiftAmt;
1302 RHSKnownOne <<= ShiftAmt;
1303 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001304 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001305 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001306 }
1307 break;
1308 case Instruction::LShr:
1309 // For a logical shift right
1310 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001311 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001312
Reid Spencer1791f232007-03-12 17:25:59 +00001313 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001314 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1315 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001316 RHSKnownZero, RHSKnownOne, Depth+1))
1317 return true;
1318 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1319 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001320 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1321 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001322 if (ShiftAmt) {
1323 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001324 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001325 RHSKnownZero |= HighBits; // high bits known zero.
1326 }
Reid Spencer1791f232007-03-12 17:25:59 +00001327 }
1328 break;
1329 case Instruction::AShr:
1330 // If this is an arithmetic shift right and only the low-bit is set, we can
1331 // always convert this into a logical shr, even if the shift amount is
1332 // variable. The low bit of the shift cannot be an input sign bit unless
1333 // the shift amount is >= the size of the datatype, which is undefined.
1334 if (DemandedMask == 1) {
1335 // Perform the logical shift right.
1336 Value *NewVal = BinaryOperator::createLShr(
1337 I->getOperand(0), I->getOperand(1), I->getName());
1338 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1339 return UpdateValueUsesWith(I, NewVal);
1340 }
1341
1342 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001343 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001344
Reid Spencer1791f232007-03-12 17:25:59 +00001345 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001346 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001347 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001348 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001349 RHSKnownZero, RHSKnownOne, Depth+1))
1350 return true;
1351 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1352 "Bits known to be one AND zero?");
1353 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001354 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001355 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1356 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1357
1358 // Handle the sign bits.
1359 APInt SignBit(APInt::getSignBit(BitWidth));
1360 // Adjust to where it is now in the mask.
1361 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1362
1363 // If the input sign bit is known to be zero, or if none of the top bits
1364 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001365 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001366 (HighBits & ~DemandedMask) == HighBits) {
1367 // Perform the logical shift right.
1368 Value *NewVal = BinaryOperator::createLShr(
1369 I->getOperand(0), SA, I->getName());
1370 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1371 return UpdateValueUsesWith(I, NewVal);
1372 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1373 RHSKnownOne |= HighBits;
1374 }
1375 }
1376 break;
1377 }
1378
1379 // If the client is only demanding bits that we know, return the known
1380 // constant.
1381 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1382 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1383 return false;
1384}
1385
Chris Lattner2deeaea2006-10-05 06:55:50 +00001386
1387/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1388/// 64 or fewer elements. DemandedElts contains the set of elements that are
1389/// actually used by the caller. This method analyzes which elements of the
1390/// operand are undef and returns that information in UndefElts.
1391///
1392/// If the information about demanded elements can be used to simplify the
1393/// operation, the operation is simplified, then the resultant value is
1394/// returned. This returns null if no change was made.
1395Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1396 uint64_t &UndefElts,
1397 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001398 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001399 assert(VWidth <= 64 && "Vector too wide to analyze!");
1400 uint64_t EltMask = ~0ULL >> (64-VWidth);
1401 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1402 "Invalid DemandedElts!");
1403
1404 if (isa<UndefValue>(V)) {
1405 // If the entire vector is undefined, just return this info.
1406 UndefElts = EltMask;
1407 return 0;
1408 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1409 UndefElts = EltMask;
1410 return UndefValue::get(V->getType());
1411 }
1412
1413 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001414 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1415 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001416 Constant *Undef = UndefValue::get(EltTy);
1417
1418 std::vector<Constant*> Elts;
1419 for (unsigned i = 0; i != VWidth; ++i)
1420 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1421 Elts.push_back(Undef);
1422 UndefElts |= (1ULL << i);
1423 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1424 Elts.push_back(Undef);
1425 UndefElts |= (1ULL << i);
1426 } else { // Otherwise, defined.
1427 Elts.push_back(CP->getOperand(i));
1428 }
1429
1430 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001431 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001432 return NewCP != CP ? NewCP : 0;
1433 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001434 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001435 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001436 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001437 Constant *Zero = Constant::getNullValue(EltTy);
1438 Constant *Undef = UndefValue::get(EltTy);
1439 std::vector<Constant*> Elts;
1440 for (unsigned i = 0; i != VWidth; ++i)
1441 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1442 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001443 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001444 }
1445
1446 if (!V->hasOneUse()) { // Other users may use these bits.
1447 if (Depth != 0) { // Not at the root.
1448 // TODO: Just compute the UndefElts information recursively.
1449 return false;
1450 }
1451 return false;
1452 } else if (Depth == 10) { // Limit search depth.
1453 return false;
1454 }
1455
1456 Instruction *I = dyn_cast<Instruction>(V);
1457 if (!I) return false; // Only analyze instructions.
1458
1459 bool MadeChange = false;
1460 uint64_t UndefElts2;
1461 Value *TmpV;
1462 switch (I->getOpcode()) {
1463 default: break;
1464
1465 case Instruction::InsertElement: {
1466 // If this is a variable index, we don't know which element it overwrites.
1467 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001468 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001469 if (Idx == 0) {
1470 // Note that we can't propagate undef elt info, because we don't know
1471 // which elt is getting updated.
1472 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1473 UndefElts2, Depth+1);
1474 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1475 break;
1476 }
1477
1478 // If this is inserting an element that isn't demanded, remove this
1479 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001480 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001481 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1482 return AddSoonDeadInstToWorklist(*I, 0);
1483
1484 // Otherwise, the element inserted overwrites whatever was there, so the
1485 // input demanded set is simpler than the output set.
1486 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1487 DemandedElts & ~(1ULL << IdxNo),
1488 UndefElts, Depth+1);
1489 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1490
1491 // The inserted element is defined.
1492 UndefElts |= 1ULL << IdxNo;
1493 break;
1494 }
1495
1496 case Instruction::And:
1497 case Instruction::Or:
1498 case Instruction::Xor:
1499 case Instruction::Add:
1500 case Instruction::Sub:
1501 case Instruction::Mul:
1502 // div/rem demand all inputs, because they don't want divide by zero.
1503 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1504 UndefElts, Depth+1);
1505 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1506 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1507 UndefElts2, Depth+1);
1508 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1509
1510 // Output elements are undefined if both are undefined. Consider things
1511 // like undef&0. The result is known zero, not undef.
1512 UndefElts &= UndefElts2;
1513 break;
1514
1515 case Instruction::Call: {
1516 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1517 if (!II) break;
1518 switch (II->getIntrinsicID()) {
1519 default: break;
1520
1521 // Binary vector operations that work column-wise. A dest element is a
1522 // function of the corresponding input elements from the two inputs.
1523 case Intrinsic::x86_sse_sub_ss:
1524 case Intrinsic::x86_sse_mul_ss:
1525 case Intrinsic::x86_sse_min_ss:
1526 case Intrinsic::x86_sse_max_ss:
1527 case Intrinsic::x86_sse2_sub_sd:
1528 case Intrinsic::x86_sse2_mul_sd:
1529 case Intrinsic::x86_sse2_min_sd:
1530 case Intrinsic::x86_sse2_max_sd:
1531 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1532 UndefElts, Depth+1);
1533 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1534 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1535 UndefElts2, Depth+1);
1536 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1537
1538 // If only the low elt is demanded and this is a scalarizable intrinsic,
1539 // scalarize it now.
1540 if (DemandedElts == 1) {
1541 switch (II->getIntrinsicID()) {
1542 default: break;
1543 case Intrinsic::x86_sse_sub_ss:
1544 case Intrinsic::x86_sse_mul_ss:
1545 case Intrinsic::x86_sse2_sub_sd:
1546 case Intrinsic::x86_sse2_mul_sd:
1547 // TODO: Lower MIN/MAX/ABS/etc
1548 Value *LHS = II->getOperand(1);
1549 Value *RHS = II->getOperand(2);
1550 // Extract the element as scalars.
1551 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1552 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1553
1554 switch (II->getIntrinsicID()) {
1555 default: assert(0 && "Case stmts out of sync!");
1556 case Intrinsic::x86_sse_sub_ss:
1557 case Intrinsic::x86_sse2_sub_sd:
1558 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1559 II->getName()), *II);
1560 break;
1561 case Intrinsic::x86_sse_mul_ss:
1562 case Intrinsic::x86_sse2_mul_sd:
1563 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1564 II->getName()), *II);
1565 break;
1566 }
1567
1568 Instruction *New =
1569 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1570 II->getName());
1571 InsertNewInstBefore(New, *II);
1572 AddSoonDeadInstToWorklist(*II, 0);
1573 return New;
1574 }
1575 }
1576
1577 // Output elements are undefined if both are undefined. Consider things
1578 // like undef&0. The result is known zero, not undef.
1579 UndefElts &= UndefElts2;
1580 break;
1581 }
1582 break;
1583 }
1584 }
1585 return MadeChange ? I : 0;
1586}
1587
Reid Spencer266e42b2006-12-23 06:05:41 +00001588/// @returns true if the specified compare instruction is
1589/// true when both operands are equal...
1590/// @brief Determine if the ICmpInst returns true if both operands are equal
1591static bool isTrueWhenEqual(ICmpInst &ICI) {
1592 ICmpInst::Predicate pred = ICI.getPredicate();
1593 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1594 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1595 pred == ICmpInst::ICMP_SLE;
1596}
1597
Chris Lattnerb8b97502003-08-13 19:01:45 +00001598/// AssociativeOpt - Perform an optimization on an associative operator. This
1599/// function is designed to check a chain of associative operators for a
1600/// potential to apply a certain optimization. Since the optimization may be
1601/// applicable if the expression was reassociated, this checks the chain, then
1602/// reassociates the expression as necessary to expose the optimization
1603/// opportunity. This makes use of a special Functor, which must define
1604/// 'shouldApply' and 'apply' methods.
1605///
1606template<typename Functor>
1607Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1608 unsigned Opcode = Root.getOpcode();
1609 Value *LHS = Root.getOperand(0);
1610
1611 // Quick check, see if the immediate LHS matches...
1612 if (F.shouldApply(LHS))
1613 return F.apply(Root);
1614
1615 // Otherwise, if the LHS is not of the same opcode as the root, return.
1616 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001617 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001618 // Should we apply this transform to the RHS?
1619 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1620
1621 // If not to the RHS, check to see if we should apply to the LHS...
1622 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1623 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1624 ShouldApply = true;
1625 }
1626
1627 // If the functor wants to apply the optimization to the RHS of LHSI,
1628 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1629 if (ShouldApply) {
1630 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001631
Chris Lattnerb8b97502003-08-13 19:01:45 +00001632 // Now all of the instructions are in the current basic block, go ahead
1633 // and perform the reassociation.
1634 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1635
1636 // First move the selected RHS to the LHS of the root...
1637 Root.setOperand(0, LHSI->getOperand(1));
1638
1639 // Make what used to be the LHS of the root be the user of the root...
1640 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001641 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001642 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1643 return 0;
1644 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001645 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001646 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001647 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1648 BasicBlock::iterator ARI = &Root; ++ARI;
1649 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1650 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001651
1652 // Now propagate the ExtraOperand down the chain of instructions until we
1653 // get to LHSI.
1654 while (TmpLHSI != LHSI) {
1655 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001656 // Move the instruction to immediately before the chain we are
1657 // constructing to avoid breaking dominance properties.
1658 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1659 BB->getInstList().insert(ARI, NextLHSI);
1660 ARI = NextLHSI;
1661
Chris Lattnerb8b97502003-08-13 19:01:45 +00001662 Value *NextOp = NextLHSI->getOperand(1);
1663 NextLHSI->setOperand(1, ExtraOperand);
1664 TmpLHSI = NextLHSI;
1665 ExtraOperand = NextOp;
1666 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001667
Chris Lattnerb8b97502003-08-13 19:01:45 +00001668 // Now that the instructions are reassociated, have the functor perform
1669 // the transformation...
1670 return F.apply(Root);
1671 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001672
Chris Lattnerb8b97502003-08-13 19:01:45 +00001673 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1674 }
1675 return 0;
1676}
1677
1678
1679// AddRHS - Implements: X + X --> X << 1
1680struct AddRHS {
1681 Value *RHS;
1682 AddRHS(Value *rhs) : RHS(rhs) {}
1683 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1684 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001685 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001686 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001687 }
1688};
1689
1690// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1691// iff C1&C2 == 0
1692struct AddMaskingAnd {
1693 Constant *C2;
1694 AddMaskingAnd(Constant *c) : C2(c) {}
1695 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001696 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001697 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001698 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001699 }
1700 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001701 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001702 }
1703};
1704
Chris Lattner86102b82005-01-01 16:22:27 +00001705static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001706 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001707 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001708 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001709 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001710
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001711 return IC->InsertNewInstBefore(CastInst::create(
1712 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001713 }
1714
Chris Lattner183b3362004-04-09 19:05:30 +00001715 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001716 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1717 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001718
Chris Lattner183b3362004-04-09 19:05:30 +00001719 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1720 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001721 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1722 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001723 }
1724
1725 Value *Op0 = SO, *Op1 = ConstOperand;
1726 if (!ConstIsRHS)
1727 std::swap(Op0, Op1);
1728 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001729 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1730 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001731 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1732 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1733 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001734 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001735 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001736 abort();
1737 }
Chris Lattner86102b82005-01-01 16:22:27 +00001738 return IC->InsertNewInstBefore(New, I);
1739}
1740
1741// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1742// constant as the other operand, try to fold the binary operator into the
1743// select arguments. This also works for Cast instructions, which obviously do
1744// not have a second operand.
1745static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1746 InstCombiner *IC) {
1747 // Don't modify shared select instructions
1748 if (!SI->hasOneUse()) return 0;
1749 Value *TV = SI->getOperand(1);
1750 Value *FV = SI->getOperand(2);
1751
1752 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001753 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001754 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001755
Chris Lattner86102b82005-01-01 16:22:27 +00001756 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1757 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1758
1759 return new SelectInst(SI->getCondition(), SelectTrueVal,
1760 SelectFalseVal);
1761 }
1762 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001763}
1764
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001765
1766/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1767/// node as operand #0, see if we can fold the instruction into the PHI (which
1768/// is only possible if all operands to the PHI are constants).
1769Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1770 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001771 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001772 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001773
Chris Lattner04689872006-09-09 22:02:56 +00001774 // Check to see if all of the operands of the PHI are constants. If there is
1775 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001776 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001777 BasicBlock *NonConstBB = 0;
1778 for (unsigned i = 0; i != NumPHIValues; ++i)
1779 if (!isa<Constant>(PN->getIncomingValue(i))) {
1780 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001781 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001782 NonConstBB = PN->getIncomingBlock(i);
1783
1784 // If the incoming non-constant value is in I's block, we have an infinite
1785 // loop.
1786 if (NonConstBB == I.getParent())
1787 return 0;
1788 }
1789
1790 // If there is exactly one non-constant value, we can insert a copy of the
1791 // operation in that block. However, if this is a critical edge, we would be
1792 // inserting the computation one some other paths (e.g. inside a loop). Only
1793 // do this if the pred block is unconditionally branching into the phi block.
1794 if (NonConstBB) {
1795 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1796 if (!BI || !BI->isUnconditional()) return 0;
1797 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001798
1799 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001800 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001801 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001802 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001803 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001804
1805 // Next, add all of the operands to the PHI.
1806 if (I.getNumOperands() == 2) {
1807 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001808 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001809 Value *InV;
1810 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001811 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1812 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1813 else
1814 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001815 } else {
1816 assert(PN->getIncomingBlock(i) == NonConstBB);
1817 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1818 InV = BinaryOperator::create(BO->getOpcode(),
1819 PN->getIncomingValue(i), C, "phitmp",
1820 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001821 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1822 InV = CmpInst::create(CI->getOpcode(),
1823 CI->getPredicate(),
1824 PN->getIncomingValue(i), C, "phitmp",
1825 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001826 else
1827 assert(0 && "Unknown binop!");
1828
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001829 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001830 }
1831 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001832 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001833 } else {
1834 CastInst *CI = cast<CastInst>(&I);
1835 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001836 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001837 Value *InV;
1838 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001839 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001840 } else {
1841 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001842 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1843 I.getType(), "phitmp",
1844 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001845 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001846 }
1847 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001848 }
1849 }
1850 return ReplaceInstUsesWith(I, NewPN);
1851}
1852
Chris Lattner113f4f42002-06-25 16:13:24 +00001853Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001854 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001855 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001856
Chris Lattnercf4a9962004-04-10 22:01:55 +00001857 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001858 // X + undef -> undef
1859 if (isa<UndefValue>(RHS))
1860 return ReplaceInstUsesWith(I, RHS);
1861
Chris Lattnercf4a9962004-04-10 22:01:55 +00001862 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001863 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001864 if (RHSC->isNullValue())
1865 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001866 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1867 if (CFP->isExactlyValue(-0.0))
1868 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001869 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001870
Chris Lattnercf4a9962004-04-10 22:01:55 +00001871 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001872 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001873 const APInt& Val = CI->getValue();
Reid Spencer959a21d2007-03-23 21:24:59 +00001874 unsigned BitWidth = Val.getBitWidth();
1875 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001876 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001877
1878 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1879 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001880 if (!isa<VectorType>(I.getType())) {
1881 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1882 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1883 KnownZero, KnownOne))
1884 return &I;
1885 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001886 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001887
1888 if (isa<PHINode>(LHS))
1889 if (Instruction *NV = FoldOpIntoPhi(I))
1890 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001891
Chris Lattner330628a2006-01-06 17:59:59 +00001892 ConstantInt *XorRHS = 0;
1893 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001894 if (isa<ConstantInt>(RHSC) &&
1895 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001896 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001897 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00001898
Reid Spencer959a21d2007-03-23 21:24:59 +00001899 unsigned Size = TySizeBits / 2;
1900 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1901 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001902 do {
1903 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001904 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1905 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001906 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1907 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001908 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00001909 if (!MaskedValueIsZero(XorLHS,
1910 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001911 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001912 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001913 }
1914 }
1915 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001916 C0080Val = APIntOps::lshr(C0080Val, Size);
1917 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1918 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001919
Reid Spencera5c18bf2007-03-28 01:36:16 +00001920 // FIXME: This shouldn't be necessary. When the backends can handle types
1921 // with funny bit widths then this whole cascade of if statements should
1922 // be removed. It is just here to get the size of the "middle" type back
1923 // up to something that the back ends can handle.
1924 const Type *MiddleType = 0;
1925 switch (Size) {
1926 default: break;
1927 case 32: MiddleType = Type::Int32Ty; break;
1928 case 16: MiddleType = Type::Int16Ty; break;
1929 case 8: MiddleType = Type::Int8Ty; break;
1930 }
1931 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001932 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001933 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001934 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001935 }
1936 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001937 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001938
Chris Lattnerb8b97502003-08-13 19:01:45 +00001939 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001940 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001941 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001942
1943 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1944 if (RHSI->getOpcode() == Instruction::Sub)
1945 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1946 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1947 }
1948 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1949 if (LHSI->getOpcode() == Instruction::Sub)
1950 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1951 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1952 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001953 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001954
Chris Lattner147e9752002-05-08 22:46:53 +00001955 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001956 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001957 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001958
1959 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001960 if (!isa<Constant>(RHS))
1961 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001962 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001963
Misha Brukmanb1c93172005-04-21 23:48:37 +00001964
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001965 ConstantInt *C2;
1966 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1967 if (X == RHS) // X*C + X --> X * (C+1)
1968 return BinaryOperator::createMul(RHS, AddOne(C2));
1969
1970 // X*C1 + X*C2 --> X * (C1+C2)
1971 ConstantInt *C1;
1972 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00001973 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001974 }
1975
1976 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001977 if (dyn_castFoldableMul(RHS, C2) == LHS)
1978 return BinaryOperator::createMul(LHS, AddOne(C2));
1979
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001980 // X + ~X --> -1 since ~X = -X-1
1981 if (dyn_castNotVal(LHS) == RHS ||
1982 dyn_castNotVal(RHS) == LHS)
1983 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1984
Chris Lattner57c8d992003-02-18 19:57:07 +00001985
Chris Lattnerb8b97502003-08-13 19:01:45 +00001986 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001987 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001988 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1989 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001990
Chris Lattnerb9cde762003-10-02 15:11:26 +00001991 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001992 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00001993 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1994 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00001995
Chris Lattnerbff91d92004-10-08 05:07:56 +00001996 // (X & FF00) + xx00 -> (X+xx00) & FF00
1997 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00001998 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00001999 if (Anded == CRHS) {
2000 // See if all bits from the first bit set in the Add RHS up are included
2001 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002002 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002003
2004 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002005 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002006
2007 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002008 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002009
Chris Lattnerbff91d92004-10-08 05:07:56 +00002010 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2011 // Okay, the xform is safe. Insert the new add pronto.
2012 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2013 LHS->getName()), I);
2014 return BinaryOperator::createAnd(NewAdd, C2);
2015 }
2016 }
2017 }
2018
Chris Lattnerd4252a72004-07-30 07:50:03 +00002019 // Try to fold constant add into select arguments.
2020 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002021 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002022 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002023 }
2024
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002025 // add (cast *A to intptrtype) B ->
2026 // cast (GEP (cast *A to sbyte*) B) ->
2027 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002028 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002029 CastInst *CI = dyn_cast<CastInst>(LHS);
2030 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002031 if (!CI) {
2032 CI = dyn_cast<CastInst>(RHS);
2033 Other = LHS;
2034 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002035 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002036 (CI->getType()->getPrimitiveSizeInBits() ==
2037 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002038 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002039 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002040 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002041 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002042 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002043 }
2044 }
2045
Chris Lattner113f4f42002-06-25 16:13:24 +00002046 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002047}
2048
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002049// isSignBit - Return true if the value represented by the constant only has the
2050// highest order bit set.
2051static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002052 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002053 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002054}
2055
Chris Lattner113f4f42002-06-25 16:13:24 +00002056Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002058
Chris Lattnere6794492002-08-12 21:17:25 +00002059 if (Op0 == Op1) // sub X, X -> 0
2060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002061
Chris Lattnere6794492002-08-12 21:17:25 +00002062 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002063 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002064 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002065
Chris Lattner81a7a232004-10-16 18:11:37 +00002066 if (isa<UndefValue>(Op0))
2067 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2068 if (isa<UndefValue>(Op1))
2069 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2070
Chris Lattner8f2f5982003-11-05 01:06:05 +00002071 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2072 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002073 if (C->isAllOnesValue())
2074 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002075
Chris Lattner8f2f5982003-11-05 01:06:05 +00002076 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002077 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002078 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002079 return BinaryOperator::createAdd(X, AddOne(C));
2080
Chris Lattner27df1db2007-01-15 07:02:54 +00002081 // -(X >>u 31) -> (X >>s 31)
2082 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002083 if (C->isZero()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002084 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002085 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002086 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002087 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002088 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002089 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002090 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002091 return BinaryOperator::create(Instruction::AShr,
2092 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002093 }
2094 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002095 }
2096 else if (SI->getOpcode() == Instruction::AShr) {
2097 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2098 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002099 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002100 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002101 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002102 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002103 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002104 }
2105 }
2106 }
Chris Lattner022167f2004-03-13 00:11:49 +00002107 }
Chris Lattner183b3362004-04-09 19:05:30 +00002108
2109 // Try to fold constant sub into select arguments.
2110 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002111 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002112 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002113
2114 if (isa<PHINode>(Op0))
2115 if (Instruction *NV = FoldOpIntoPhi(I))
2116 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002117 }
2118
Chris Lattnera9be4492005-04-07 16:15:25 +00002119 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2120 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002121 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002122 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002123 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002124 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002125 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002126 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2127 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2128 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002129 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002130 Op1I->getOperand(0));
2131 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002132 }
2133
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002134 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002135 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2136 // is not used by anyone else...
2137 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002138 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002139 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002140 // Swap the two operands of the subexpr...
2141 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2142 Op1I->setOperand(0, IIOp1);
2143 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002144
Chris Lattner3082c5a2003-02-18 19:28:33 +00002145 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002146 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002147 }
2148
2149 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2150 //
2151 if (Op1I->getOpcode() == Instruction::And &&
2152 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2153 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2154
Chris Lattner396dbfe2004-06-09 05:08:07 +00002155 Value *NewNot =
2156 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002157 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002158 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002159
Reid Spencer3c514952006-10-16 23:08:08 +00002160 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002161 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002162 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002163 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002164 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002165 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002166 ConstantExpr::getNeg(DivRHS));
2167
Chris Lattner57c8d992003-02-18 19:57:07 +00002168 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002169 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002170 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002171 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002172 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002173 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002174 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002175 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002176
Chris Lattner7a002fe2006-12-02 00:13:08 +00002177 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002178 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2179 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002180 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2181 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2182 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2183 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002184 } else if (Op0I->getOpcode() == Instruction::Sub) {
2185 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2186 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002187 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002188
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002189 ConstantInt *C1;
2190 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002191 if (X == Op1) // X*C - X --> X * (C-1)
2192 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002193
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002194 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2195 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002196 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002197 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002198 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002199}
2200
Reid Spencer266e42b2006-12-23 06:05:41 +00002201/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002202/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002203static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2204 switch (pred) {
2205 case ICmpInst::ICMP_SLT:
2206 // True if LHS s< RHS and RHS == 0
2207 return RHS->isNullValue();
2208 case ICmpInst::ICMP_SLE:
2209 // True if LHS s<= RHS and RHS == -1
2210 return RHS->isAllOnesValue();
2211 case ICmpInst::ICMP_UGE:
2212 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002213 return RHS->getValue() ==
2214 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002215 case ICmpInst::ICMP_UGT:
2216 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002217 return RHS->getValue() ==
2218 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002219 default:
2220 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002221 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002222}
2223
Chris Lattner113f4f42002-06-25 16:13:24 +00002224Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002225 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002226 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002227
Chris Lattner81a7a232004-10-16 18:11:37 +00002228 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2229 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2230
Chris Lattnere6794492002-08-12 21:17:25 +00002231 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002232 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2233 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002234
2235 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002236 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002237 if (SI->getOpcode() == Instruction::Shl)
2238 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002239 return BinaryOperator::createMul(SI->getOperand(0),
2240 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002241
Chris Lattnercce81be2003-09-11 22:24:54 +00002242 if (CI->isNullValue())
2243 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2244 if (CI->equalsInt(1)) // X * 1 == X
2245 return ReplaceInstUsesWith(I, Op0);
2246 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002247 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002248
Zhou Sheng4961cf12007-03-29 01:57:21 +00002249 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002250 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002251 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002252 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002253 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002254 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002255 if (Op1F->isNullValue())
2256 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002257
Chris Lattner3082c5a2003-02-18 19:28:33 +00002258 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2259 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2260 if (Op1F->getValue() == 1.0)
2261 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2262 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002263
2264 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2265 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2266 isa<ConstantInt>(Op0I->getOperand(1))) {
2267 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2268 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2269 Op1, "tmp");
2270 InsertNewInstBefore(Add, I);
2271 Value *C1C2 = ConstantExpr::getMul(Op1,
2272 cast<Constant>(Op0I->getOperand(1)));
2273 return BinaryOperator::createAdd(Add, C1C2);
2274
2275 }
Chris Lattner183b3362004-04-09 19:05:30 +00002276
2277 // Try to fold constant mul into select arguments.
2278 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002279 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002280 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002281
2282 if (isa<PHINode>(Op0))
2283 if (Instruction *NV = FoldOpIntoPhi(I))
2284 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002285 }
2286
Chris Lattner934a64cf2003-03-10 23:23:04 +00002287 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2288 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002289 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002290
Chris Lattner2635b522004-02-23 05:39:21 +00002291 // If one of the operands of the multiply is a cast from a boolean value, then
2292 // we know the bool is either zero or one, so this is a 'masking' multiply.
2293 // See if we can simplify things based on how the boolean was originally
2294 // formed.
2295 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002296 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002297 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002298 BoolCast = CI;
2299 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002300 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002301 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002302 BoolCast = CI;
2303 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002304 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002305 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2306 const Type *SCOpTy = SCIOp0->getType();
2307
Reid Spencer266e42b2006-12-23 06:05:41 +00002308 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002309 // multiply into a shift/and combination.
2310 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002311 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002312 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002313 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002314 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002315 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002316 InsertNewInstBefore(
2317 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002318 BoolCast->getOperand(0)->getName()+
2319 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002320
2321 // If the multiply type is not the same as the source type, sign extend
2322 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002323 if (I.getType() != V->getType()) {
2324 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2325 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2326 Instruction::CastOps opcode =
2327 (SrcBits == DstBits ? Instruction::BitCast :
2328 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2329 V = InsertCastBefore(opcode, V, I.getType(), I);
2330 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002331
Chris Lattner2635b522004-02-23 05:39:21 +00002332 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002333 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002334 }
2335 }
2336 }
2337
Chris Lattner113f4f42002-06-25 16:13:24 +00002338 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002339}
2340
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002341/// This function implements the transforms on div instructions that work
2342/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2343/// used by the visitors to those instructions.
2344/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002345Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002346 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002347
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002348 // undef / X -> 0
2349 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002351
2352 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002353 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002354 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002355
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002356 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002357 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2358 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002359 // same basic block, then we replace the select with Y, and the condition
2360 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002361 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002362 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002363 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2364 if (ST->isNullValue()) {
2365 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2366 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002367 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002368 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2369 I.setOperand(1, SI->getOperand(2));
2370 else
2371 UpdateValueUsesWith(SI, SI->getOperand(2));
2372 return &I;
2373 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002374
Chris Lattnerd79dc792006-09-09 20:26:32 +00002375 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2376 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2377 if (ST->isNullValue()) {
2378 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2379 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002380 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002381 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2382 I.setOperand(1, SI->getOperand(1));
2383 else
2384 UpdateValueUsesWith(SI, SI->getOperand(1));
2385 return &I;
2386 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002387 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002388
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002389 return 0;
2390}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002391
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002392/// This function implements the transforms common to both integer division
2393/// instructions (udiv and sdiv). It is called by the visitors to those integer
2394/// division instructions.
2395/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002396Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002397 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2398
2399 if (Instruction *Common = commonDivTransforms(I))
2400 return Common;
2401
2402 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2403 // div X, 1 == X
2404 if (RHS->equalsInt(1))
2405 return ReplaceInstUsesWith(I, Op0);
2406
2407 // (X / C1) / C2 -> X / (C1*C2)
2408 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2409 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2410 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2411 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002412 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002413 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002414
Reid Spencer6d392062007-03-23 20:05:17 +00002415 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2417 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2418 return R;
2419 if (isa<PHINode>(Op0))
2420 if (Instruction *NV = FoldOpIntoPhi(I))
2421 return NV;
2422 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002423 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002424
Chris Lattner3082c5a2003-02-18 19:28:33 +00002425 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002426 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002427 if (LHS->equalsInt(0))
2428 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2429
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002430 return 0;
2431}
2432
2433Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2435
2436 // Handle the integer div common cases
2437 if (Instruction *Common = commonIDivTransforms(I))
2438 return Common;
2439
2440 // X udiv C^2 -> X >> C
2441 // Check to see if this is an unsigned division with an exact power of 2,
2442 // if so, convert to a right shift.
2443 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002444 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002445 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002446 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002447 }
2448
2449 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002450 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002451 if (RHSI->getOpcode() == Instruction::Shl &&
2452 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002453 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002454 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002455 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002456 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002457 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002458 Constant *C2V = ConstantInt::get(NTy, C2);
2459 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002460 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002461 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002462 }
2463 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002464 }
2465
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002466 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2467 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002468 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002469 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002470 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002471 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002472 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002473 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002474 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002475 // Construct the "on true" case of the select
2476 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2477 Instruction *TSI = BinaryOperator::createLShr(
2478 Op0, TC, SI->getName()+".t");
2479 TSI = InsertNewInstBefore(TSI, I);
2480
2481 // Construct the "on false" case of the select
2482 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2483 Instruction *FSI = BinaryOperator::createLShr(
2484 Op0, FC, SI->getName()+".f");
2485 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002486
Reid Spencer3939b1a2007-03-05 23:36:13 +00002487 // construct the select instruction and return it.
2488 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002489 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002490 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002491 return 0;
2492}
2493
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002494Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2495 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2496
2497 // Handle the integer div common cases
2498 if (Instruction *Common = commonIDivTransforms(I))
2499 return Common;
2500
2501 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2502 // sdiv X, -1 == -X
2503 if (RHS->isAllOnesValue())
2504 return BinaryOperator::createNeg(Op0);
2505
2506 // -X/C -> X/-C
2507 if (Value *LHSNeg = dyn_castNegVal(Op0))
2508 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2509 }
2510
2511 // If the sign bits of both operands are zero (i.e. we can prove they are
2512 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002513 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002514 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002515 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2516 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2517 }
2518 }
2519
2520 return 0;
2521}
2522
2523Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2524 return commonDivTransforms(I);
2525}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002526
Chris Lattner85dda9a2006-03-02 06:50:58 +00002527/// GetFactor - If we can prove that the specified value is at least a multiple
2528/// of some factor, return that factor.
2529static Constant *GetFactor(Value *V) {
2530 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2531 return CI;
2532
2533 // Unless we can be tricky, we know this is a multiple of 1.
2534 Constant *Result = ConstantInt::get(V->getType(), 1);
2535
2536 Instruction *I = dyn_cast<Instruction>(V);
2537 if (!I) return Result;
2538
2539 if (I->getOpcode() == Instruction::Mul) {
2540 // Handle multiplies by a constant, etc.
2541 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2542 GetFactor(I->getOperand(1)));
2543 } else if (I->getOpcode() == Instruction::Shl) {
2544 // (X<<C) -> X * (1 << C)
2545 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2546 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2547 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2548 }
2549 } else if (I->getOpcode() == Instruction::And) {
2550 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2551 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002552 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002553 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2554 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002555 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002556 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002557 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002558 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002559 if (!CI->isIntegerCast())
2560 return Result;
2561 Value *Op = CI->getOperand(0);
2562 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002563 }
2564 return Result;
2565}
2566
Reid Spencer7eb55b32006-11-02 01:53:59 +00002567/// This function implements the transforms on rem instructions that work
2568/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2569/// is used by the visitors to those instructions.
2570/// @brief Transforms common to all three rem instructions
2571Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002572 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002573
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002574 // 0 % X == 0, we don't need to preserve faults!
2575 if (Constant *LHS = dyn_cast<Constant>(Op0))
2576 if (LHS->isNullValue())
2577 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2578
2579 if (isa<UndefValue>(Op0)) // undef % X -> 0
2580 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2581 if (isa<UndefValue>(Op1))
2582 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002583
2584 // Handle cases involving: rem X, (select Cond, Y, Z)
2585 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2586 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2587 // the same basic block, then we replace the select with Y, and the
2588 // condition of the select with false (if the cond value is in the same
2589 // BB). If the select has uses other than the div, this allows them to be
2590 // simplified also.
2591 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2592 if (ST->isNullValue()) {
2593 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2594 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002595 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002596 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2597 I.setOperand(1, SI->getOperand(2));
2598 else
2599 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002600 return &I;
2601 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002602 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2603 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2604 if (ST->isNullValue()) {
2605 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2606 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002607 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002608 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2609 I.setOperand(1, SI->getOperand(1));
2610 else
2611 UpdateValueUsesWith(SI, SI->getOperand(1));
2612 return &I;
2613 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002614 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002615
Reid Spencer7eb55b32006-11-02 01:53:59 +00002616 return 0;
2617}
2618
2619/// This function implements the transforms common to both integer remainder
2620/// instructions (urem and srem). It is called by the visitors to those integer
2621/// remainder instructions.
2622/// @brief Common integer remainder transforms
2623Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2624 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2625
2626 if (Instruction *common = commonRemTransforms(I))
2627 return common;
2628
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002629 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002630 // X % 0 == undef, we don't need to preserve faults!
2631 if (RHS->equalsInt(0))
2632 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2633
Chris Lattner3082c5a2003-02-18 19:28:33 +00002634 if (RHS->equalsInt(1)) // X % 1 == 0
2635 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2636
Chris Lattnerb70f1412006-02-28 05:49:21 +00002637 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2638 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2639 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2640 return R;
2641 } else if (isa<PHINode>(Op0I)) {
2642 if (Instruction *NV = FoldOpIntoPhi(I))
2643 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002644 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002645 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2646 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002647 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002648 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002649 }
2650
Reid Spencer7eb55b32006-11-02 01:53:59 +00002651 return 0;
2652}
2653
2654Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2655 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2656
2657 if (Instruction *common = commonIRemTransforms(I))
2658 return common;
2659
2660 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2661 // X urem C^2 -> X and C
2662 // Check to see if this is an unsigned remainder with an exact power of 2,
2663 // if so, convert to a bitwise and.
2664 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002665 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002666 return BinaryOperator::createAnd(Op0, SubOne(C));
2667 }
2668
Chris Lattner2e90b732006-02-05 07:54:04 +00002669 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002670 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2671 if (RHSI->getOpcode() == Instruction::Shl &&
2672 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002673 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002674 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2675 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2676 "tmp"), I);
2677 return BinaryOperator::createAnd(Op0, Add);
2678 }
2679 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002680 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002681
Reid Spencer7eb55b32006-11-02 01:53:59 +00002682 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2683 // where C1&C2 are powers of two.
2684 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2685 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2686 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2687 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002688 if ((STO->getValue().isPowerOf2()) &&
2689 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002690 Value *TrueAnd = InsertNewInstBefore(
2691 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2692 Value *FalseAnd = InsertNewInstBefore(
2693 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2694 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2695 }
2696 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002697 }
2698
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002699 return 0;
2700}
2701
Reid Spencer7eb55b32006-11-02 01:53:59 +00002702Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2703 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2704
2705 if (Instruction *common = commonIRemTransforms(I))
2706 return common;
2707
2708 if (Value *RHSNeg = dyn_castNegVal(Op1))
2709 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002710 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002711 // X % -Y -> X % Y
2712 AddUsesToWorkList(I);
2713 I.setOperand(1, RHSNeg);
2714 return &I;
2715 }
2716
2717 // If the top bits of both operands are zero (i.e. we can prove they are
2718 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002719 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002720 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2721 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2722 return BinaryOperator::createURem(Op0, Op1, I.getName());
2723 }
2724
2725 return 0;
2726}
2727
2728Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002729 return commonRemTransforms(I);
2730}
2731
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002732// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002733static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002734 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002735 if (isSigned) {
2736 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002737 APInt Val(APInt::getSignedMaxValue(TypeBits));
2738 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002739 }
Reid Spenceref599b02007-03-19 21:10:28 +00002740 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002741}
2742
2743// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002744static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2745 if (isSigned) {
2746 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002747 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2748 APInt Val(APInt::getSignedMinValue(TypeBits));
2749 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002750 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002751 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002752}
2753
Chris Lattner35167c32004-06-09 07:59:58 +00002754// isOneBitSet - Return true if there is exactly one bit set in the specified
2755// constant.
2756static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002757 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002758}
2759
Chris Lattner8fc5af42004-09-23 21:46:38 +00002760// isHighOnes - Return true if the constant is of the form 1+0+.
2761// This is the same as lowones(~X).
2762static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002763 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002764}
2765
Reid Spencer266e42b2006-12-23 06:05:41 +00002766/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002767/// are carefully arranged to allow folding of expressions such as:
2768///
2769/// (A < B) | (A > B) --> (A != B)
2770///
Reid Spencer266e42b2006-12-23 06:05:41 +00002771/// Note that this is only valid if the first and second predicates have the
2772/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002773///
Reid Spencer266e42b2006-12-23 06:05:41 +00002774/// Three bits are used to represent the condition, as follows:
2775/// 0 A > B
2776/// 1 A == B
2777/// 2 A < B
2778///
2779/// <=> Value Definition
2780/// 000 0 Always false
2781/// 001 1 A > B
2782/// 010 2 A == B
2783/// 011 3 A >= B
2784/// 100 4 A < B
2785/// 101 5 A != B
2786/// 110 6 A <= B
2787/// 111 7 Always true
2788///
2789static unsigned getICmpCode(const ICmpInst *ICI) {
2790 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002792 case ICmpInst::ICMP_UGT: return 1; // 001
2793 case ICmpInst::ICMP_SGT: return 1; // 001
2794 case ICmpInst::ICMP_EQ: return 2; // 010
2795 case ICmpInst::ICMP_UGE: return 3; // 011
2796 case ICmpInst::ICMP_SGE: return 3; // 011
2797 case ICmpInst::ICMP_ULT: return 4; // 100
2798 case ICmpInst::ICMP_SLT: return 4; // 100
2799 case ICmpInst::ICMP_NE: return 5; // 101
2800 case ICmpInst::ICMP_ULE: return 6; // 110
2801 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002802 // True -> 7
2803 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002804 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002805 return 0;
2806 }
2807}
2808
Reid Spencer266e42b2006-12-23 06:05:41 +00002809/// getICmpValue - This is the complement of getICmpCode, which turns an
2810/// opcode and two operands into either a constant true or false, or a brand
2811/// new /// ICmp instruction. The sign is passed in to determine which kind
2812/// of predicate to use in new icmp instructions.
2813static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2814 switch (code) {
2815 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002816 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002817 case 1:
2818 if (sign)
2819 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2820 else
2821 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2822 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2823 case 3:
2824 if (sign)
2825 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2826 else
2827 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2828 case 4:
2829 if (sign)
2830 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2831 else
2832 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2833 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2834 case 6:
2835 if (sign)
2836 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2837 else
2838 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002839 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002840 }
2841}
2842
Reid Spencer266e42b2006-12-23 06:05:41 +00002843static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2844 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2845 (ICmpInst::isSignedPredicate(p1) &&
2846 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2847 (ICmpInst::isSignedPredicate(p2) &&
2848 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2849}
2850
2851namespace {
2852// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2853struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002854 InstCombiner &IC;
2855 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002856 ICmpInst::Predicate pred;
2857 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2858 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2859 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002860 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002861 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2862 if (PredicatesFoldable(pred, ICI->getPredicate()))
2863 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2864 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002865 return false;
2866 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002867 Instruction *apply(Instruction &Log) const {
2868 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2869 if (ICI->getOperand(0) != LHS) {
2870 assert(ICI->getOperand(1) == LHS);
2871 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002872 }
2873
Chris Lattnerd1bce952007-03-13 14:27:42 +00002874 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002875 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002876 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002877 unsigned Code;
2878 switch (Log.getOpcode()) {
2879 case Instruction::And: Code = LHSCode & RHSCode; break;
2880 case Instruction::Or: Code = LHSCode | RHSCode; break;
2881 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002882 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002883 }
2884
Chris Lattnerd1bce952007-03-13 14:27:42 +00002885 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2886 ICmpInst::isSignedPredicate(ICI->getPredicate());
2887
2888 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002889 if (Instruction *I = dyn_cast<Instruction>(RV))
2890 return I;
2891 // Otherwise, it's a constant boolean value...
2892 return IC.ReplaceInstUsesWith(Log, RV);
2893 }
2894};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002895} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002896
Chris Lattnerba1cb382003-09-19 17:17:26 +00002897// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2898// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002899// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002900Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002901 ConstantInt *OpRHS,
2902 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002903 BinaryOperator &TheAnd) {
2904 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002905 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002906 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002907 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002908
Chris Lattnerba1cb382003-09-19 17:17:26 +00002909 switch (Op->getOpcode()) {
2910 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002911 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002912 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002913 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002914 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002915 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002916 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002917 }
2918 break;
2919 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002920 if (Together == AndRHS) // (X | C) & C --> C
2921 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002922
Chris Lattner86102b82005-01-01 16:22:27 +00002923 if (Op->hasOneUse() && Together != OpRHS) {
2924 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002925 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002926 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002927 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002928 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002929 }
2930 break;
2931 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002932 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002933 // Adding a one to a single bit bit-field should be turned into an XOR
2934 // of the bit. First thing to check is to see if this AND is with a
2935 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002936 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002937
2938 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002939 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002940 // Ok, at this point, we know that we are masking the result of the
2941 // ADD down to exactly one bit. If the constant we are adding has
2942 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002943 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002944
Chris Lattnerba1cb382003-09-19 17:17:26 +00002945 // Check to see if any bits below the one bit set in AndRHSV are set.
2946 if ((AddRHS & (AndRHSV-1)) == 0) {
2947 // If not, the only thing that can effect the output of the AND is
2948 // the bit specified by AndRHSV. If that bit is set, the effect of
2949 // the XOR is to toggle the bit. If it is clear, then the ADD has
2950 // no effect.
2951 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2952 TheAnd.setOperand(0, X);
2953 return &TheAnd;
2954 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002955 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002956 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002957 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002958 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002959 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002960 }
2961 }
2962 }
2963 }
2964 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002965
2966 case Instruction::Shl: {
2967 // We know that the AND will not produce any of the bits shifted in, so if
2968 // the anded constant includes them, clear them now!
2969 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00002970 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00002971 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00002972 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
2973 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002974
Zhou Shengb3a80b12007-03-29 08:15:12 +00002975 if (CI->getValue() == ShlMask) {
2976 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00002977 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2978 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002979 TheAnd.setOperand(1, CI);
2980 return &TheAnd;
2981 }
2982 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002983 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002984 case Instruction::LShr:
2985 {
Chris Lattner2da29172003-09-19 19:05:02 +00002986 // We know that the AND will not produce any of the bits shifted in, so if
2987 // the anded constant includes them, clear them now! This only applies to
2988 // unsigned shifts, because a signed shr may bring in set bits!
2989 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00002990 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00002991 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00002992 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
2993 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002994
Zhou Shengb3a80b12007-03-29 08:15:12 +00002995 if (CI->getValue() == ShrMask) {
2996 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00002997 return ReplaceInstUsesWith(TheAnd, Op);
2998 } else if (CI != AndRHS) {
2999 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3000 return &TheAnd;
3001 }
3002 break;
3003 }
3004 case Instruction::AShr:
3005 // Signed shr.
3006 // See if this is shifting in some sign extension, then masking it out
3007 // with an and.
3008 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003009 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003010 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003011 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3012 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003013 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003014 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003015 // Make the argument unsigned.
3016 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003017 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003018 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003019 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003020 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003021 }
Chris Lattner2da29172003-09-19 19:05:02 +00003022 }
3023 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003024 }
3025 return 0;
3026}
3027
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003028
Chris Lattner6862fbd2004-09-29 17:40:11 +00003029/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3030/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003031/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3032/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003033/// insert new instructions.
3034Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003035 bool isSigned, bool Inside,
3036 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003037 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003038 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003039 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003040
Chris Lattner6862fbd2004-09-29 17:40:11 +00003041 if (Inside) {
3042 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003043 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003044
Reid Spencer266e42b2006-12-23 06:05:41 +00003045 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003046 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003047 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003048 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3049 return new ICmpInst(pred, V, Hi);
3050 }
3051
3052 // Emit V-Lo <u Hi-Lo
3053 Constant *NegLo = ConstantExpr::getNeg(Lo);
3054 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003055 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003056 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3057 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003058 }
3059
3060 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003061 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003062
Reid Spencerf4071162007-03-21 23:19:50 +00003063 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003064 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003065 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003066 ICmpInst::Predicate pred = (isSigned ?
3067 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3068 return new ICmpInst(pred, V, Hi);
3069 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003070
Reid Spencerf4071162007-03-21 23:19:50 +00003071 // Emit V-Lo >u Hi-1-Lo
3072 // Note that Hi has already had one subtracted from it, above.
3073 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003074 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003075 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003076 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3077 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003078}
3079
Chris Lattnerb4b25302005-09-18 07:22:02 +00003080// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3081// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3082// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3083// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003084static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003085 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003086 uint32_t BitWidth = Val->getType()->getBitWidth();
3087 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003088
3089 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003090 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003091 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003092 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003093 return true;
3094}
3095
Chris Lattnerb4b25302005-09-18 07:22:02 +00003096/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3097/// where isSub determines whether the operator is a sub. If we can fold one of
3098/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003099///
3100/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3101/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3102/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3103///
3104/// return (A +/- B).
3105///
3106Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003107 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003108 Instruction &I) {
3109 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3110 if (!LHSI || LHSI->getNumOperands() != 2 ||
3111 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3112
3113 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3114
3115 switch (LHSI->getOpcode()) {
3116 default: return 0;
3117 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003118 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003119 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003120 if ((Mask->getValue().countLeadingZeros() +
3121 Mask->getValue().countPopulation()) ==
3122 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003123 break;
3124
3125 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3126 // part, we don't need any explicit masks to take them out of A. If that
3127 // is all N is, ignore it.
Reid Spencer755d0e72007-03-26 17:44:01 +00003128 unsigned MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003129 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003130 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003131 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003132 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003133 break;
3134 }
3135 }
Chris Lattneraf517572005-09-18 04:24:45 +00003136 return 0;
3137 case Instruction::Or:
3138 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003139 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003140 if ((Mask->getValue().countLeadingZeros() +
3141 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003142 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003143 break;
3144 return 0;
3145 }
3146
3147 Instruction *New;
3148 if (isSub)
3149 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3150 else
3151 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3152 return InsertNewInstBefore(New, I);
3153}
3154
Chris Lattner113f4f42002-06-25 16:13:24 +00003155Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003156 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003158
Chris Lattner81a7a232004-10-16 18:11:37 +00003159 if (isa<UndefValue>(Op1)) // X & undef -> 0
3160 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3161
Chris Lattner86102b82005-01-01 16:22:27 +00003162 // and X, X = X
3163 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003164 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003165
Chris Lattner5b2edb12006-02-12 08:02:11 +00003166 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003167 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003168 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003169 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3170 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3171 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003172 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003173 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003174 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003175 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003176 if (CP->isAllOnesValue())
3177 return ReplaceInstUsesWith(I, I.getOperand(0));
3178 }
3179 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003180
Zhou Sheng75b871f2007-01-11 12:24:14 +00003181 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003182 const APInt& AndRHSMask = AndRHS->getValue();
3183 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003184
Chris Lattnerba1cb382003-09-19 17:17:26 +00003185 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003186 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003187 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003188 Value *Op0LHS = Op0I->getOperand(0);
3189 Value *Op0RHS = Op0I->getOperand(1);
3190 switch (Op0I->getOpcode()) {
3191 case Instruction::Xor:
3192 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003193 // If the mask is only needed on one incoming arm, push it up.
3194 if (Op0I->hasOneUse()) {
3195 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3196 // Not masking anything out for the LHS, move to RHS.
3197 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3198 Op0RHS->getName()+".masked");
3199 InsertNewInstBefore(NewRHS, I);
3200 return BinaryOperator::create(
3201 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003202 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003203 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003204 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3205 // Not masking anything out for the RHS, move to LHS.
3206 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3207 Op0LHS->getName()+".masked");
3208 InsertNewInstBefore(NewLHS, I);
3209 return BinaryOperator::create(
3210 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3211 }
3212 }
3213
Chris Lattner86102b82005-01-01 16:22:27 +00003214 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003215 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003216 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3217 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3218 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3219 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3220 return BinaryOperator::createAnd(V, AndRHS);
3221 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3222 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003223 break;
3224
3225 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003226 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3227 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3228 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3229 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3230 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003231 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003232 }
3233
Chris Lattner16464b32003-07-23 19:25:52 +00003234 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003235 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003236 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003237 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003238 // If this is an integer truncation or change from signed-to-unsigned, and
3239 // if the source is an and/or with immediate, transform it. This
3240 // frequently occurs for bitfield accesses.
3241 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003242 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003243 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003244 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003245 if (CastOp->getOpcode() == Instruction::And) {
3246 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003247 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3248 // This will fold the two constants together, which may allow
3249 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003250 Instruction *NewCast = CastInst::createTruncOrBitCast(
3251 CastOp->getOperand(0), I.getType(),
3252 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003253 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003254 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003255 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003256 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003257 return BinaryOperator::createAnd(NewCast, C3);
3258 } else if (CastOp->getOpcode() == Instruction::Or) {
3259 // Change: and (cast (or X, C1) to T), C2
3260 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003261 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003262 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3263 return ReplaceInstUsesWith(I, AndRHS);
3264 }
3265 }
Chris Lattner33217db2003-07-23 19:36:21 +00003266 }
Chris Lattner183b3362004-04-09 19:05:30 +00003267
3268 // Try to fold constant and into select arguments.
3269 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003271 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003272 if (isa<PHINode>(Op0))
3273 if (Instruction *NV = FoldOpIntoPhi(I))
3274 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003275 }
3276
Chris Lattnerbb74e222003-03-10 23:06:50 +00003277 Value *Op0NotVal = dyn_castNotVal(Op0);
3278 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003279
Chris Lattner023a4832004-06-18 06:07:51 +00003280 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3281 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3282
Misha Brukman9c003d82004-07-30 12:50:08 +00003283 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003284 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003285 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3286 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003287 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003288 return BinaryOperator::createNot(Or);
3289 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003290
3291 {
3292 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003293 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3294 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3295 return ReplaceInstUsesWith(I, Op1);
3296 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3297 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3298 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003299
3300 if (Op0->hasOneUse() &&
3301 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3302 if (A == Op1) { // (A^B)&A -> A&(A^B)
3303 I.swapOperands(); // Simplify below
3304 std::swap(Op0, Op1);
3305 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3306 cast<BinaryOperator>(Op0)->swapOperands();
3307 I.swapOperands(); // Simplify below
3308 std::swap(Op0, Op1);
3309 }
3310 }
3311 if (Op1->hasOneUse() &&
3312 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3313 if (B == Op0) { // B&(A^B) -> B&(B^A)
3314 cast<BinaryOperator>(Op1)->swapOperands();
3315 std::swap(A, B);
3316 }
3317 if (A == Op0) { // A&(A^B) -> A & ~B
3318 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3319 InsertNewInstBefore(NotB, I);
3320 return BinaryOperator::createAnd(A, NotB);
3321 }
3322 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003323 }
3324
Reid Spencer266e42b2006-12-23 06:05:41 +00003325 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3326 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3327 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003328 return R;
3329
Chris Lattner623826c2004-09-28 21:48:02 +00003330 Value *LHSVal, *RHSVal;
3331 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003332 ICmpInst::Predicate LHSCC, RHSCC;
3333 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3334 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3335 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3336 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3337 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3338 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3339 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3340 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003341 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003342 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3343 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3344 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3345 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003346 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003347 std::swap(LHS, RHS);
3348 std::swap(LHSCst, RHSCst);
3349 std::swap(LHSCC, RHSCC);
3350 }
3351
Reid Spencer266e42b2006-12-23 06:05:41 +00003352 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003353 // comparing a value against two constants and and'ing the result
3354 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003355 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3356 // (from the FoldICmpLogical check above), that the two constants
3357 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003358 assert(LHSCst != RHSCst && "Compares not folded above?");
3359
3360 switch (LHSCC) {
3361 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003362 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003363 switch (RHSCC) {
3364 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003365 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3366 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3367 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003368 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003369 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3370 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3371 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003372 return ReplaceInstUsesWith(I, LHS);
3373 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003374 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003375 switch (RHSCC) {
3376 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003377 case ICmpInst::ICMP_ULT:
3378 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3379 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3380 break; // (X != 13 & X u< 15) -> no change
3381 case ICmpInst::ICMP_SLT:
3382 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3383 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3384 break; // (X != 13 & X s< 15) -> no change
3385 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3386 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3387 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003388 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003389 case ICmpInst::ICMP_NE:
3390 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003391 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3392 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3393 LHSVal->getName()+".off");
3394 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003395 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3396 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003397 }
3398 break; // (X != 13 & X != 15) -> no change
3399 }
3400 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003401 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003402 switch (RHSCC) {
3403 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003404 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3405 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003406 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003407 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3408 break;
3409 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3410 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003411 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003412 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3413 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003414 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003415 break;
3416 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003417 switch (RHSCC) {
3418 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003419 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3420 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003421 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003422 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3423 break;
3424 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3425 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003426 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003427 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3428 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003429 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003430 break;
3431 case ICmpInst::ICMP_UGT:
3432 switch (RHSCC) {
3433 default: assert(0 && "Unknown integer condition code!");
3434 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3435 return ReplaceInstUsesWith(I, LHS);
3436 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3437 return ReplaceInstUsesWith(I, RHS);
3438 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3439 break;
3440 case ICmpInst::ICMP_NE:
3441 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3442 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3443 break; // (X u> 13 & X != 15) -> no change
3444 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3445 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3446 true, I);
3447 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3448 break;
3449 }
3450 break;
3451 case ICmpInst::ICMP_SGT:
3452 switch (RHSCC) {
3453 default: assert(0 && "Unknown integer condition code!");
3454 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3455 return ReplaceInstUsesWith(I, LHS);
3456 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3457 return ReplaceInstUsesWith(I, RHS);
3458 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3459 break;
3460 case ICmpInst::ICMP_NE:
3461 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3462 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3463 break; // (X s> 13 & X != 15) -> no change
3464 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3465 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3466 true, I);
3467 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3468 break;
3469 }
3470 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003471 }
3472 }
3473 }
3474
Chris Lattner3af10532006-05-05 06:39:07 +00003475 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003476 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3477 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3478 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3479 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003480 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003481 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003482 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3483 I.getType(), TD) &&
3484 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3485 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003486 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3487 Op1C->getOperand(0),
3488 I.getName());
3489 InsertNewInstBefore(NewOp, I);
3490 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3491 }
Chris Lattner3af10532006-05-05 06:39:07 +00003492 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003493
3494 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003495 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3496 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3497 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003498 SI0->getOperand(1) == SI1->getOperand(1) &&
3499 (SI0->hasOneUse() || SI1->hasOneUse())) {
3500 Instruction *NewOp =
3501 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3502 SI1->getOperand(0),
3503 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003504 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3505 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003506 }
Chris Lattner3af10532006-05-05 06:39:07 +00003507 }
3508
Chris Lattner113f4f42002-06-25 16:13:24 +00003509 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003510}
3511
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003512/// CollectBSwapParts - Look to see if the specified value defines a single byte
3513/// in the result. If it does, and if the specified byte hasn't been filled in
3514/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003515static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003516 Instruction *I = dyn_cast<Instruction>(V);
3517 if (I == 0) return true;
3518
3519 // If this is an or instruction, it is an inner node of the bswap.
3520 if (I->getOpcode() == Instruction::Or)
3521 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3522 CollectBSwapParts(I->getOperand(1), ByteValues);
3523
Zhou Shengb25806f2007-03-30 09:29:48 +00003524 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003525 // If this is a shift by a constant int, and it is "24", then its operand
3526 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003527 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003528 // Not shifting the entire input by N-1 bytes?
Zhou Shengb25806f2007-03-30 09:29:48 +00003529 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003530 8*(ByteValues.size()-1))
3531 return true;
3532
3533 unsigned DestNo;
3534 if (I->getOpcode() == Instruction::Shl) {
3535 // X << 24 defines the top byte with the lowest of the input bytes.
3536 DestNo = ByteValues.size()-1;
3537 } else {
3538 // X >>u 24 defines the low byte with the highest of the input bytes.
3539 DestNo = 0;
3540 }
3541
3542 // If the destination byte value is already defined, the values are or'd
3543 // together, which isn't a bswap (unless it's an or of the same bits).
3544 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3545 return true;
3546 ByteValues[DestNo] = I->getOperand(0);
3547 return false;
3548 }
3549
3550 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3551 // don't have this.
3552 Value *Shift = 0, *ShiftLHS = 0;
3553 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3554 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3555 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3556 return true;
3557 Instruction *SI = cast<Instruction>(Shift);
3558
3559 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Shengb25806f2007-03-30 09:29:48 +00003560 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3561 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003562 return true;
3563
3564 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3565 unsigned DestByte;
Zhou Shengb25806f2007-03-30 09:29:48 +00003566 if (AndAmt->getValue().getActiveBits() > 64)
3567 return true;
3568 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003569 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Shengb25806f2007-03-30 09:29:48 +00003570 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003571 break;
3572 // Unknown mask for bswap.
3573 if (DestByte == ByteValues.size()) return true;
3574
Reid Spencere0fc4df2006-10-20 07:07:24 +00003575 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003576 unsigned SrcByte;
3577 if (SI->getOpcode() == Instruction::Shl)
3578 SrcByte = DestByte - ShiftBytes;
3579 else
3580 SrcByte = DestByte + ShiftBytes;
3581
3582 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3583 if (SrcByte != ByteValues.size()-DestByte-1)
3584 return true;
3585
3586 // If the destination byte value is already defined, the values are or'd
3587 // together, which isn't a bswap (unless it's an or of the same bits).
3588 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3589 return true;
3590 ByteValues[DestByte] = SI->getOperand(0);
3591 return false;
3592}
3593
3594/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3595/// If so, insert the new bswap intrinsic and return it.
3596Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003597 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3598 if (!ITy || ITy->getBitWidth() % 16)
3599 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003600
3601 /// ByteValues - For each byte of the result, we keep track of which value
3602 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003603 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003604 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003605
3606 // Try to find all the pieces corresponding to the bswap.
3607 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3608 CollectBSwapParts(I.getOperand(1), ByteValues))
3609 return 0;
3610
3611 // Check to see if all of the bytes come from the same value.
3612 Value *V = ByteValues[0];
3613 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3614
3615 // Check to make sure that all of the bytes come from the same value.
3616 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3617 if (ByteValues[i] != V)
3618 return 0;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003619 const Type *Tys[] = { ITy, ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003620 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003621 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003622 return new CallInst(F, V);
3623}
3624
3625
Chris Lattner113f4f42002-06-25 16:13:24 +00003626Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003627 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003628 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003629
Chris Lattner3a8248f2007-03-24 23:56:43 +00003630 if (isa<UndefValue>(Op1)) // X | undef -> -1
3631 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003632
Chris Lattner5b2edb12006-02-12 08:02:11 +00003633 // or X, X = X
3634 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003635 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003636
Chris Lattner5b2edb12006-02-12 08:02:11 +00003637 // See if we can simplify any instructions used by the instruction whose sole
3638 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003639 if (!isa<VectorType>(I.getType())) {
3640 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3641 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3642 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3643 KnownZero, KnownOne))
3644 return &I;
3645 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003646
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003647 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003648 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003649 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003650 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3651 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003652 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003653 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003654 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003655 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3656 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003657
Chris Lattnerd4252a72004-07-30 07:50:03 +00003658 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3659 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003660 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003661 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003662 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003663 return BinaryOperator::createXor(Or,
3664 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003665 }
Chris Lattner183b3362004-04-09 19:05:30 +00003666
3667 // Try to fold constant and into select arguments.
3668 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003669 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003670 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003671 if (isa<PHINode>(Op0))
3672 if (Instruction *NV = FoldOpIntoPhi(I))
3673 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003674 }
3675
Chris Lattner330628a2006-01-06 17:59:59 +00003676 Value *A = 0, *B = 0;
3677 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003678
3679 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3680 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3681 return ReplaceInstUsesWith(I, Op1);
3682 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3683 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3684 return ReplaceInstUsesWith(I, Op0);
3685
Chris Lattnerb7845d62006-07-10 20:25:24 +00003686 // (A | B) | C and A | (B | C) -> bswap if possible.
3687 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003688 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003689 match(Op1, m_Or(m_Value(), m_Value())) ||
3690 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3691 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003692 if (Instruction *BSwap = MatchBSwap(I))
3693 return BSwap;
3694 }
3695
Chris Lattnerb62f5082005-05-09 04:58:36 +00003696 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3697 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003698 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003699 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3700 InsertNewInstBefore(NOr, I);
3701 NOr->takeName(Op0);
3702 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003703 }
3704
3705 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3706 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003707 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003708 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3709 InsertNewInstBefore(NOr, I);
3710 NOr->takeName(Op0);
3711 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003712 }
3713
Chris Lattner15212982005-09-18 03:42:07 +00003714 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003715 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003716 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3717
3718 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3719 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3720
3721
Chris Lattner01f56c62005-09-18 06:02:59 +00003722 // If we have: ((V + N) & C1) | (V & C2)
3723 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3724 // replace with V+N.
3725 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003726 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003727 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003728 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3729 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003730 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003731 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003732 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003733 return ReplaceInstUsesWith(I, A);
3734 }
3735 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003736 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003737 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3738 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003739 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003740 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003741 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003742 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003743 }
3744 }
3745 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003746
3747 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003748 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3749 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3750 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003751 SI0->getOperand(1) == SI1->getOperand(1) &&
3752 (SI0->hasOneUse() || SI1->hasOneUse())) {
3753 Instruction *NewOp =
3754 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3755 SI1->getOperand(0),
3756 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003757 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3758 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003759 }
3760 }
Chris Lattner812aab72003-08-12 19:11:07 +00003761
Chris Lattnerd4252a72004-07-30 07:50:03 +00003762 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3763 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003764 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003765 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003766 } else {
3767 A = 0;
3768 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003769 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003770 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3771 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003772 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003773 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003774
Misha Brukman9c003d82004-07-30 12:50:08 +00003775 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003776 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3777 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3778 I.getName()+".demorgan"), I);
3779 return BinaryOperator::createNot(And);
3780 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003781 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003782
Reid Spencer266e42b2006-12-23 06:05:41 +00003783 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3784 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3785 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003786 return R;
3787
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003788 Value *LHSVal, *RHSVal;
3789 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 ICmpInst::Predicate LHSCC, RHSCC;
3791 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3792 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3793 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3794 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3795 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3796 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3797 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3798 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003799 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003800 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3801 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3802 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3803 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003804 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003805 std::swap(LHS, RHS);
3806 std::swap(LHSCst, RHSCst);
3807 std::swap(LHSCC, RHSCC);
3808 }
3809
Reid Spencer266e42b2006-12-23 06:05:41 +00003810 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003811 // comparing a value against two constants and or'ing the result
3812 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003813 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3814 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003815 // equal.
3816 assert(LHSCst != RHSCst && "Compares not folded above?");
3817
3818 switch (LHSCC) {
3819 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003820 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003821 switch (RHSCC) {
3822 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003823 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003824 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3825 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3826 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3827 LHSVal->getName()+".off");
3828 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003829 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003830 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003831 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003832 break; // (X == 13 | X == 15) -> no change
3833 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3834 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003835 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003836 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3837 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3838 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003839 return ReplaceInstUsesWith(I, RHS);
3840 }
3841 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003842 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003843 switch (RHSCC) {
3844 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003845 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3846 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3847 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003848 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003849 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3850 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3851 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003852 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003853 }
3854 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003855 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003856 switch (RHSCC) {
3857 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003858 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003859 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003860 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3861 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3862 false, I);
3863 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3864 break;
3865 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3866 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003867 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003868 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3869 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003870 }
3871 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003872 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003873 switch (RHSCC) {
3874 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003875 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3876 break;
3877 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3878 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3879 false, I);
3880 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3881 break;
3882 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3883 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3884 return ReplaceInstUsesWith(I, RHS);
3885 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3886 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003887 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003888 break;
3889 case ICmpInst::ICMP_UGT:
3890 switch (RHSCC) {
3891 default: assert(0 && "Unknown integer condition code!");
3892 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3893 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3894 return ReplaceInstUsesWith(I, LHS);
3895 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3896 break;
3897 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3898 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003899 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003900 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3901 break;
3902 }
3903 break;
3904 case ICmpInst::ICMP_SGT:
3905 switch (RHSCC) {
3906 default: assert(0 && "Unknown integer condition code!");
3907 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3908 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3909 return ReplaceInstUsesWith(I, LHS);
3910 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3911 break;
3912 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3913 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003914 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003915 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3916 break;
3917 }
3918 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003919 }
3920 }
3921 }
Chris Lattner3af10532006-05-05 06:39:07 +00003922
3923 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003924 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003925 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003926 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3927 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003928 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003929 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003930 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3931 I.getType(), TD) &&
3932 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3933 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003934 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3935 Op1C->getOperand(0),
3936 I.getName());
3937 InsertNewInstBefore(NewOp, I);
3938 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3939 }
Chris Lattner3af10532006-05-05 06:39:07 +00003940 }
Chris Lattner3af10532006-05-05 06:39:07 +00003941
Chris Lattner15212982005-09-18 03:42:07 +00003942
Chris Lattner113f4f42002-06-25 16:13:24 +00003943 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003944}
3945
Chris Lattnerc2076352004-02-16 01:20:27 +00003946// XorSelf - Implements: X ^ X --> 0
3947struct XorSelf {
3948 Value *RHS;
3949 XorSelf(Value *rhs) : RHS(rhs) {}
3950 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3951 Instruction *apply(BinaryOperator &Xor) const {
3952 return &Xor;
3953 }
3954};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003955
3956
Chris Lattner113f4f42002-06-25 16:13:24 +00003957Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003958 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003960
Chris Lattner81a7a232004-10-16 18:11:37 +00003961 if (isa<UndefValue>(Op1))
3962 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3963
Chris Lattnerc2076352004-02-16 01:20:27 +00003964 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3965 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3966 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003967 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003968 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003969
3970 // See if we can simplify any instructions used by the instruction whose sole
3971 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003972 if (!isa<VectorType>(I.getType())) {
3973 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3974 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3975 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3976 KnownZero, KnownOne))
3977 return &I;
3978 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003979
Zhou Sheng75b871f2007-01-11 12:24:14 +00003980 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003981 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3982 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003983 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003984 return new ICmpInst(ICI->getInversePredicate(),
3985 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003986
Reid Spencer266e42b2006-12-23 06:05:41 +00003987 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003988 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003989 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3990 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003991 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3992 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003993 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003994 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003995 }
Chris Lattner023a4832004-06-18 06:07:51 +00003996
3997 // ~(~X & Y) --> (X | ~Y)
3998 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3999 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4000 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4001 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004002 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004003 Op0I->getOperand(1)->getName()+".not");
4004 InsertNewInstBefore(NotY, I);
4005 return BinaryOperator::createOr(Op0NotVal, NotY);
4006 }
4007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004008
Chris Lattner97638592003-07-23 21:37:07 +00004009 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004010 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004011 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004012 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004013 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4014 return BinaryOperator::createSub(
4015 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004016 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004017 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004018 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004019 } else if (Op0I->getOpcode() == Instruction::Or) {
4020 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004021 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004022 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4023 // Anything in both C1 and C2 is known to be zero, remove it from
4024 // NewRHS.
4025 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4026 NewRHS = ConstantExpr::getAnd(NewRHS,
4027 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004028 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004029 I.setOperand(0, Op0I->getOperand(0));
4030 I.setOperand(1, NewRHS);
4031 return &I;
4032 }
Chris Lattner97638592003-07-23 21:37:07 +00004033 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004034 }
Chris Lattner183b3362004-04-09 19:05:30 +00004035
4036 // Try to fold constant and into select arguments.
4037 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004038 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004039 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004040 if (isa<PHINode>(Op0))
4041 if (Instruction *NV = FoldOpIntoPhi(I))
4042 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004043 }
4044
Chris Lattnerbb74e222003-03-10 23:06:50 +00004045 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004046 if (X == Op1)
4047 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004048 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004049
Chris Lattnerbb74e222003-03-10 23:06:50 +00004050 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004051 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004052 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004053
Chris Lattner07418422007-03-18 22:51:34 +00004054
4055 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4056 if (Op1I) {
4057 Value *A, *B;
4058 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4059 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004060 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004061 I.swapOperands();
4062 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004063 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004064 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004065 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004066 }
Chris Lattner07418422007-03-18 22:51:34 +00004067 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4068 if (Op0 == A) // A^(A^B) == B
4069 return ReplaceInstUsesWith(I, B);
4070 else if (Op0 == B) // A^(B^A) == B
4071 return ReplaceInstUsesWith(I, A);
4072 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004073 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004074 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004075 std::swap(A, B);
4076 }
Chris Lattner07418422007-03-18 22:51:34 +00004077 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004078 I.swapOperands(); // Simplified below.
4079 std::swap(Op0, Op1);
4080 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004081 }
Chris Lattner07418422007-03-18 22:51:34 +00004082 }
4083
4084 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4085 if (Op0I) {
4086 Value *A, *B;
4087 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4088 if (A == Op1) // (B|A)^B == (A|B)^B
4089 std::swap(A, B);
4090 if (B == Op1) { // (A|B)^B == A & ~B
4091 Instruction *NotB =
4092 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4093 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004094 }
Chris Lattner07418422007-03-18 22:51:34 +00004095 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4096 if (Op1 == A) // (A^B)^A == B
4097 return ReplaceInstUsesWith(I, B);
4098 else if (Op1 == B) // (B^A)^A == B
4099 return ReplaceInstUsesWith(I, A);
4100 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4101 if (A == Op1) // (A&B)^A -> (B&A)^A
4102 std::swap(A, B);
4103 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004104 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004105 Instruction *N =
4106 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004107 return BinaryOperator::createAnd(N, Op1);
4108 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004109 }
Chris Lattner07418422007-03-18 22:51:34 +00004110 }
4111
4112 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4113 if (Op0I && Op1I && Op0I->isShift() &&
4114 Op0I->getOpcode() == Op1I->getOpcode() &&
4115 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4116 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4117 Instruction *NewOp =
4118 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4119 Op1I->getOperand(0),
4120 Op0I->getName()), I);
4121 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4122 Op1I->getOperand(1));
4123 }
4124
4125 if (Op0I && Op1I) {
4126 Value *A, *B, *C, *D;
4127 // (A & B)^(A | B) -> A ^ B
4128 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4129 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4130 if ((A == C && B == D) || (A == D && B == C))
4131 return BinaryOperator::createXor(A, B);
4132 }
4133 // (A | B)^(A & B) -> A ^ B
4134 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4135 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4136 if ((A == C && B == D) || (A == D && B == C))
4137 return BinaryOperator::createXor(A, B);
4138 }
4139
4140 // (A & B)^(C & D)
4141 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4142 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4143 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4144 // (X & Y)^(X & Y) -> (Y^Z) & X
4145 Value *X = 0, *Y = 0, *Z = 0;
4146 if (A == C)
4147 X = A, Y = B, Z = D;
4148 else if (A == D)
4149 X = A, Y = B, Z = C;
4150 else if (B == C)
4151 X = B, Y = A, Z = D;
4152 else if (B == D)
4153 X = B, Y = A, Z = C;
4154
4155 if (X) {
4156 Instruction *NewOp =
4157 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4158 return BinaryOperator::createAnd(NewOp, X);
4159 }
4160 }
4161 }
4162
Reid Spencer266e42b2006-12-23 06:05:41 +00004163 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4164 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4165 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004166 return R;
4167
Chris Lattner3af10532006-05-05 06:39:07 +00004168 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004169 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004170 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004171 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4172 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004173 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004174 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004175 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4176 I.getType(), TD) &&
4177 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4178 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004179 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4180 Op1C->getOperand(0),
4181 I.getName());
4182 InsertNewInstBefore(NewOp, I);
4183 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4184 }
Chris Lattner3af10532006-05-05 06:39:07 +00004185 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004186
Chris Lattner113f4f42002-06-25 16:13:24 +00004187 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004188}
4189
Chris Lattner6862fbd2004-09-29 17:40:11 +00004190/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4191/// overflowed for this type.
4192static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004193 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004194 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4195
Reid Spencerf4071162007-03-21 23:19:50 +00004196 if (IsSigned)
4197 if (In2->getValue().isNegative())
4198 return Result->getValue().sgt(In1->getValue());
4199 else
4200 return Result->getValue().slt(In1->getValue());
4201 else
4202 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004203}
4204
Chris Lattner0798af32005-01-13 20:14:25 +00004205/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4206/// code necessary to compute the offset from the base pointer (without adding
4207/// in the base pointer). Return the result as a signed integer of intptr size.
4208static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4209 TargetData &TD = IC.getTargetData();
4210 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004211 const Type *IntPtrTy = TD.getIntPtrType();
4212 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004213
4214 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004215 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004216
Chris Lattner0798af32005-01-13 20:14:25 +00004217 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4218 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004219 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004220 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004221 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4222 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004223 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004224 Scale = ConstantExpr::getMul(OpC, Scale);
4225 if (Constant *RC = dyn_cast<Constant>(Result))
4226 Result = ConstantExpr::getAdd(RC, Scale);
4227 else {
4228 // Emit an add instruction.
4229 Result = IC.InsertNewInstBefore(
4230 BinaryOperator::createAdd(Result, Scale,
4231 GEP->getName()+".offs"), I);
4232 }
4233 }
4234 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004235 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004236 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004237 Op->getName()+".c"), I);
4238 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004239 // We'll let instcombine(mul) convert this to a shl if possible.
4240 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4241 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004242
4243 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004244 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004245 GEP->getName()+".offs"), I);
4246 }
4247 }
4248 return Result;
4249}
4250
Reid Spencer266e42b2006-12-23 06:05:41 +00004251/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004252/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004253Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4254 ICmpInst::Predicate Cond,
4255 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004256 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004257
4258 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4259 if (isa<PointerType>(CI->getOperand(0)->getType()))
4260 RHS = CI->getOperand(0);
4261
Chris Lattner0798af32005-01-13 20:14:25 +00004262 Value *PtrBase = GEPLHS->getOperand(0);
4263 if (PtrBase == RHS) {
4264 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004265 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4266 // each index is zero or not.
4267 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004268 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004269 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4270 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004271 bool EmitIt = true;
4272 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4273 if (isa<UndefValue>(C)) // undef index -> undef.
4274 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4275 if (C->isNullValue())
4276 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004277 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4278 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004279 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004280 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004281 ConstantInt::get(Type::Int1Ty,
4282 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004283 }
4284
4285 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004286 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004287 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004288 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4289 if (InVal == 0)
4290 InVal = Comp;
4291 else {
4292 InVal = InsertNewInstBefore(InVal, I);
4293 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004294 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004295 InVal = BinaryOperator::createOr(InVal, Comp);
4296 else // True if all are equal
4297 InVal = BinaryOperator::createAnd(InVal, Comp);
4298 }
4299 }
4300 }
4301
4302 if (InVal)
4303 return InVal;
4304 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004305 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004306 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4307 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004308 }
Chris Lattner0798af32005-01-13 20:14:25 +00004309
Reid Spencer266e42b2006-12-23 06:05:41 +00004310 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004311 // the result to fold to a constant!
4312 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4313 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4314 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004315 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4316 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004317 }
4318 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004319 // If the base pointers are different, but the indices are the same, just
4320 // compare the base pointer.
4321 if (PtrBase != GEPRHS->getOperand(0)) {
4322 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004323 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004324 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004325 if (IndicesTheSame)
4326 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4327 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4328 IndicesTheSame = false;
4329 break;
4330 }
4331
4332 // If all indices are the same, just compare the base pointers.
4333 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004334 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4335 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004336
4337 // Otherwise, the base pointers are different and the indices are
4338 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004339 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004340 }
Chris Lattner0798af32005-01-13 20:14:25 +00004341
Chris Lattner81e84172005-01-13 22:25:21 +00004342 // If one of the GEPs has all zero indices, recurse.
4343 bool AllZeros = true;
4344 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4345 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4346 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4347 AllZeros = false;
4348 break;
4349 }
4350 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004351 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4352 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004353
4354 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004355 AllZeros = true;
4356 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4357 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4358 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4359 AllZeros = false;
4360 break;
4361 }
4362 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004363 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004364
Chris Lattner4fa89822005-01-14 00:20:05 +00004365 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4366 // If the GEPs only differ by one index, compare it.
4367 unsigned NumDifferences = 0; // Keep track of # differences.
4368 unsigned DiffOperand = 0; // The operand that differs.
4369 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4370 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004371 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4372 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004373 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004374 NumDifferences = 2;
4375 break;
4376 } else {
4377 if (NumDifferences++) break;
4378 DiffOperand = i;
4379 }
4380 }
4381
4382 if (NumDifferences == 0) // SAME GEP?
4383 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004384 ConstantInt::get(Type::Int1Ty,
4385 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004386 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004387 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4388 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004389 // Make sure we do a signed comparison here.
4390 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004391 }
4392 }
4393
Reid Spencer266e42b2006-12-23 06:05:41 +00004394 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004395 // the result to fold to a constant!
4396 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4397 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4398 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4399 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4400 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004401 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004402 }
4403 }
4404 return 0;
4405}
4406
Reid Spencer266e42b2006-12-23 06:05:41 +00004407Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4408 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004410
Chris Lattner6ee923f2007-01-14 19:42:17 +00004411 // Fold trivial predicates.
4412 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4413 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4414 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4415 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4416
4417 // Simplify 'fcmp pred X, X'
4418 if (Op0 == Op1) {
4419 switch (I.getPredicate()) {
4420 default: assert(0 && "Unknown predicate!");
4421 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4422 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4423 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4424 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4425 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4426 case FCmpInst::FCMP_OLT: // True if ordered and less than
4427 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4428 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4429
4430 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4431 case FCmpInst::FCMP_ULT: // True if unordered or less than
4432 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4433 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4434 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4435 I.setPredicate(FCmpInst::FCMP_UNO);
4436 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4437 return &I;
4438
4439 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4440 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4441 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4442 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4443 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4444 I.setPredicate(FCmpInst::FCMP_ORD);
4445 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4446 return &I;
4447 }
4448 }
4449
Reid Spencer266e42b2006-12-23 06:05:41 +00004450 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004451 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004452
Reid Spencer266e42b2006-12-23 06:05:41 +00004453 // Handle fcmp with constant RHS
4454 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4455 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4456 switch (LHSI->getOpcode()) {
4457 case Instruction::PHI:
4458 if (Instruction *NV = FoldOpIntoPhi(I))
4459 return NV;
4460 break;
4461 case Instruction::Select:
4462 // If either operand of the select is a constant, we can fold the
4463 // comparison into the select arms, which will cause one to be
4464 // constant folded and the select turned into a bitwise or.
4465 Value *Op1 = 0, *Op2 = 0;
4466 if (LHSI->hasOneUse()) {
4467 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4468 // Fold the known value into the constant operand.
4469 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4470 // Insert a new FCmp of the other select operand.
4471 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4472 LHSI->getOperand(2), RHSC,
4473 I.getName()), I);
4474 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4475 // Fold the known value into the constant operand.
4476 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4477 // Insert a new FCmp of the other select operand.
4478 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4479 LHSI->getOperand(1), RHSC,
4480 I.getName()), I);
4481 }
4482 }
4483
4484 if (Op1)
4485 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4486 break;
4487 }
4488 }
4489
4490 return Changed ? &I : 0;
4491}
4492
4493Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4494 bool Changed = SimplifyCompare(I);
4495 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4496 const Type *Ty = Op0->getType();
4497
4498 // icmp X, X
4499 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004500 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4501 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004502
4503 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004504 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004505
4506 // icmp of GlobalValues can never equal each other as long as they aren't
4507 // external weak linkage type.
4508 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4509 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4510 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004511 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4512 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004513
4514 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004515 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004516 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4517 isa<ConstantPointerNull>(Op0)) &&
4518 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004519 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004520 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4521 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004522
Reid Spencer266e42b2006-12-23 06:05:41 +00004523 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004524 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004525 switch (I.getPredicate()) {
4526 default: assert(0 && "Invalid icmp instruction!");
4527 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004528 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004529 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004530 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004531 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004532 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004533 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004534
Reid Spencer266e42b2006-12-23 06:05:41 +00004535 case ICmpInst::ICMP_UGT:
4536 case ICmpInst::ICMP_SGT:
4537 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004538 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004539 case ICmpInst::ICMP_ULT:
4540 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004541 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4542 InsertNewInstBefore(Not, I);
4543 return BinaryOperator::createAnd(Not, Op1);
4544 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004545 case ICmpInst::ICMP_UGE:
4546 case ICmpInst::ICMP_SGE:
4547 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004548 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004549 case ICmpInst::ICMP_ULE:
4550 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004551 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4552 InsertNewInstBefore(Not, I);
4553 return BinaryOperator::createOr(Not, Op1);
4554 }
4555 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004556 }
4557
Chris Lattner2dd01742004-06-09 04:24:29 +00004558 // See if we are doing a comparison between a constant and an instruction that
4559 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004560 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004561 switch (I.getPredicate()) {
4562 default: break;
4563 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4564 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004565 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004566 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4567 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4568 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4569 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4570 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004571
Reid Spencer266e42b2006-12-23 06:05:41 +00004572 case ICmpInst::ICMP_SLT:
4573 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004574 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004575 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4576 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4577 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4578 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4579 break;
4580
4581 case ICmpInst::ICMP_UGT:
4582 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004583 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004584 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4585 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4586 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4587 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4588 break;
4589
4590 case ICmpInst::ICMP_SGT:
4591 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004592 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004593 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4594 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4595 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4596 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4597 break;
4598
4599 case ICmpInst::ICMP_ULE:
4600 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004601 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004602 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4603 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4604 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4605 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4606 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004607
Reid Spencer266e42b2006-12-23 06:05:41 +00004608 case ICmpInst::ICMP_SLE:
4609 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004610 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004611 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4612 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4613 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4614 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4615 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004616
Reid Spencer266e42b2006-12-23 06:05:41 +00004617 case ICmpInst::ICMP_UGE:
4618 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004619 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004620 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4621 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4622 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4623 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4624 break;
4625
4626 case ICmpInst::ICMP_SGE:
4627 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004628 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004629 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4630 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4631 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4632 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4633 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004634 }
4635
Reid Spencer266e42b2006-12-23 06:05:41 +00004636 // If we still have a icmp le or icmp ge instruction, turn it into the
4637 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004638 // already been handled above, this requires little checking.
4639 //
Reid Spencer624766f2007-03-25 19:55:33 +00004640 switch (I.getPredicate()) {
4641 default: break;
4642 case ICmpInst::ICMP_ULE:
4643 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4644 case ICmpInst::ICMP_SLE:
4645 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4646 case ICmpInst::ICMP_UGE:
4647 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4648 case ICmpInst::ICMP_SGE:
4649 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4650 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004651
4652 // See if we can fold the comparison based on bits known to be zero or one
4653 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004654 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4655 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4656 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004657 KnownZero, KnownOne, 0))
4658 return &I;
4659
4660 // Given the known and unknown bits, compute a range that the LHS could be
4661 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004662 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004663 // Compute the Min, Max and RHS values based on the known bits. For the
4664 // EQ and NE we use unsigned values.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00004665 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4666 const APInt& RHSVal = CI->getValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00004667 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004668 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4669 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004670 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004671 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4672 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004673 }
4674 switch (I.getPredicate()) { // LE/GE have been folded already.
4675 default: assert(0 && "Unknown icmp opcode!");
4676 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004677 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004678 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004679 break;
4680 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004681 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004682 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004683 break;
4684 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004685 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004686 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004687 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004688 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004689 break;
4690 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004691 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004692 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004693 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004694 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004695 break;
4696 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004697 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004698 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004699 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004700 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004701 break;
4702 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004703 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004704 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004705 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004706 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004707 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004708 }
4709 }
4710
Reid Spencer266e42b2006-12-23 06:05:41 +00004711 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004712 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004713 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004714 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004715 switch (LHSI->getOpcode()) {
4716 case Instruction::And:
4717 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4718 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004719 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4720
Reid Spencer266e42b2006-12-23 06:05:41 +00004721 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004722 // and/compare to be the input width without changing the value
4723 // produced, eliminating a cast.
4724 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4725 // We can do this transformation if either the AND constant does not
4726 // have its sign bit set or if it is an equality comparison.
4727 // Extending a relational comparison when we're checking the sign
4728 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004729 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004730 (I.isEquality() || AndCST->getValue().isPositive() &&
4731 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004732 ConstantInt *NewCST;
4733 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004734 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4735 uint32_t BitWidth = cast<IntegerType>(
4736 Cast->getOperand(0)->getType())->getBitWidth();
4737 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4738 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00004739 Instruction *NewAnd =
4740 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4741 LHSI->getName());
4742 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004743 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004744 }
4745 }
4746
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004747 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4748 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4749 // happens a LOT in code produced by the C front-end, for bitfield
4750 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004751 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4752 if (Shift && !Shift->isShift())
4753 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004754
Reid Spencere0fc4df2006-10-20 07:07:24 +00004755 ConstantInt *ShAmt;
4756 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004757 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4758 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004759
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004760 // We can fold this as long as we can't shift unknown bits
4761 // into the mask. This can only happen with signed shift
4762 // rights, as they sign-extend.
4763 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004764 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004765 if (!CanFold) {
4766 // To test for the bad case of the signed shr, see if any
4767 // of the bits shifted in could be tested after the mask.
Zhou Shengfd28a332007-03-30 17:20:39 +00004768 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
4769 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004770
Zhou Shengb3a80b12007-03-29 08:15:12 +00004771 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
4772 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
4773 AndCST->getValue()) == 0)
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004774 CanFold = true;
4775 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004776
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004777 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004778 Constant *NewCst;
4779 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004780 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004781 else
4782 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004783
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004784 // Check to see if we are shifting out any of the bits being
4785 // compared.
4786 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4787 // If we shifted bits out, the fold is not going to work out.
4788 // As a special case, check to see if this means that the
4789 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004790 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004791 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004792 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004793 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004794 } else {
4795 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004796 Constant *NewAndCST;
4797 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004798 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004799 else
4800 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4801 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004802 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004803 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004804 AddUsesToWorkList(I);
4805 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004806 }
4807 }
Chris Lattner35167c32004-06-09 07:59:58 +00004808 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004809
4810 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4811 // preferable because it allows the C<<Y expression to be hoisted out
4812 // of a loop if Y is invariant and X is not.
4813 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004814 I.isEquality() && !Shift->isArithmeticShift() &&
4815 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004816 // Compute C << Y.
4817 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004818 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004819 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004820 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004821 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004822 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004823 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004824 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004825 }
4826 InsertNewInstBefore(cast<Instruction>(NS), I);
4827
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004828 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004829 Instruction *NewAnd = BinaryOperator::createAnd(
4830 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004831 InsertNewInstBefore(NewAnd, I);
4832
4833 I.setOperand(0, NewAnd);
4834 return &I;
4835 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004836 }
4837 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004838
Reid Spencer266e42b2006-12-23 06:05:41 +00004839 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004840 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004841 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004842 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4843
4844 // Check that the shift amount is in range. If not, don't perform
4845 // undefined shifts. When the shift is visited it will be
4846 // simplified.
Zhou Shengb25806f2007-03-30 09:29:48 +00004847 if (ShAmt->uge(TypeBits))
Chris Lattner19b57f52005-06-15 20:53:31 +00004848 break;
4849
Chris Lattner272d5ca2004-09-28 18:22:15 +00004850 // If we are comparing against bits always shifted out, the
4851 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004852 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004853 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004854 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004855 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004856 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004857 return ReplaceInstUsesWith(I, Cst);
4858 }
4859
4860 if (LHSI->hasOneUse()) {
4861 // Otherwise strength reduce the shift into an and.
Zhou Shengfd28a332007-03-30 17:20:39 +00004862 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Reid Spencer52830322007-03-25 21:11:44 +00004863 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4864 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004865
Chris Lattner272d5ca2004-09-28 18:22:15 +00004866 Instruction *AndI =
4867 BinaryOperator::createAnd(LHSI->getOperand(0),
4868 Mask, LHSI->getName()+".mask");
4869 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004871 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004872 }
4873 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004874 }
4875 break;
4876
Reid Spencer266e42b2006-12-23 06:05:41 +00004877 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004878 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004879 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004880 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004881 // Check that the shift amount is in range. If not, don't perform
4882 // undefined shifts. When the shift is visited it will be
4883 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004884 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Zhou Shengb25806f2007-03-30 09:29:48 +00004885 if (ShAmt->uge(TypeBits))
Chris Lattner19b57f52005-06-15 20:53:31 +00004886 break;
4887
Chris Lattner1023b872004-09-27 16:18:50 +00004888 // If we are comparing against bits always shifted out, the
4889 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004890 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004891 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004892 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4893 ShAmt);
4894 else
4895 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4896 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004897
Chris Lattner1023b872004-09-27 16:18:50 +00004898 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004899 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004900 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004901 return ReplaceInstUsesWith(I, Cst);
4902 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004903
Chris Lattner1023b872004-09-27 16:18:50 +00004904 if (LHSI->hasOneUse() || CI->isNullValue()) {
Zhou Shengfd28a332007-03-30 17:20:39 +00004905 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004906
Chris Lattner1023b872004-09-27 16:18:50 +00004907 // Otherwise strength reduce the shift into an and.
Zhou Shengb3a80b12007-03-29 08:15:12 +00004908 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004909 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004910
Chris Lattner1023b872004-09-27 16:18:50 +00004911 Instruction *AndI =
4912 BinaryOperator::createAnd(LHSI->getOperand(0),
4913 Mask, LHSI->getName()+".mask");
4914 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004915 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004916 ConstantExpr::getShl(CI, ShAmt));
4917 }
Chris Lattner1023b872004-09-27 16:18:50 +00004918 }
4919 }
4920 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004921
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004922 case Instruction::SDiv:
4923 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004924 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004925 // Fold this div into the comparison, producing a range check.
4926 // Determine, based on the divide type, what the range is being
4927 // checked. If there is an overflow on the low or high side, remember
4928 // it, otherwise compute the range [low, hi) bounding the new value.
4929 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004930 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004931 // FIXME: If the operand types don't match the type of the divide
4932 // then don't attempt this transform. The code below doesn't have the
4933 // logic to deal with a signed divide and an unsigned compare (and
4934 // vice versa). This is because (x /s C1) <s C2 produces different
4935 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4936 // (x /u C1) <u C2. Simply casting the operands and result won't
4937 // work. :( The if statement below tests that condition and bails
4938 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004939 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4940 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004941 break;
Reid Spencerf4071162007-03-21 23:19:50 +00004942 if (DivRHS->isZero())
4943 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004944
4945 // Initialize the variables that will indicate the nature of the
4946 // range check.
4947 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004948 ConstantInt *LoBound = 0, *HiBound = 0;
4949
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004950 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4951 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4952 // C2 (CI). By solving for X we can turn this into a range check
4953 // instead of computing a divide.
4954 ConstantInt *Prod =
4955 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004956
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004957 // Determine if the product overflows by seeing if the product is
4958 // not equal to the divide. Make sure we do the same kind of divide
4959 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00004960 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4961 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004962
Reid Spencer266e42b2006-12-23 06:05:41 +00004963 // Get the ICmp opcode
4964 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004965
Reid Spencerf4071162007-03-21 23:19:50 +00004966 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004967 LoBound = Prod;
4968 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004969 HiOverflow = ProdOV ||
4970 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00004971 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004972 if (CI->isNullValue()) { // (X / pos) op 0
4973 // Can't overflow.
4974 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4975 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00004976 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004977 LoBound = Prod;
4978 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004979 HiOverflow = ProdOV ||
4980 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004981 } else { // (X / pos) op neg
4982 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4983 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00004984 cast<ConstantInt>(DivRHSH), true);
4985 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004986 HiOverflow = ProdOV;
4987 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004988 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004989 if (CI->isNullValue()) { // (X / neg) op 0
4990 LoBound = AddOne(DivRHS);
4991 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004992 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004993 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00004994 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004995 HiOverflow = LoOverflow = ProdOV;
4996 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00004997 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
4998 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004999 HiBound = AddOne(Prod);
5000 } else { // (X / neg) op neg
5001 LoBound = Prod;
5002 LoOverflow = HiOverflow = ProdOV;
5003 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5004 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005005
Chris Lattnera92af962004-10-11 19:40:04 +00005006 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005007 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005008 }
5009
5010 if (LoBound) {
5011 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005012 switch (predicate) {
5013 default: assert(0 && "Unhandled icmp opcode!");
5014 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005015 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005016 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005017 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005018 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5019 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005020 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5022 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005023 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005024 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5025 true, I);
5026 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005027 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005028 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005029 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005030 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5031 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005032 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005033 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5034 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005035 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005036 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5037 false, I);
5038 case ICmpInst::ICMP_ULT:
5039 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005040 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005041 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005042 return new ICmpInst(predicate, X, LoBound);
5043 case ICmpInst::ICMP_UGT:
5044 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005045 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005046 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005047 if (predicate == ICmpInst::ICMP_UGT)
5048 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5049 else
5050 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005051 }
5052 }
5053 }
5054 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005055 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005056
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005058 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005059 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005060
Reid Spencere0fc4df2006-10-20 07:07:24 +00005061 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5062 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005063 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5064 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005065 case Instruction::SRem:
5066 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005067 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005068 BO->hasOneUse()) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005069 const APInt& V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005070 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005071 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5072 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005073 return new ICmpInst(I.getPredicate(), NewRem,
5074 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005075 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005076 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005077 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005078 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005079 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5080 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005081 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005082 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5083 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005084 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005085 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5086 // efficiently invertible, or if the add has just this one use.
5087 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005088
Chris Lattnerc992add2003-08-13 05:33:12 +00005089 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005090 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005091 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005092 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005093 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005094 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005095 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005096 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005097 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005098 }
5099 }
5100 break;
5101 case Instruction::Xor:
5102 // For the xor case, we can xor two constants together, eliminating
5103 // the explicit xor.
5104 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005105 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5106 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005107
5108 // FALLTHROUGH
5109 case Instruction::Sub:
5110 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005111 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005112 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5113 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005114 break;
5115
5116 case Instruction::Or:
5117 // If bits are being or'd in that are not present in the constant we
5118 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005119 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005120 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005121 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005122 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5123 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005124 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005125 break;
5126
5127 case Instruction::And:
5128 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005129 // If bits are being compared against that are and'd out, then the
5130 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005131 if (!ConstantExpr::getAnd(CI,
5132 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005133 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5134 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005135
Chris Lattner35167c32004-06-09 07:59:58 +00005136 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005137 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005138 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5139 ICmpInst::ICMP_NE, Op0,
5140 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005141
Reid Spencer266e42b2006-12-23 06:05:41 +00005142 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005143 if (isSignBit(BOC)) {
5144 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005145 Constant *Zero = Constant::getNullValue(X->getType());
5146 ICmpInst::Predicate pred = isICMP_NE ?
5147 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5148 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005149 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005150
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005151 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005152 if (CI->isNullValue() && isHighOnes(BOC)) {
5153 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005154 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005155 ICmpInst::Predicate pred = isICMP_NE ?
5156 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5157 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005158 }
5159
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005160 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005161 default: break;
5162 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005163 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
Reid Spencer6bba6c82007-04-01 07:35:23 +00005164 // Handle icmp {eq|ne} <intrinsic>, intcst.
5165 if (II->getIntrinsicID() == Intrinsic::bswap) {
5166 AddToWorkList(II);
Chris Lattnera7942b72006-11-29 05:02:16 +00005167 I.setOperand(0, II->getOperand(1));
Reid Spencer6bba6c82007-04-01 07:35:23 +00005168 I.setOperand(1, ConstantInt::get(CI->getValue().byteSwap()));
Chris Lattnera7942b72006-11-29 05:02:16 +00005169 return &I;
5170 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005171 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005172 } else { // Not a ICMP_EQ/ICMP_NE
5173 // If the LHS is a cast from an integral value of the same size, then
5174 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005175 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5176 Value *CastOp = Cast->getOperand(0);
5177 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005178 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005179 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005180 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005181 // If this is an unsigned comparison, try to make the comparison use
5182 // smaller constant values.
5183 switch (I.getPredicate()) {
5184 default: break;
5185 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5186 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005187 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005188 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005189 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005190 break;
5191 }
5192 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5193 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005194 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005195 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5196 Constant::getNullValue(SrcTy));
5197 break;
5198 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005199 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005200
Chris Lattner2b55ea32004-02-23 07:16:20 +00005201 }
5202 }
Chris Lattnere967b342003-06-04 05:10:11 +00005203 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005204 }
5205
Reid Spencer266e42b2006-12-23 06:05:41 +00005206 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005207 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5208 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5209 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005210 case Instruction::GetElementPtr:
5211 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005212 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005213 bool isAllZeros = true;
5214 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5215 if (!isa<Constant>(LHSI->getOperand(i)) ||
5216 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5217 isAllZeros = false;
5218 break;
5219 }
5220 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005222 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5223 }
5224 break;
5225
Chris Lattner77c32c32005-04-23 15:31:55 +00005226 case Instruction::PHI:
5227 if (Instruction *NV = FoldOpIntoPhi(I))
5228 return NV;
5229 break;
5230 case Instruction::Select:
5231 // If either operand of the select is a constant, we can fold the
5232 // comparison into the select arms, which will cause one to be
5233 // constant folded and the select turned into a bitwise or.
5234 Value *Op1 = 0, *Op2 = 0;
5235 if (LHSI->hasOneUse()) {
5236 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5237 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005238 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5239 // Insert a new ICmp of the other select operand.
5240 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5241 LHSI->getOperand(2), RHSC,
5242 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005243 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5244 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005245 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5246 // Insert a new ICmp of the other select operand.
5247 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5248 LHSI->getOperand(1), RHSC,
5249 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005250 }
5251 }
Jeff Cohen82639852005-04-23 21:38:35 +00005252
Chris Lattner77c32c32005-04-23 15:31:55 +00005253 if (Op1)
5254 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5255 break;
5256 }
5257 }
5258
Reid Spencer266e42b2006-12-23 06:05:41 +00005259 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005260 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005261 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005262 return NI;
5263 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005264 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5265 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005266 return NI;
5267
Reid Spencer266e42b2006-12-23 06:05:41 +00005268 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005269 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5270 // now.
5271 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5272 if (isa<PointerType>(Op0->getType()) &&
5273 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005274 // We keep moving the cast from the left operand over to the right
5275 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005276 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005277
Chris Lattner64d87b02007-01-06 01:45:59 +00005278 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5279 // so eliminate it as well.
5280 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5281 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005282
Chris Lattner16930792003-11-03 04:25:02 +00005283 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005284 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005285 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005286 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005287 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005288 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005289 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005290 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005291 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005292 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005293 }
5294
5295 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005296 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005297 // This comes up when you have code like
5298 // int X = A < B;
5299 // if (X) ...
5300 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005301 // with a constant or another cast from the same type.
5302 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005303 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005304 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005305 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005306
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005307 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005308 Value *A, *B, *C, *D;
5309 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5310 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5311 Value *OtherVal = A == Op1 ? B : A;
5312 return new ICmpInst(I.getPredicate(), OtherVal,
5313 Constant::getNullValue(A->getType()));
5314 }
5315
5316 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5317 // A^c1 == C^c2 --> A == C^(c1^c2)
5318 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5319 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5320 if (Op1->hasOneUse()) {
5321 Constant *NC = ConstantExpr::getXor(C1, C2);
5322 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5323 return new ICmpInst(I.getPredicate(), A,
5324 InsertNewInstBefore(Xor, I));
5325 }
5326
5327 // A^B == A^D -> B == D
5328 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5329 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5330 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5331 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5332 }
5333 }
5334
5335 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5336 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005337 // A == (A^B) -> B == 0
5338 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005339 return new ICmpInst(I.getPredicate(), OtherVal,
5340 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005341 }
5342 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005343 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005344 return new ICmpInst(I.getPredicate(), B,
5345 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005346 }
5347 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005348 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005349 return new ICmpInst(I.getPredicate(), B,
5350 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005351 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005352
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005353 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5354 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5355 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5356 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5357 Value *X = 0, *Y = 0, *Z = 0;
5358
5359 if (A == C) {
5360 X = B; Y = D; Z = A;
5361 } else if (A == D) {
5362 X = B; Y = C; Z = A;
5363 } else if (B == C) {
5364 X = A; Y = D; Z = B;
5365 } else if (B == D) {
5366 X = A; Y = C; Z = B;
5367 }
5368
5369 if (X) { // Build (X^Y) & Z
5370 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5371 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5372 I.setOperand(0, Op1);
5373 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5374 return &I;
5375 }
5376 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005377 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005378 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005379}
5380
Reid Spencer266e42b2006-12-23 06:05:41 +00005381// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005382// We only handle extending casts so far.
5383//
Reid Spencer266e42b2006-12-23 06:05:41 +00005384Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5385 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005386 Value *LHSCIOp = LHSCI->getOperand(0);
5387 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005388 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005389 Value *RHSCIOp;
5390
Reid Spencer266e42b2006-12-23 06:05:41 +00005391 // We only handle extension cast instructions, so far. Enforce this.
5392 if (LHSCI->getOpcode() != Instruction::ZExt &&
5393 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005394 return 0;
5395
Reid Spencer266e42b2006-12-23 06:05:41 +00005396 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5397 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005398
Reid Spencer266e42b2006-12-23 06:05:41 +00005399 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005400 // Not an extension from the same type?
5401 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005402 if (RHSCIOp->getType() != LHSCIOp->getType())
5403 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005404
5405 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5406 // and the other is a zext), then we can't handle this.
5407 if (CI->getOpcode() != LHSCI->getOpcode())
5408 return 0;
5409
5410 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5411 // then we can't handle this.
5412 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5413 return 0;
5414
5415 // Okay, just insert a compare of the reduced operands now!
5416 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005417 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005418
Reid Spencer266e42b2006-12-23 06:05:41 +00005419 // If we aren't dealing with a constant on the RHS, exit early
5420 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5421 if (!CI)
5422 return 0;
5423
5424 // Compute the constant that would happen if we truncated to SrcTy then
5425 // reextended to DestTy.
5426 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5427 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5428
5429 // If the re-extended constant didn't change...
5430 if (Res2 == CI) {
5431 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5432 // For example, we might have:
5433 // %A = sext short %X to uint
5434 // %B = icmp ugt uint %A, 1330
5435 // It is incorrect to transform this into
5436 // %B = icmp ugt short %X, 1330
5437 // because %A may have negative value.
5438 //
5439 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5440 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005441 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005442 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5443 else
5444 return 0;
5445 }
5446
5447 // The re-extended constant changed so the constant cannot be represented
5448 // in the shorter type. Consequently, we cannot emit a simple comparison.
5449
5450 // First, handle some easy cases. We know the result cannot be equal at this
5451 // point so handle the ICI.isEquality() cases
5452 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005453 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005454 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005455 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005456
5457 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5458 // should have been folded away previously and not enter in here.
5459 Value *Result;
5460 if (isSignedCmp) {
5461 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005462 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005463 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005464 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005465 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005466 } else {
5467 // We're performing an unsigned comparison.
5468 if (isSignedExt) {
5469 // We're performing an unsigned comp with a sign extended value.
5470 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005471 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005472 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5473 NegOne, ICI.getName()), ICI);
5474 } else {
5475 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005476 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005477 }
5478 }
5479
5480 // Finally, return the value computed.
5481 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5482 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5483 return ReplaceInstUsesWith(ICI, Result);
5484 } else {
5485 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5486 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5487 "ICmp should be folded!");
5488 if (Constant *CI = dyn_cast<Constant>(Result))
5489 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5490 else
5491 return BinaryOperator::createNot(Result);
5492 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005493}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005494
Reid Spencer2341c222007-02-02 02:16:23 +00005495Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5496 return commonShiftTransforms(I);
5497}
5498
5499Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5500 return commonShiftTransforms(I);
5501}
5502
5503Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5504 return commonShiftTransforms(I);
5505}
5506
5507Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5508 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005510
5511 // shl X, 0 == X and shr X, 0 == X
5512 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005513 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005514 Op0 == Constant::getNullValue(Op0->getType()))
5515 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005516
Reid Spencer266e42b2006-12-23 06:05:41 +00005517 if (isa<UndefValue>(Op0)) {
5518 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005519 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005520 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005521 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5522 }
5523 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005524 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5525 return ReplaceInstUsesWith(I, Op0);
5526 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005527 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005528 }
5529
Chris Lattnerd4dee402006-11-10 23:38:52 +00005530 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5531 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005532 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005533 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005534 return ReplaceInstUsesWith(I, CSI);
5535
Chris Lattner183b3362004-04-09 19:05:30 +00005536 // Try to fold constant and into select arguments.
5537 if (isa<Constant>(Op0))
5538 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005539 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005540 return R;
5541
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005542 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005543 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005544 if (MaskedValueIsZero(Op0,
5545 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005546 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005547 }
5548 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005549
Reid Spencere0fc4df2006-10-20 07:07:24 +00005550 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005551 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5552 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005553 return 0;
5554}
5555
Reid Spencere0fc4df2006-10-20 07:07:24 +00005556Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005557 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005558 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005559
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005560 // See if we can simplify any instructions used by the instruction whose sole
5561 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005562 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5563 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5564 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005565 KnownZero, KnownOne))
5566 return &I;
5567
Chris Lattner14553932006-01-06 07:12:35 +00005568 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5569 // of a signed value.
5570 //
Zhou Shengb25806f2007-03-30 09:29:48 +00005571 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005572 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005573 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5574 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005575 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005576 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005577 }
Chris Lattner14553932006-01-06 07:12:35 +00005578 }
5579
5580 // ((X*C1) << C2) == (X * (C1 << C2))
5581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5582 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5583 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5584 return BinaryOperator::createMul(BO->getOperand(0),
5585 ConstantExpr::getShl(BOOp, Op1));
5586
5587 // Try to fold constant and into select arguments.
5588 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5589 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5590 return R;
5591 if (isa<PHINode>(Op0))
5592 if (Instruction *NV = FoldOpIntoPhi(I))
5593 return NV;
5594
5595 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005596 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5597 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5598 Value *V1, *V2;
5599 ConstantInt *CC;
5600 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005601 default: break;
5602 case Instruction::Add:
5603 case Instruction::And:
5604 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005605 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005606 // These operators commute.
5607 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005608 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5609 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005610 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005611 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005612 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005613 Op0BO->getName());
5614 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005615 Instruction *X =
5616 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5617 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005618 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005619 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005620 return BinaryOperator::createAnd(X, ConstantInt::get(
5621 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005622 }
Chris Lattner14553932006-01-06 07:12:35 +00005623
Chris Lattner797dee72005-09-18 06:30:59 +00005624 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005625 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005626 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005627 match(Op0BOOp1,
5628 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005629 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5630 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005631 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005632 Op0BO->getOperand(0), Op1,
5633 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005634 InsertNewInstBefore(YS, I); // (Y << C)
5635 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005636 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005637 V1->getName()+".mask");
5638 InsertNewInstBefore(XM, I); // X & (CC << C)
5639
5640 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5641 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005642 }
Chris Lattner14553932006-01-06 07:12:35 +00005643
Reid Spencer2f34b982007-02-02 14:41:37 +00005644 // FALL THROUGH.
5645 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005646 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005647 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5648 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005649 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005650 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005651 Op0BO->getOperand(1), Op1,
5652 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005653 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005654 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005655 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005656 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005657 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005658 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005659 return BinaryOperator::createAnd(X, ConstantInt::get(
5660 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005661 }
Chris Lattner14553932006-01-06 07:12:35 +00005662
Chris Lattner1df0e982006-05-31 21:14:00 +00005663 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005664 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5665 match(Op0BO->getOperand(0),
5666 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005667 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005668 cast<BinaryOperator>(Op0BO->getOperand(0))
5669 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005670 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005671 Op0BO->getOperand(1), Op1,
5672 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005673 InsertNewInstBefore(YS, I); // (Y << C)
5674 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005675 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005676 V1->getName()+".mask");
5677 InsertNewInstBefore(XM, I); // X & (CC << C)
5678
Chris Lattner1df0e982006-05-31 21:14:00 +00005679 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005680 }
Chris Lattner14553932006-01-06 07:12:35 +00005681
Chris Lattner27cb9db2005-09-18 05:12:10 +00005682 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005683 }
Chris Lattner14553932006-01-06 07:12:35 +00005684 }
5685
5686
5687 // If the operand is an bitwise operator with a constant RHS, and the
5688 // shift is the only use, we can pull it out of the shift.
5689 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5690 bool isValid = true; // Valid only for And, Or, Xor
5691 bool highBitSet = false; // Transform if high bit of constant set?
5692
5693 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005694 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005695 case Instruction::Add:
5696 isValid = isLeftShift;
5697 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005698 case Instruction::Or:
5699 case Instruction::Xor:
5700 highBitSet = false;
5701 break;
5702 case Instruction::And:
5703 highBitSet = true;
5704 break;
Chris Lattner14553932006-01-06 07:12:35 +00005705 }
5706
5707 // If this is a signed shift right, and the high bit is modified
5708 // by the logical operation, do not perform the transformation.
5709 // The highBitSet boolean indicates the value of the high bit of
5710 // the constant which would cause it to be modified for this
5711 // operation.
5712 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005713 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005714 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005715 }
5716
5717 if (isValid) {
5718 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5719
5720 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005721 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005722 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005723 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005724
5725 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5726 NewRHS);
5727 }
5728 }
5729 }
5730 }
5731
Chris Lattnereb372a02006-01-06 07:52:12 +00005732 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005733 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5734 if (ShiftOp && !ShiftOp->isShift())
5735 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005736
Reid Spencere0fc4df2006-10-20 07:07:24 +00005737 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005738 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00005739 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5740 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00005741 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5742 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5743 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005744
Chris Lattner3e009e82007-02-05 00:57:54 +00005745 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005746 if (AmtSum > TypeBits)
5747 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005748
5749 const IntegerType *Ty = cast<IntegerType>(I.getType());
5750
5751 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005752 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005753 return BinaryOperator::create(I.getOpcode(), X,
5754 ConstantInt::get(Ty, AmtSum));
5755 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5756 I.getOpcode() == Instruction::AShr) {
5757 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5758 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5759 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5760 I.getOpcode() == Instruction::LShr) {
5761 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5762 Instruction *Shift =
5763 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5764 InsertNewInstBefore(Shift, I);
5765
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005766 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005767 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005768 }
5769
Chris Lattner3e009e82007-02-05 00:57:54 +00005770 // Okay, if we get here, one shift must be left, and the other shift must be
5771 // right. See if the amounts are equal.
5772 if (ShiftAmt1 == ShiftAmt2) {
5773 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5774 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005775 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005776 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005777 }
5778 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5779 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005780 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005781 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005782 }
5783 // We can simplify ((X << C) >>s C) into a trunc + sext.
5784 // NOTE: we could do this for any C, but that would make 'unusual' integer
5785 // types. For now, just stick to ones well-supported by the code
5786 // generators.
5787 const Type *SExtType = 0;
5788 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005789 case 1 :
5790 case 8 :
5791 case 16 :
5792 case 32 :
5793 case 64 :
5794 case 128:
5795 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5796 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005797 default: break;
5798 }
5799 if (SExtType) {
5800 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5801 InsertNewInstBefore(NewTrunc, I);
5802 return new SExtInst(NewTrunc, Ty);
5803 }
5804 // Otherwise, we can't handle it yet.
5805 } else if (ShiftAmt1 < ShiftAmt2) {
5806 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005807
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005808 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005809 if (I.getOpcode() == Instruction::Shl) {
5810 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5811 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005812 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005813 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005814 InsertNewInstBefore(Shift, I);
5815
Reid Spencer52830322007-03-25 21:11:44 +00005816 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5817 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005818 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005819
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005820 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005821 if (I.getOpcode() == Instruction::LShr) {
5822 assert(ShiftOp->getOpcode() == Instruction::Shl);
5823 Instruction *Shift =
5824 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5825 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005826
Reid Spencer769a5a82007-03-26 17:18:58 +00005827 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005828 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005829 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005830
5831 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5832 } else {
5833 assert(ShiftAmt2 < ShiftAmt1);
5834 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5835
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005836 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005837 if (I.getOpcode() == Instruction::Shl) {
5838 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5839 ShiftOp->getOpcode() == Instruction::AShr);
5840 Instruction *Shift =
5841 BinaryOperator::create(ShiftOp->getOpcode(), X,
5842 ConstantInt::get(Ty, ShiftDiff));
5843 InsertNewInstBefore(Shift, I);
5844
Reid Spencer52830322007-03-25 21:11:44 +00005845 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005846 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005847 }
5848
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005849 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005850 if (I.getOpcode() == Instruction::LShr) {
5851 assert(ShiftOp->getOpcode() == Instruction::Shl);
5852 Instruction *Shift =
5853 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5854 InsertNewInstBefore(Shift, I);
5855
Reid Spencer441486c2007-03-26 23:45:51 +00005856 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005857 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005858 }
5859
5860 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005861 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005862 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005863 return 0;
5864}
5865
Chris Lattner48a44f72002-05-02 17:06:02 +00005866
Chris Lattner8f663e82005-10-29 04:36:15 +00005867/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5868/// expression. If so, decompose it, returning some value X, such that Val is
5869/// X*Scale+Offset.
5870///
5871static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5872 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005873 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005874 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005875 Offset = CI->getZExtValue();
5876 Scale = 1;
5877 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005878 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5879 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005880 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005881 if (I->getOpcode() == Instruction::Shl) {
5882 // This is a value scaled by '1 << the shift amt'.
5883 Scale = 1U << CUI->getZExtValue();
5884 Offset = 0;
5885 return I->getOperand(0);
5886 } else if (I->getOpcode() == Instruction::Mul) {
5887 // This value is scaled by 'CUI'.
5888 Scale = CUI->getZExtValue();
5889 Offset = 0;
5890 return I->getOperand(0);
5891 } else if (I->getOpcode() == Instruction::Add) {
5892 // We have X+C. Check to see if we really have (X*C2)+C1,
5893 // where C1 is divisible by C2.
5894 unsigned SubScale;
5895 Value *SubVal =
5896 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5897 Offset += CUI->getZExtValue();
5898 if (SubScale > 1 && (Offset % SubScale == 0)) {
5899 Scale = SubScale;
5900 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005901 }
5902 }
5903 }
5904 }
5905 }
5906
5907 // Otherwise, we can't look past this.
5908 Scale = 1;
5909 Offset = 0;
5910 return Val;
5911}
5912
5913
Chris Lattner216be912005-10-24 06:03:58 +00005914/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5915/// try to eliminate the cast by moving the type information into the alloc.
5916Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5917 AllocationInst &AI) {
5918 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005919 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005920
Chris Lattnerac87beb2005-10-24 06:22:12 +00005921 // Remove any uses of AI that are dead.
5922 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005923
Chris Lattnerac87beb2005-10-24 06:22:12 +00005924 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5925 Instruction *User = cast<Instruction>(*UI++);
5926 if (isInstructionTriviallyDead(User)) {
5927 while (UI != E && *UI == User)
5928 ++UI; // If this instruction uses AI more than once, don't break UI.
5929
Chris Lattnerac87beb2005-10-24 06:22:12 +00005930 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005931 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005932 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005933 }
5934 }
5935
Chris Lattner216be912005-10-24 06:03:58 +00005936 // Get the type really allocated and the type casted to.
5937 const Type *AllocElTy = AI.getAllocatedType();
5938 const Type *CastElTy = PTy->getElementType();
5939 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005940
Chris Lattner945e4372007-02-14 05:52:17 +00005941 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5942 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005943 if (CastElTyAlign < AllocElTyAlign) return 0;
5944
Chris Lattner46705b22005-10-24 06:35:18 +00005945 // If the allocation has multiple uses, only promote it if we are strictly
5946 // increasing the alignment of the resultant allocation. If we keep it the
5947 // same, we open the door to infinite loops of various kinds.
5948 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5949
Chris Lattner216be912005-10-24 06:03:58 +00005950 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5951 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005952 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005953
Chris Lattner8270c332005-10-29 03:19:53 +00005954 // See if we can satisfy the modulus by pulling a scale out of the array
5955 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005956 unsigned ArraySizeScale, ArrayOffset;
5957 Value *NumElements = // See if the array size is a decomposable linear expr.
5958 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5959
Chris Lattner8270c332005-10-29 03:19:53 +00005960 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5961 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005962 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5963 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005964
Chris Lattner8270c332005-10-29 03:19:53 +00005965 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5966 Value *Amt = 0;
5967 if (Scale == 1) {
5968 Amt = NumElements;
5969 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005970 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005971 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5972 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005973 Amt = ConstantExpr::getMul(
5974 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5975 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005976 else if (Scale != 1) {
5977 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5978 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005979 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005980 }
5981
Chris Lattner8f663e82005-10-29 04:36:15 +00005982 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005983 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005984 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5985 Amt = InsertNewInstBefore(Tmp, AI);
5986 }
5987
Chris Lattner216be912005-10-24 06:03:58 +00005988 AllocationInst *New;
5989 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00005990 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005991 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00005992 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005993 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005994 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005995
5996 // If the allocation has multiple uses, insert a cast and change all things
5997 // that used it to use the new cast. This will also hack on CI, but it will
5998 // die soon.
5999 if (!AI.hasOneUse()) {
6000 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006001 // New is the allocation instruction, pointer typed. AI is the original
6002 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6003 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006004 InsertNewInstBefore(NewCast, AI);
6005 AI.replaceAllUsesWith(NewCast);
6006 }
Chris Lattner216be912005-10-24 06:03:58 +00006007 return ReplaceInstUsesWith(CI, New);
6008}
6009
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006010/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006011/// and return it as type Ty without inserting any new casts and without
6012/// changing the computed value. This is used by code that tries to decide
6013/// whether promoting or shrinking integer operations to wider or smaller types
6014/// will allow us to eliminate a truncate or extend.
6015///
6016/// This is a truncation operation if Ty is smaller than V->getType(), or an
6017/// extension operation if Ty is larger.
6018static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006019 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006020 // We can always evaluate constants in another type.
6021 if (isa<ConstantInt>(V))
6022 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006023
6024 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006025 if (!I) return false;
6026
6027 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006028
6029 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006030 case Instruction::Add:
6031 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006032 case Instruction::And:
6033 case Instruction::Or:
6034 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006035 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006036 // These operators can all arbitrarily be extended or truncated.
6037 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6038 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006039
Chris Lattner960acb02006-11-29 07:18:39 +00006040 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006041 if (!I->hasOneUse()) return false;
6042 // If we are truncating the result of this SHL, and if it's a shift of a
6043 // constant amount, we can always perform a SHL in a smaller type.
6044 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006045 uint32_t BitWidth = Ty->getBitWidth();
6046 if (BitWidth < OrigTy->getBitWidth() &&
6047 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006048 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6049 }
6050 break;
6051 case Instruction::LShr:
6052 if (!I->hasOneUse()) return false;
6053 // If this is a truncate of a logical shr, we can truncate it to a smaller
6054 // lshr iff we know that the bits we would otherwise be shifting in are
6055 // already zeros.
6056 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006057 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6058 uint32_t BitWidth = Ty->getBitWidth();
6059 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006060 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00006061 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6062 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006063 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6064 }
6065 }
Chris Lattner960acb02006-11-29 07:18:39 +00006066 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006067 case Instruction::Trunc:
6068 case Instruction::ZExt:
6069 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006070 // If this is a cast from the destination type, we can trivially eliminate
6071 // it, and this will remove a cast overall.
6072 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006073 // If the first operand is itself a cast, and is eliminable, do not count
6074 // this as an eliminable cast. We would prefer to eliminate those two
6075 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006076 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006077 return true;
6078
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006079 ++NumCastsRemoved;
6080 return true;
6081 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006082 break;
6083 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006084 // TODO: Can handle more cases here.
6085 break;
6086 }
6087
6088 return false;
6089}
6090
6091/// EvaluateInDifferentType - Given an expression that
6092/// CanEvaluateInDifferentType returns true for, actually insert the code to
6093/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006094Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006095 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006096 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006097 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006098
6099 // Otherwise, it must be an instruction.
6100 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006101 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006102 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006103 case Instruction::Add:
6104 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006105 case Instruction::And:
6106 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006107 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006108 case Instruction::AShr:
6109 case Instruction::LShr:
6110 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006111 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006112 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6113 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6114 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006115 break;
6116 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006117 case Instruction::Trunc:
6118 case Instruction::ZExt:
6119 case Instruction::SExt:
6120 case Instruction::BitCast:
6121 // If the source type of the cast is the type we're trying for then we can
6122 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006123 if (I->getOperand(0)->getType() == Ty)
6124 return I->getOperand(0);
6125
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006126 // Some other kind of cast, which shouldn't happen, so just ..
6127 // FALL THROUGH
6128 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006129 // TODO: Can handle more cases here.
6130 assert(0 && "Unreachable!");
6131 break;
6132 }
6133
6134 return InsertNewInstBefore(Res, *I);
6135}
6136
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006137/// @brief Implement the transforms common to all CastInst visitors.
6138Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006139 Value *Src = CI.getOperand(0);
6140
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006141 // Casting undef to anything results in undef so might as just replace it and
6142 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006143 if (isa<UndefValue>(Src)) // cast undef -> undef
6144 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6145
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006146 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6147 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006148 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006149 if (Instruction::CastOps opc =
6150 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6151 // The first cast (CSrc) is eliminable so we need to fix up or replace
6152 // the second cast (CI). CSrc will then have a good chance of being dead.
6153 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006154 }
6155 }
Chris Lattner03841652004-05-25 04:29:21 +00006156
Chris Lattnerd0d51602003-06-21 23:12:02 +00006157 // If casting the result of a getelementptr instruction with no offset, turn
6158 // this into a cast of the original pointer!
6159 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006160 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006161 bool AllZeroOperands = true;
6162 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6163 if (!isa<Constant>(GEP->getOperand(i)) ||
6164 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6165 AllZeroOperands = false;
6166 break;
6167 }
6168 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006169 // Changing the cast operand is usually not a good idea but it is safe
6170 // here because the pointer operand is being replaced with another
6171 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006172 CI.setOperand(0, GEP->getOperand(0));
6173 return &CI;
6174 }
6175 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006176
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006177 // If we are casting a malloc or alloca to a pointer to a type of the same
6178 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006179 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006180 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6181 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006182
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006183 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006184 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6185 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6186 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006187
6188 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006189 if (isa<PHINode>(Src))
6190 if (Instruction *NV = FoldOpIntoPhi(CI))
6191 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006192
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006193 return 0;
6194}
6195
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006196/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6197/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006198/// cases.
6199/// @brief Implement the transforms common to CastInst with integer operands
6200Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6201 if (Instruction *Result = commonCastTransforms(CI))
6202 return Result;
6203
6204 Value *Src = CI.getOperand(0);
6205 const Type *SrcTy = Src->getType();
6206 const Type *DestTy = CI.getType();
6207 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6208 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6209
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006210 // See if we can simplify any instructions used by the LHS whose sole
6211 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006212 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6213 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006214 KnownZero, KnownOne))
6215 return &CI;
6216
6217 // If the source isn't an instruction or has more than one use then we
6218 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006219 Instruction *SrcI = dyn_cast<Instruction>(Src);
6220 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006221 return 0;
6222
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006223 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006224 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006225 if (!isa<BitCastInst>(CI) &&
6226 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6227 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006228 // If this cast is a truncate, evaluting in a different type always
6229 // eliminates the cast, so it is always a win. If this is a noop-cast
6230 // this just removes a noop cast which isn't pointful, but simplifies
6231 // the code. If this is a zero-extension, we need to do an AND to
6232 // maintain the clear top-part of the computation, so we require that
6233 // the input have eliminated at least one cast. If this is a sign
6234 // extension, we insert two new casts (to do the extension) so we
6235 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006236 bool DoXForm;
6237 switch (CI.getOpcode()) {
6238 default:
6239 // All the others use floating point so we shouldn't actually
6240 // get here because of the check above.
6241 assert(0 && "Unknown cast type");
6242 case Instruction::Trunc:
6243 DoXForm = true;
6244 break;
6245 case Instruction::ZExt:
6246 DoXForm = NumCastsRemoved >= 1;
6247 break;
6248 case Instruction::SExt:
6249 DoXForm = NumCastsRemoved >= 2;
6250 break;
6251 case Instruction::BitCast:
6252 DoXForm = false;
6253 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006254 }
6255
6256 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006257 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6258 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006259 assert(Res->getType() == DestTy);
6260 switch (CI.getOpcode()) {
6261 default: assert(0 && "Unknown cast type!");
6262 case Instruction::Trunc:
6263 case Instruction::BitCast:
6264 // Just replace this cast with the result.
6265 return ReplaceInstUsesWith(CI, Res);
6266 case Instruction::ZExt: {
6267 // We need to emit an AND to clear the high bits.
6268 assert(SrcBitSize < DestBitSize && "Not a zext?");
Zhou Sheng2777a312007-03-28 09:19:01 +00006269 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006270 return BinaryOperator::createAnd(Res, C);
6271 }
6272 case Instruction::SExt:
6273 // We need to emit a cast to truncate, then a cast to sext.
6274 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006275 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6276 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006277 }
6278 }
6279 }
6280
6281 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6282 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6283
6284 switch (SrcI->getOpcode()) {
6285 case Instruction::Add:
6286 case Instruction::Mul:
6287 case Instruction::And:
6288 case Instruction::Or:
6289 case Instruction::Xor:
6290 // If we are discarding information, or just changing the sign,
6291 // rewrite.
6292 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6293 // Don't insert two casts if they cannot be eliminated. We allow
6294 // two casts to be inserted if the sizes are the same. This could
6295 // only be converting signedness, which is a noop.
6296 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006297 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6298 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006299 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006300 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6301 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6302 return BinaryOperator::create(
6303 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006304 }
6305 }
6306
6307 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6308 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6309 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006310 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006311 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006312 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006313 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6314 }
6315 break;
6316 case Instruction::SDiv:
6317 case Instruction::UDiv:
6318 case Instruction::SRem:
6319 case Instruction::URem:
6320 // If we are just changing the sign, rewrite.
6321 if (DestBitSize == SrcBitSize) {
6322 // Don't insert two casts if they cannot be eliminated. We allow
6323 // two casts to be inserted if the sizes are the same. This could
6324 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006325 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6326 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006327 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6328 Op0, DestTy, SrcI);
6329 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6330 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006331 return BinaryOperator::create(
6332 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6333 }
6334 }
6335 break;
6336
6337 case Instruction::Shl:
6338 // Allow changing the sign of the source operand. Do not allow
6339 // changing the size of the shift, UNLESS the shift amount is a
6340 // constant. We must not change variable sized shifts to a smaller
6341 // size, because it is undefined to shift more bits out than exist
6342 // in the value.
6343 if (DestBitSize == SrcBitSize ||
6344 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006345 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6346 Instruction::BitCast : Instruction::Trunc);
6347 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006348 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006349 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006350 }
6351 break;
6352 case Instruction::AShr:
6353 // If this is a signed shr, and if all bits shifted in are about to be
6354 // truncated off, turn it into an unsigned shr to allow greater
6355 // simplifications.
6356 if (DestBitSize < SrcBitSize &&
6357 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006358 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006359 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6360 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006361 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006362 }
6363 }
6364 break;
6365
Reid Spencer266e42b2006-12-23 06:05:41 +00006366 case Instruction::ICmp:
6367 // If we are just checking for a icmp eq of a single bit and casting it
6368 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006369 // cast to integer to avoid the comparison.
6370 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00006371 const APInt& Op1CV = Op1C->getValue();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006372 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6373 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6374 // cast (X == 1) to int --> X iff X has only the low bit set.
6375 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6376 // cast (X != 0) to int --> X iff X has only the low bit set.
6377 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6378 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6379 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006380 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006382 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6383 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6384 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006385 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006386
6387 // This only works for EQ and NE
6388 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6389 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6390 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006391
Zhou Sheng0900993e2007-03-23 03:13:21 +00006392 APInt KnownZeroMask(KnownZero ^ TypeMask);
6393 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006394 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006395 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006396 // (X&4) == 2 --> false
6397 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006398 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006399 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006400 return ReplaceInstUsesWith(CI, Res);
6401 }
6402
Zhou Sheng0900993e2007-03-23 03:13:21 +00006403 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006404 Value *In = Op0;
6405 if (ShiftAmt) {
6406 // Perform a logical shr by shiftamt.
6407 // Insert the shift to put the result in the low bit.
6408 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006409 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006410 ConstantInt::get(In->getType(), ShiftAmt),
6411 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006412 }
6413
Reid Spencer266e42b2006-12-23 06:05:41 +00006414 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006415 Constant *One = ConstantInt::get(In->getType(), 1);
6416 In = BinaryOperator::createXor(In, One, "tmp");
6417 InsertNewInstBefore(cast<Instruction>(In), CI);
6418 }
6419
6420 if (CI.getType() == In->getType())
6421 return ReplaceInstUsesWith(CI, In);
6422 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006423 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006424 }
6425 }
6426 }
6427 break;
6428 }
6429 return 0;
6430}
6431
6432Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006433 if (Instruction *Result = commonIntCastTransforms(CI))
6434 return Result;
6435
6436 Value *Src = CI.getOperand(0);
6437 const Type *Ty = CI.getType();
6438 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00006439 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006440
6441 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6442 switch (SrcI->getOpcode()) {
6443 default: break;
6444 case Instruction::LShr:
6445 // We can shrink lshr to something smaller if we know the bits shifted in
6446 // are already zeros.
6447 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006448 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00006449
6450 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006451 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006452 Value* SrcIOp0 = SrcI->getOperand(0);
6453 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006454 if (ShAmt >= DestBitWidth) // All zeros.
6455 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6456
6457 // Okay, we can shrink this. Truncate the input, then return a new
6458 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006459 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6460 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6461 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006462 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006463 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006464 } else { // This is a variable shr.
6465
6466 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6467 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6468 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006469 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006470 Value *One = ConstantInt::get(SrcI->getType(), 1);
6471
Reid Spencer2341c222007-02-02 02:16:23 +00006472 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006473 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006474 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006475 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6476 SrcI->getOperand(0),
6477 "tmp"), CI);
6478 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006479 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006480 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006481 }
6482 break;
6483 }
6484 }
6485
6486 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006487}
6488
6489Instruction *InstCombiner::visitZExt(CastInst &CI) {
6490 // If one of the common conversion will work ..
6491 if (Instruction *Result = commonIntCastTransforms(CI))
6492 return Result;
6493
6494 Value *Src = CI.getOperand(0);
6495
6496 // If this is a cast of a cast
6497 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006498 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6499 // types and if the sizes are just right we can convert this into a logical
6500 // 'and' which will be much cheaper than the pair of casts.
6501 if (isa<TruncInst>(CSrc)) {
6502 // Get the sizes of the types involved
6503 Value *A = CSrc->getOperand(0);
6504 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6505 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6506 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6507 // If we're actually extending zero bits and the trunc is a no-op
6508 if (MidSize < DstSize && SrcSize == DstSize) {
6509 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006510 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006511 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006512 Instruction *And =
6513 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6514 // Unfortunately, if the type changed, we need to cast it back.
6515 if (And->getType() != CI.getType()) {
6516 And->setName(CSrc->getName()+".mask");
6517 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006518 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006519 }
6520 return And;
6521 }
6522 }
6523 }
6524
6525 return 0;
6526}
6527
6528Instruction *InstCombiner::visitSExt(CastInst &CI) {
6529 return commonIntCastTransforms(CI);
6530}
6531
6532Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6533 return commonCastTransforms(CI);
6534}
6535
6536Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6537 return commonCastTransforms(CI);
6538}
6539
6540Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006541 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006542}
6543
6544Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006545 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006546}
6547
6548Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6549 return commonCastTransforms(CI);
6550}
6551
6552Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6553 return commonCastTransforms(CI);
6554}
6555
6556Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006557 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006558}
6559
6560Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6561 return commonCastTransforms(CI);
6562}
6563
6564Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6565
6566 // If the operands are integer typed then apply the integer transforms,
6567 // otherwise just apply the common ones.
6568 Value *Src = CI.getOperand(0);
6569 const Type *SrcTy = Src->getType();
6570 const Type *DestTy = CI.getType();
6571
Chris Lattner03c49532007-01-15 02:27:26 +00006572 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006573 if (Instruction *Result = commonIntCastTransforms(CI))
6574 return Result;
6575 } else {
6576 if (Instruction *Result = commonCastTransforms(CI))
6577 return Result;
6578 }
6579
6580
6581 // Get rid of casts from one type to the same type. These are useless and can
6582 // be replaced by the operand.
6583 if (DestTy == Src->getType())
6584 return ReplaceInstUsesWith(CI, Src);
6585
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006586 // If the source and destination are pointers, and this cast is equivalent to
6587 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6588 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006589 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6590 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6591 const Type *DstElTy = DstPTy->getElementType();
6592 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006593
Reid Spencerc635f472006-12-31 05:48:39 +00006594 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006595 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006596 while (SrcElTy != DstElTy &&
6597 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6598 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6599 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006600 ++NumZeros;
6601 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006602
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006603 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006604 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006605 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6606 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006607 }
6608 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006609 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006610
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006611 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6612 if (SVI->hasOneUse()) {
6613 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6614 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006615 if (isa<VectorType>(DestTy) &&
6616 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006617 SVI->getType()->getNumElements()) {
6618 CastInst *Tmp;
6619 // If either of the operands is a cast from CI.getType(), then
6620 // evaluating the shuffle in the casted destination's type will allow
6621 // us to eliminate at least one cast.
6622 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6623 Tmp->getOperand(0)->getType() == DestTy) ||
6624 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6625 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006626 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6627 SVI->getOperand(0), DestTy, &CI);
6628 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6629 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006630 // Return a new shuffle vector. Use the same element ID's, as we
6631 // know the vector types match #elts.
6632 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006633 }
6634 }
6635 }
6636 }
Chris Lattner260ab202002-04-18 17:39:14 +00006637 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006638}
6639
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006640/// GetSelectFoldableOperands - We want to turn code that looks like this:
6641/// %C = or %A, %B
6642/// %D = select %cond, %C, %A
6643/// into:
6644/// %C = select %cond, %B, 0
6645/// %D = or %A, %C
6646///
6647/// Assuming that the specified instruction is an operand to the select, return
6648/// a bitmask indicating which operands of this instruction are foldable if they
6649/// equal the other incoming value of the select.
6650///
6651static unsigned GetSelectFoldableOperands(Instruction *I) {
6652 switch (I->getOpcode()) {
6653 case Instruction::Add:
6654 case Instruction::Mul:
6655 case Instruction::And:
6656 case Instruction::Or:
6657 case Instruction::Xor:
6658 return 3; // Can fold through either operand.
6659 case Instruction::Sub: // Can only fold on the amount subtracted.
6660 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006661 case Instruction::LShr:
6662 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006663 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006664 default:
6665 return 0; // Cannot fold
6666 }
6667}
6668
6669/// GetSelectFoldableConstant - For the same transformation as the previous
6670/// function, return the identity constant that goes into the select.
6671static Constant *GetSelectFoldableConstant(Instruction *I) {
6672 switch (I->getOpcode()) {
6673 default: assert(0 && "This cannot happen!"); abort();
6674 case Instruction::Add:
6675 case Instruction::Sub:
6676 case Instruction::Or:
6677 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006678 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006679 case Instruction::LShr:
6680 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006681 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006682 case Instruction::And:
6683 return ConstantInt::getAllOnesValue(I->getType());
6684 case Instruction::Mul:
6685 return ConstantInt::get(I->getType(), 1);
6686 }
6687}
6688
Chris Lattner411336f2005-01-19 21:50:18 +00006689/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6690/// have the same opcode and only one use each. Try to simplify this.
6691Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6692 Instruction *FI) {
6693 if (TI->getNumOperands() == 1) {
6694 // If this is a non-volatile load or a cast from the same type,
6695 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006696 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006697 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6698 return 0;
6699 } else {
6700 return 0; // unknown unary op.
6701 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006702
Chris Lattner411336f2005-01-19 21:50:18 +00006703 // Fold this by inserting a select from the input values.
6704 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6705 FI->getOperand(0), SI.getName()+".v");
6706 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006707 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6708 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006709 }
6710
Reid Spencer2341c222007-02-02 02:16:23 +00006711 // Only handle binary operators here.
6712 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006713 return 0;
6714
6715 // Figure out if the operations have any operands in common.
6716 Value *MatchOp, *OtherOpT, *OtherOpF;
6717 bool MatchIsOpZero;
6718 if (TI->getOperand(0) == FI->getOperand(0)) {
6719 MatchOp = TI->getOperand(0);
6720 OtherOpT = TI->getOperand(1);
6721 OtherOpF = FI->getOperand(1);
6722 MatchIsOpZero = true;
6723 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6724 MatchOp = TI->getOperand(1);
6725 OtherOpT = TI->getOperand(0);
6726 OtherOpF = FI->getOperand(0);
6727 MatchIsOpZero = false;
6728 } else if (!TI->isCommutative()) {
6729 return 0;
6730 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6731 MatchOp = TI->getOperand(0);
6732 OtherOpT = TI->getOperand(1);
6733 OtherOpF = FI->getOperand(0);
6734 MatchIsOpZero = true;
6735 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6736 MatchOp = TI->getOperand(1);
6737 OtherOpT = TI->getOperand(0);
6738 OtherOpF = FI->getOperand(1);
6739 MatchIsOpZero = true;
6740 } else {
6741 return 0;
6742 }
6743
6744 // If we reach here, they do have operations in common.
6745 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6746 OtherOpF, SI.getName()+".v");
6747 InsertNewInstBefore(NewSI, SI);
6748
6749 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6750 if (MatchIsOpZero)
6751 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6752 else
6753 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006754 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006755 assert(0 && "Shouldn't get here");
6756 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006757}
6758
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006759Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006760 Value *CondVal = SI.getCondition();
6761 Value *TrueVal = SI.getTrueValue();
6762 Value *FalseVal = SI.getFalseValue();
6763
6764 // select true, X, Y -> X
6765 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006766 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006767 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006768
6769 // select C, X, X -> X
6770 if (TrueVal == FalseVal)
6771 return ReplaceInstUsesWith(SI, TrueVal);
6772
Chris Lattner81a7a232004-10-16 18:11:37 +00006773 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6774 return ReplaceInstUsesWith(SI, FalseVal);
6775 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6776 return ReplaceInstUsesWith(SI, TrueVal);
6777 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6778 if (isa<Constant>(TrueVal))
6779 return ReplaceInstUsesWith(SI, TrueVal);
6780 else
6781 return ReplaceInstUsesWith(SI, FalseVal);
6782 }
6783
Reid Spencer542964f2007-01-11 18:21:29 +00006784 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006785 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006786 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006787 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006788 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006789 } else {
6790 // Change: A = select B, false, C --> A = and !B, C
6791 Value *NotCond =
6792 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6793 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006794 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006795 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006796 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006797 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006798 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006799 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006800 } else {
6801 // Change: A = select B, C, true --> A = or !B, C
6802 Value *NotCond =
6803 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6804 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006805 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006806 }
6807 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006808 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006809
Chris Lattner183b3362004-04-09 19:05:30 +00006810 // Selecting between two integer constants?
6811 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6812 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6813 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006814 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006815 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006816 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006817 // select C, 0, 1 -> cast !C to int
6818 Value *NotCond =
6819 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006820 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006821 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006822 }
Chris Lattner35167c32004-06-09 07:59:58 +00006823
Reid Spencer266e42b2006-12-23 06:05:41 +00006824 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006825
Reid Spencer266e42b2006-12-23 06:05:41 +00006826 // (x <s 0) ? -1 : 0 -> ashr x, 31
6827 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006828 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006829 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6830 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006831 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006832 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006833 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006834 else {
6835 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006836 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006837 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006838 }
6839
6840 if (CanXForm) {
6841 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006842 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006843 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006844 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006845 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6846 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6847 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006848 InsertNewInstBefore(SRA, SI);
6849
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006850 // Finally, convert to the type of the select RHS. We figure out
6851 // if this requires a SExt, Trunc or BitCast based on the sizes.
6852 Instruction::CastOps opc = Instruction::BitCast;
6853 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6854 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6855 if (SRASize < SISize)
6856 opc = Instruction::SExt;
6857 else if (SRASize > SISize)
6858 opc = Instruction::Trunc;
6859 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006860 }
6861 }
6862
6863
6864 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006865 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006866 // non-constant value, eliminate this whole mess. This corresponds to
6867 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006868 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006869 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006870 cast<Constant>(IC->getOperand(1))->isNullValue())
6871 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6872 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006873 isa<ConstantInt>(ICA->getOperand(1)) &&
6874 (ICA->getOperand(1) == TrueValC ||
6875 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006876 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6877 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006878 // know whether we have a icmp_ne or icmp_eq and whether the
6879 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006880 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006881 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006882 Value *V = ICA;
6883 if (ShouldNotVal)
6884 V = InsertNewInstBefore(BinaryOperator::create(
6885 Instruction::Xor, V, ICA->getOperand(1)), SI);
6886 return ReplaceInstUsesWith(SI, V);
6887 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006888 }
Chris Lattner533bc492004-03-30 19:37:13 +00006889 }
Chris Lattner623fba12004-04-10 22:21:27 +00006890
6891 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006892 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6893 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006894 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006895 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006896 return ReplaceInstUsesWith(SI, FalseVal);
6897 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006898 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006899 return ReplaceInstUsesWith(SI, TrueVal);
6900 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6901
Reid Spencer266e42b2006-12-23 06:05:41 +00006902 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006903 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006904 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006905 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006906 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006907 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6908 return ReplaceInstUsesWith(SI, TrueVal);
6909 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6910 }
6911 }
6912
6913 // See if we are selecting two values based on a comparison of the two values.
6914 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6915 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6916 // Transform (X == Y) ? X : Y -> Y
6917 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6918 return ReplaceInstUsesWith(SI, FalseVal);
6919 // Transform (X != Y) ? X : Y -> X
6920 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6921 return ReplaceInstUsesWith(SI, TrueVal);
6922 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6923
6924 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6925 // Transform (X == Y) ? Y : X -> X
6926 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6927 return ReplaceInstUsesWith(SI, FalseVal);
6928 // Transform (X != Y) ? Y : X -> Y
6929 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006930 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006931 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6932 }
6933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006934
Chris Lattnera04c9042005-01-13 22:52:24 +00006935 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6936 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6937 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006938 Instruction *AddOp = 0, *SubOp = 0;
6939
Chris Lattner411336f2005-01-19 21:50:18 +00006940 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6941 if (TI->getOpcode() == FI->getOpcode())
6942 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6943 return IV;
6944
6945 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6946 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006947 if (TI->getOpcode() == Instruction::Sub &&
6948 FI->getOpcode() == Instruction::Add) {
6949 AddOp = FI; SubOp = TI;
6950 } else if (FI->getOpcode() == Instruction::Sub &&
6951 TI->getOpcode() == Instruction::Add) {
6952 AddOp = TI; SubOp = FI;
6953 }
6954
6955 if (AddOp) {
6956 Value *OtherAddOp = 0;
6957 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6958 OtherAddOp = AddOp->getOperand(1);
6959 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6960 OtherAddOp = AddOp->getOperand(0);
6961 }
6962
6963 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006964 // So at this point we know we have (Y -> OtherAddOp):
6965 // select C, (add X, Y), (sub X, Z)
6966 Value *NegVal; // Compute -Z
6967 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6968 NegVal = ConstantExpr::getNeg(C);
6969 } else {
6970 NegVal = InsertNewInstBefore(
6971 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006972 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006973
6974 Value *NewTrueOp = OtherAddOp;
6975 Value *NewFalseOp = NegVal;
6976 if (AddOp != TI)
6977 std::swap(NewTrueOp, NewFalseOp);
6978 Instruction *NewSel =
6979 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6980
6981 NewSel = InsertNewInstBefore(NewSel, SI);
6982 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006983 }
6984 }
6985 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006986
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006987 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006988 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006989 // See the comment above GetSelectFoldableOperands for a description of the
6990 // transformation we are doing here.
6991 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6992 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6993 !isa<Constant>(FalseVal))
6994 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6995 unsigned OpToFold = 0;
6996 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6997 OpToFold = 1;
6998 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6999 OpToFold = 2;
7000 }
7001
7002 if (OpToFold) {
7003 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007004 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007005 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007006 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007007 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7009 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007010 else {
7011 assert(0 && "Unknown instruction!!");
7012 }
7013 }
7014 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007015
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007016 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7017 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7018 !isa<Constant>(TrueVal))
7019 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7020 unsigned OpToFold = 0;
7021 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7022 OpToFold = 1;
7023 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7024 OpToFold = 2;
7025 }
7026
7027 if (OpToFold) {
7028 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007029 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007030 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007031 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007032 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007033 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7034 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007035 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007036 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007037 }
7038 }
7039 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007040
7041 if (BinaryOperator::isNot(CondVal)) {
7042 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7043 SI.setOperand(1, FalseVal);
7044 SI.setOperand(2, TrueVal);
7045 return &SI;
7046 }
7047
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007048 return 0;
7049}
7050
Chris Lattner82f2ef22006-03-06 20:18:44 +00007051/// GetKnownAlignment - If the specified pointer has an alignment that we can
7052/// determine, return it, otherwise return 0.
7053static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7054 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7055 unsigned Align = GV->getAlignment();
7056 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007057 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007058 return Align;
7059 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7060 unsigned Align = AI->getAlignment();
7061 if (Align == 0 && TD) {
7062 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007063 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007064 else if (isa<MallocInst>(AI)) {
7065 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007066 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007067 Align =
7068 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007069 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007070 Align =
7071 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007072 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007073 }
7074 }
7075 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007076 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007077 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007078 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007079 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007080 if (isa<PointerType>(CI->getOperand(0)->getType()))
7081 return GetKnownAlignment(CI->getOperand(0), TD);
7082 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007083 } else if (isa<GetElementPtrInst>(V) ||
7084 (isa<ConstantExpr>(V) &&
7085 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7086 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007087 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7088 if (BaseAlignment == 0) return 0;
7089
7090 // If all indexes are zero, it is just the alignment of the base pointer.
7091 bool AllZeroOperands = true;
7092 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7093 if (!isa<Constant>(GEPI->getOperand(i)) ||
7094 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7095 AllZeroOperands = false;
7096 break;
7097 }
7098 if (AllZeroOperands)
7099 return BaseAlignment;
7100
7101 // Otherwise, if the base alignment is >= the alignment we expect for the
7102 // base pointer type, then we know that the resultant pointer is aligned at
7103 // least as much as its type requires.
7104 if (!TD) return 0;
7105
7106 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007107 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007108 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007109 <= BaseAlignment) {
7110 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007111 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007112 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007113 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007114 return 0;
7115 }
7116 return 0;
7117}
7118
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007119
Chris Lattnerc66b2232006-01-13 20:11:04 +00007120/// visitCallInst - CallInst simplification. This mostly only handles folding
7121/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7122/// the heavy lifting.
7123///
Chris Lattner970c33a2003-06-19 17:00:31 +00007124Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007125 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7126 if (!II) return visitCallSite(&CI);
7127
Chris Lattner51ea1272004-02-28 05:22:00 +00007128 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7129 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007130 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007131 bool Changed = false;
7132
7133 // memmove/cpy/set of zero bytes is a noop.
7134 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7135 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7136
Chris Lattner00648e12004-10-12 04:52:52 +00007137 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007138 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007139 // Replace the instruction with just byte operations. We would
7140 // transform other cases to loads/stores, but we don't know if
7141 // alignment is sufficient.
7142 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007143 }
7144
Chris Lattner00648e12004-10-12 04:52:52 +00007145 // If we have a memmove and the source operation is a constant global,
7146 // then the source and dest pointers can't alias, so we can change this
7147 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007148 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007149 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7150 if (GVSrc->isConstant()) {
7151 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007152 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007153 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007154 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007155 Name = "llvm.memcpy.i32";
7156 else
7157 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007158 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007159 CI.getCalledFunction()->getFunctionType());
7160 CI.setOperand(0, MemCpy);
7161 Changed = true;
7162 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007163 }
Chris Lattner00648e12004-10-12 04:52:52 +00007164
Chris Lattner82f2ef22006-03-06 20:18:44 +00007165 // If we can determine a pointer alignment that is bigger than currently
7166 // set, update the alignment.
7167 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7168 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7169 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7170 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007171 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007172 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007173 Changed = true;
7174 }
7175 } else if (isa<MemSetInst>(MI)) {
7176 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007177 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007178 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007179 Changed = true;
7180 }
7181 }
7182
Chris Lattnerc66b2232006-01-13 20:11:04 +00007183 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007184 } else {
7185 switch (II->getIntrinsicID()) {
7186 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007187 case Intrinsic::ppc_altivec_lvx:
7188 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007189 case Intrinsic::x86_sse_loadu_ps:
7190 case Intrinsic::x86_sse2_loadu_pd:
7191 case Intrinsic::x86_sse2_loadu_dq:
7192 // Turn PPC lvx -> load if the pointer is known aligned.
7193 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007194 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007195 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007196 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007197 return new LoadInst(Ptr);
7198 }
7199 break;
7200 case Intrinsic::ppc_altivec_stvx:
7201 case Intrinsic::ppc_altivec_stvxl:
7202 // Turn stvx -> store if the pointer is known aligned.
7203 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007204 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007205 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7206 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007207 return new StoreInst(II->getOperand(1), Ptr);
7208 }
7209 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007210 case Intrinsic::x86_sse_storeu_ps:
7211 case Intrinsic::x86_sse2_storeu_pd:
7212 case Intrinsic::x86_sse2_storeu_dq:
7213 case Intrinsic::x86_sse2_storel_dq:
7214 // Turn X86 storeu -> store if the pointer is known aligned.
7215 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7216 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007217 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7218 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007219 return new StoreInst(II->getOperand(2), Ptr);
7220 }
7221 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007222
7223 case Intrinsic::x86_sse_cvttss2si: {
7224 // These intrinsics only demands the 0th element of its input vector. If
7225 // we can simplify the input based on that, do so now.
7226 uint64_t UndefElts;
7227 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7228 UndefElts)) {
7229 II->setOperand(1, V);
7230 return II;
7231 }
7232 break;
7233 }
7234
Chris Lattnere79d2492006-04-06 19:19:17 +00007235 case Intrinsic::ppc_altivec_vperm:
7236 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007237 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007238 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7239
7240 // Check that all of the elements are integer constants or undefs.
7241 bool AllEltsOk = true;
7242 for (unsigned i = 0; i != 16; ++i) {
7243 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7244 !isa<UndefValue>(Mask->getOperand(i))) {
7245 AllEltsOk = false;
7246 break;
7247 }
7248 }
7249
7250 if (AllEltsOk) {
7251 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007252 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7253 II->getOperand(1), Mask->getType(), CI);
7254 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7255 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007256 Value *Result = UndefValue::get(Op0->getType());
7257
7258 // Only extract each element once.
7259 Value *ExtractedElts[32];
7260 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7261
7262 for (unsigned i = 0; i != 16; ++i) {
7263 if (isa<UndefValue>(Mask->getOperand(i)))
7264 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007265 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007266 Idx &= 31; // Match the hardware behavior.
7267
7268 if (ExtractedElts[Idx] == 0) {
7269 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007270 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007271 InsertNewInstBefore(Elt, CI);
7272 ExtractedElts[Idx] = Elt;
7273 }
7274
7275 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007276 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007277 InsertNewInstBefore(cast<Instruction>(Result), CI);
7278 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007279 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007280 }
7281 }
7282 break;
7283
Chris Lattner503221f2006-01-13 21:28:09 +00007284 case Intrinsic::stackrestore: {
7285 // If the save is right next to the restore, remove the restore. This can
7286 // happen when variable allocas are DCE'd.
7287 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7288 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7289 BasicBlock::iterator BI = SS;
7290 if (&*++BI == II)
7291 return EraseInstFromFunction(CI);
7292 }
7293 }
7294
7295 // If the stack restore is in a return/unwind block and if there are no
7296 // allocas or calls between the restore and the return, nuke the restore.
7297 TerminatorInst *TI = II->getParent()->getTerminator();
7298 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7299 BasicBlock::iterator BI = II;
7300 bool CannotRemove = false;
7301 for (++BI; &*BI != TI; ++BI) {
7302 if (isa<AllocaInst>(BI) ||
7303 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7304 CannotRemove = true;
7305 break;
7306 }
7307 }
7308 if (!CannotRemove)
7309 return EraseInstFromFunction(CI);
7310 }
7311 break;
7312 }
7313 }
Chris Lattner00648e12004-10-12 04:52:52 +00007314 }
7315
Chris Lattnerc66b2232006-01-13 20:11:04 +00007316 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007317}
7318
7319// InvokeInst simplification
7320//
7321Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007322 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007323}
7324
Chris Lattneraec3d942003-10-07 22:32:43 +00007325// visitCallSite - Improvements for call and invoke instructions.
7326//
7327Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007328 bool Changed = false;
7329
7330 // If the callee is a constexpr cast of a function, attempt to move the cast
7331 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007332 if (transformConstExprCastCall(CS)) return 0;
7333
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007334 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007335
Chris Lattner61d9d812005-05-13 07:09:09 +00007336 if (Function *CalleeF = dyn_cast<Function>(Callee))
7337 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7338 Instruction *OldCall = CS.getInstruction();
7339 // If the call and callee calling conventions don't match, this call must
7340 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007341 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007342 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007343 if (!OldCall->use_empty())
7344 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7345 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7346 return EraseInstFromFunction(*OldCall);
7347 return 0;
7348 }
7349
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007350 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7351 // This instruction is not reachable, just remove it. We insert a store to
7352 // undef so that we know that this code is not reachable, despite the fact
7353 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007354 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007355 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007356 CS.getInstruction());
7357
7358 if (!CS.getInstruction()->use_empty())
7359 CS.getInstruction()->
7360 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7361
7362 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7363 // Don't break the CFG, insert a dummy cond branch.
7364 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007365 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007366 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007367 return EraseInstFromFunction(*CS.getInstruction());
7368 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007369
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007370 const PointerType *PTy = cast<PointerType>(Callee->getType());
7371 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7372 if (FTy->isVarArg()) {
7373 // See if we can optimize any arguments passed through the varargs area of
7374 // the call.
7375 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7376 E = CS.arg_end(); I != E; ++I)
7377 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7378 // If this cast does not effect the value passed through the varargs
7379 // area, we can eliminate the use of the cast.
7380 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007381 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007382 *I = Op;
7383 Changed = true;
7384 }
7385 }
7386 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007387
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007388 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007389}
7390
Chris Lattner970c33a2003-06-19 17:00:31 +00007391// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7392// attempt to move the cast to the arguments of the call/invoke.
7393//
7394bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7395 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7396 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007397 if (CE->getOpcode() != Instruction::BitCast ||
7398 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007399 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007400 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007401 Instruction *Caller = CS.getInstruction();
7402
7403 // Okay, this is a cast from a function to a different type. Unless doing so
7404 // would cause a type conversion of one of our arguments, change this call to
7405 // be a direct call with arguments casted to the appropriate types.
7406 //
7407 const FunctionType *FT = Callee->getFunctionType();
7408 const Type *OldRetTy = Caller->getType();
7409
Chris Lattner1f7942f2004-01-14 06:06:08 +00007410 // Check to see if we are changing the return type...
7411 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007412 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007413 // Conversion is ok if changing from pointer to int of same size.
7414 !(isa<PointerType>(FT->getReturnType()) &&
7415 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007416 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007417
7418 // If the callsite is an invoke instruction, and the return value is used by
7419 // a PHI node in a successor, we cannot change the return type of the call
7420 // because there is no place to put the cast instruction (without breaking
7421 // the critical edge). Bail out in this case.
7422 if (!Caller->use_empty())
7423 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7424 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7425 UI != E; ++UI)
7426 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7427 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007428 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007429 return false;
7430 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007431
7432 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7433 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007434
Chris Lattner970c33a2003-06-19 17:00:31 +00007435 CallSite::arg_iterator AI = CS.arg_begin();
7436 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7437 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007438 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007439 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007440 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007441 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007442 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007443 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007444 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7445 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007446 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007447 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007448 }
7449
7450 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007451 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007452 return false; // Do not delete arguments unless we have a function body...
7453
7454 // Okay, we decided that this is a safe thing to do: go ahead and start
7455 // inserting cast instructions as necessary...
7456 std::vector<Value*> Args;
7457 Args.reserve(NumActualArgs);
7458
7459 AI = CS.arg_begin();
7460 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7461 const Type *ParamTy = FT->getParamType(i);
7462 if ((*AI)->getType() == ParamTy) {
7463 Args.push_back(*AI);
7464 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007465 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007466 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007467 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007468 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007469 }
7470 }
7471
7472 // If the function takes more arguments than the call was taking, add them
7473 // now...
7474 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7475 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7476
7477 // If we are removing arguments to the function, emit an obnoxious warning...
7478 if (FT->getNumParams() < NumActualArgs)
7479 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007480 cerr << "WARNING: While resolving call to function '"
7481 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007482 } else {
7483 // Add all of the arguments in their promoted form to the arg list...
7484 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7485 const Type *PTy = getPromotedType((*AI)->getType());
7486 if (PTy != (*AI)->getType()) {
7487 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007488 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7489 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007490 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007491 InsertNewInstBefore(Cast, *Caller);
7492 Args.push_back(Cast);
7493 } else {
7494 Args.push_back(*AI);
7495 }
7496 }
7497 }
7498
7499 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007500 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007501
7502 Instruction *NC;
7503 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007504 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007505 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007506 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007507 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007508 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007509 if (cast<CallInst>(Caller)->isTailCall())
7510 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007511 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007512 }
7513
Chris Lattner6e0123b2007-02-11 01:23:03 +00007514 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007515 Value *NV = NC;
7516 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7517 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007518 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007519 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7520 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007521 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007522
7523 // If this is an invoke instruction, we should insert it after the first
7524 // non-phi, instruction in the normal successor block.
7525 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7526 BasicBlock::iterator I = II->getNormalDest()->begin();
7527 while (isa<PHINode>(I)) ++I;
7528 InsertNewInstBefore(NC, *I);
7529 } else {
7530 // Otherwise, it's a call, just insert cast right after the call instr
7531 InsertNewInstBefore(NC, *Caller);
7532 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007533 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007534 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007535 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007536 }
7537 }
7538
7539 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7540 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007541 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007542 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007543 return true;
7544}
7545
Chris Lattnercadac0c2006-11-01 04:51:18 +00007546/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7547/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7548/// and a single binop.
7549Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7550 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007551 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7552 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007553 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007554 Value *LHSVal = FirstInst->getOperand(0);
7555 Value *RHSVal = FirstInst->getOperand(1);
7556
7557 const Type *LHSType = LHSVal->getType();
7558 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007559
7560 // Scan to see if all operands are the same opcode, all have one use, and all
7561 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007562 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007563 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007564 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007565 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007566 // types or GEP's with different index types.
7567 I->getOperand(0)->getType() != LHSType ||
7568 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007569 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007570
7571 // If they are CmpInst instructions, check their predicates
7572 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7573 if (cast<CmpInst>(I)->getPredicate() !=
7574 cast<CmpInst>(FirstInst)->getPredicate())
7575 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007576
7577 // Keep track of which operand needs a phi node.
7578 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7579 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007580 }
7581
Chris Lattner4f218d52006-11-08 19:42:28 +00007582 // Otherwise, this is safe to transform, determine if it is profitable.
7583
7584 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7585 // Indexes are often folded into load/store instructions, so we don't want to
7586 // hide them behind a phi.
7587 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7588 return 0;
7589
Chris Lattnercadac0c2006-11-01 04:51:18 +00007590 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007591 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007592 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007593 if (LHSVal == 0) {
7594 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7595 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7596 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007597 InsertNewInstBefore(NewLHS, PN);
7598 LHSVal = NewLHS;
7599 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007600
7601 if (RHSVal == 0) {
7602 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7603 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7604 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007605 InsertNewInstBefore(NewRHS, PN);
7606 RHSVal = NewRHS;
7607 }
7608
Chris Lattnercd62f112006-11-08 19:29:23 +00007609 // Add all operands to the new PHIs.
7610 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7611 if (NewLHS) {
7612 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7613 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7614 }
7615 if (NewRHS) {
7616 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7617 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7618 }
7619 }
7620
Chris Lattnercadac0c2006-11-01 04:51:18 +00007621 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007622 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007623 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7624 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7625 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007626 else {
7627 assert(isa<GetElementPtrInst>(FirstInst));
7628 return new GetElementPtrInst(LHSVal, RHSVal);
7629 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007630}
7631
Chris Lattner14f82c72006-11-01 07:13:54 +00007632/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7633/// of the block that defines it. This means that it must be obvious the value
7634/// of the load is not changed from the point of the load to the end of the
7635/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007636///
7637/// Finally, it is safe, but not profitable, to sink a load targetting a
7638/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7639/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007640static bool isSafeToSinkLoad(LoadInst *L) {
7641 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7642
7643 for (++BBI; BBI != E; ++BBI)
7644 if (BBI->mayWriteToMemory())
7645 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007646
7647 // Check for non-address taken alloca. If not address-taken already, it isn't
7648 // profitable to do this xform.
7649 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7650 bool isAddressTaken = false;
7651 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7652 UI != E; ++UI) {
7653 if (isa<LoadInst>(UI)) continue;
7654 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7655 // If storing TO the alloca, then the address isn't taken.
7656 if (SI->getOperand(1) == AI) continue;
7657 }
7658 isAddressTaken = true;
7659 break;
7660 }
7661
7662 if (!isAddressTaken)
7663 return false;
7664 }
7665
Chris Lattner14f82c72006-11-01 07:13:54 +00007666 return true;
7667}
7668
Chris Lattner970c33a2003-06-19 17:00:31 +00007669
Chris Lattner7515cab2004-11-14 19:13:23 +00007670// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7671// operator and they all are only used by the PHI, PHI together their
7672// inputs, and do the operation once, to the result of the PHI.
7673Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7674 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7675
7676 // Scan the instruction, looking for input operations that can be folded away.
7677 // If all input operands to the phi are the same instruction (e.g. a cast from
7678 // the same type or "+42") we can pull the operation through the PHI, reducing
7679 // code size and simplifying code.
7680 Constant *ConstantOp = 0;
7681 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007682 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007683 if (isa<CastInst>(FirstInst)) {
7684 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007685 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007686 // Can fold binop, compare or shift here if the RHS is a constant,
7687 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007688 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007689 if (ConstantOp == 0)
7690 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007691 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7692 isVolatile = LI->isVolatile();
7693 // We can't sink the load if the loaded value could be modified between the
7694 // load and the PHI.
7695 if (LI->getParent() != PN.getIncomingBlock(0) ||
7696 !isSafeToSinkLoad(LI))
7697 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007698 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007699 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007700 return FoldPHIArgBinOpIntoPHI(PN);
7701 // Can't handle general GEPs yet.
7702 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007703 } else {
7704 return 0; // Cannot fold this operation.
7705 }
7706
7707 // Check to see if all arguments are the same operation.
7708 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7709 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7710 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007711 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007712 return 0;
7713 if (CastSrcTy) {
7714 if (I->getOperand(0)->getType() != CastSrcTy)
7715 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007716 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007717 // We can't sink the load if the loaded value could be modified between
7718 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007719 if (LI->isVolatile() != isVolatile ||
7720 LI->getParent() != PN.getIncomingBlock(i) ||
7721 !isSafeToSinkLoad(LI))
7722 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007723 } else if (I->getOperand(1) != ConstantOp) {
7724 return 0;
7725 }
7726 }
7727
7728 // Okay, they are all the same operation. Create a new PHI node of the
7729 // correct type, and PHI together all of the LHS's of the instructions.
7730 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7731 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007732 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007733
7734 Value *InVal = FirstInst->getOperand(0);
7735 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007736
7737 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007738 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7739 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7740 if (NewInVal != InVal)
7741 InVal = 0;
7742 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7743 }
7744
7745 Value *PhiVal;
7746 if (InVal) {
7747 // The new PHI unions all of the same values together. This is really
7748 // common, so we handle it intelligently here for compile-time speed.
7749 PhiVal = InVal;
7750 delete NewPN;
7751 } else {
7752 InsertNewInstBefore(NewPN, PN);
7753 PhiVal = NewPN;
7754 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007755
Chris Lattner7515cab2004-11-14 19:13:23 +00007756 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007757 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7758 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007759 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007760 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007761 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007762 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007763 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7764 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7765 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007766 else
Reid Spencer2341c222007-02-02 02:16:23 +00007767 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007768 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007769}
Chris Lattner48a44f72002-05-02 17:06:02 +00007770
Chris Lattner71536432005-01-17 05:10:15 +00007771/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7772/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007773static bool DeadPHICycle(PHINode *PN,
7774 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00007775 if (PN->use_empty()) return true;
7776 if (!PN->hasOneUse()) return false;
7777
7778 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007779 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00007780 return true;
7781
7782 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7783 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007784
Chris Lattner71536432005-01-17 05:10:15 +00007785 return false;
7786}
7787
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007788// PHINode simplification
7789//
Chris Lattner113f4f42002-06-25 16:13:24 +00007790Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007791 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007792 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007793
Owen Andersonae8aa642006-07-10 22:03:18 +00007794 if (Value *V = PN.hasConstantValue())
7795 return ReplaceInstUsesWith(PN, V);
7796
Owen Andersonae8aa642006-07-10 22:03:18 +00007797 // If all PHI operands are the same operation, pull them through the PHI,
7798 // reducing code size.
7799 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7800 PN.getIncomingValue(0)->hasOneUse())
7801 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7802 return Result;
7803
7804 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7805 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7806 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007807 if (PN.hasOneUse()) {
7808 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7809 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00007810 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00007811 PotentiallyDeadPHIs.insert(&PN);
7812 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7813 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7814 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007815
7816 // If this phi has a single use, and if that use just computes a value for
7817 // the next iteration of a loop, delete the phi. This occurs with unused
7818 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7819 // common case here is good because the only other things that catch this
7820 // are induction variable analysis (sometimes) and ADCE, which is only run
7821 // late.
7822 if (PHIUser->hasOneUse() &&
7823 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7824 PHIUser->use_back() == &PN) {
7825 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7826 }
7827 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007828
Chris Lattner91daeb52003-12-19 05:58:40 +00007829 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007830}
7831
Reid Spencer13bc5d72006-12-12 09:18:51 +00007832static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7833 Instruction *InsertPoint,
7834 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007835 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7836 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007837 // We must cast correctly to the pointer type. Ensure that we
7838 // sign extend the integer value if it is smaller as this is
7839 // used for address computation.
7840 Instruction::CastOps opcode =
7841 (VTySize < PtrSize ? Instruction::SExt :
7842 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7843 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007844}
7845
Chris Lattner48a44f72002-05-02 17:06:02 +00007846
Chris Lattner113f4f42002-06-25 16:13:24 +00007847Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007848 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007849 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007850 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007851 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007852 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007853
Chris Lattner81a7a232004-10-16 18:11:37 +00007854 if (isa<UndefValue>(GEP.getOperand(0)))
7855 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7856
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007857 bool HasZeroPointerIndex = false;
7858 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7859 HasZeroPointerIndex = C->isNullValue();
7860
7861 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007862 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007863
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007864 // Keep track of whether all indices are zero constants integers.
7865 bool AllZeroIndices = true;
7866
Chris Lattner69193f92004-04-05 01:30:19 +00007867 // Eliminate unneeded casts for indices.
7868 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007869
Chris Lattner2b2412d2004-04-07 18:38:20 +00007870 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007871 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
7872 // Track whether this GEP has all zero indices, if so, it doesn't move the
7873 // input pointer, it just changes its type.
7874 if (AllZeroIndices) {
7875 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
7876 AllZeroIndices = CI->isNullValue();
7877 else
7878 AllZeroIndices = false;
7879 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007880 if (isa<SequentialType>(*GTI)) {
7881 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007882 if (CI->getOpcode() == Instruction::ZExt ||
7883 CI->getOpcode() == Instruction::SExt) {
7884 const Type *SrcTy = CI->getOperand(0)->getType();
7885 // We can eliminate a cast from i32 to i64 iff the target
7886 // is a 32-bit pointer target.
7887 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7888 MadeChange = true;
7889 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007890 }
7891 }
7892 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007893 // If we are using a wider index than needed for this platform, shrink it
7894 // to what we need. If the incoming value needs a cast instruction,
7895 // insert it. This explicit cast can make subsequent optimizations more
7896 // obvious.
7897 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007898 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007899 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007900 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007901 MadeChange = true;
7902 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007903 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7904 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007905 GEP.setOperand(i, Op);
7906 MadeChange = true;
7907 }
Chris Lattner69193f92004-04-05 01:30:19 +00007908 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007909 }
Chris Lattner69193f92004-04-05 01:30:19 +00007910 if (MadeChange) return &GEP;
7911
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007912 // If this GEP instruction doesn't move the pointer, and if the input operand
7913 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
7914 // real input to the dest type.
7915 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
7916 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
7917 GEP.getType());
7918
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007919 // Combine Indices - If the source pointer to this getelementptr instruction
7920 // is a getelementptr instruction, combine the indices of the two
7921 // getelementptr instructions into a single instruction.
7922 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007923 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007924 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007925 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007926
7927 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007928 // Note that if our source is a gep chain itself that we wait for that
7929 // chain to be resolved before we perform this transformation. This
7930 // avoids us creating a TON of code in some cases.
7931 //
7932 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7933 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7934 return 0; // Wait until our source is folded to completion.
7935
Chris Lattneraf6094f2007-02-15 22:48:32 +00007936 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007937
7938 // Find out whether the last index in the source GEP is a sequential idx.
7939 bool EndsWithSequential = false;
7940 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7941 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007942 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007943
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007944 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007945 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007946 // Replace: gep (gep %P, long B), long A, ...
7947 // With: T = long A+B; gep %P, T, ...
7948 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007949 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007950 if (SO1 == Constant::getNullValue(SO1->getType())) {
7951 Sum = GO1;
7952 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7953 Sum = SO1;
7954 } else {
7955 // If they aren't the same type, convert both to an integer of the
7956 // target's pointer size.
7957 if (SO1->getType() != GO1->getType()) {
7958 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007959 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007960 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007961 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007962 } else {
7963 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007964 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007965 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007966 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007967
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007968 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007969 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007970 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007971 } else {
7972 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007973 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7974 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007975 }
7976 }
7977 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007978 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7979 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7980 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007981 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7982 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007983 }
Chris Lattner69193f92004-04-05 01:30:19 +00007984 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007985
7986 // Recycle the GEP we already have if possible.
7987 if (SrcGEPOperands.size() == 2) {
7988 GEP.setOperand(0, SrcGEPOperands[0]);
7989 GEP.setOperand(1, Sum);
7990 return &GEP;
7991 } else {
7992 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7993 SrcGEPOperands.end()-1);
7994 Indices.push_back(Sum);
7995 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7996 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007997 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007998 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007999 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008000 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008001 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8002 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008003 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8004 }
8005
8006 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008007 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8008 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008009
Chris Lattner5f667a62004-05-07 22:09:22 +00008010 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008011 // GEP of global variable. If all of the indices for this GEP are
8012 // constants, we can promote this to a constexpr instead of an instruction.
8013
8014 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008015 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008016 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8017 for (; I != E && isa<Constant>(*I); ++I)
8018 Indices.push_back(cast<Constant>(*I));
8019
8020 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008021 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8022 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008023
8024 // Replace all uses of the GEP with the new constexpr...
8025 return ReplaceInstUsesWith(GEP, CE);
8026 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008027 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008028 if (!isa<PointerType>(X->getType())) {
8029 // Not interesting. Source pointer must be a cast from pointer.
8030 } else if (HasZeroPointerIndex) {
8031 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8032 // into : GEP [10 x ubyte]* X, long 0, ...
8033 //
8034 // This occurs when the program declares an array extern like "int X[];"
8035 //
8036 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8037 const PointerType *XTy = cast<PointerType>(X->getType());
8038 if (const ArrayType *XATy =
8039 dyn_cast<ArrayType>(XTy->getElementType()))
8040 if (const ArrayType *CATy =
8041 dyn_cast<ArrayType>(CPTy->getElementType()))
8042 if (CATy->getElementType() == XATy->getElementType()) {
8043 // At this point, we know that the cast source type is a pointer
8044 // to an array of the same type as the destination pointer
8045 // array. Because the array type is never stepped over (there
8046 // is a leading zero) we can fold the cast into this GEP.
8047 GEP.setOperand(0, X);
8048 return &GEP;
8049 }
8050 } else if (GEP.getNumOperands() == 2) {
8051 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008052 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8053 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008054 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8055 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8056 if (isa<ArrayType>(SrcElTy) &&
8057 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8058 TD->getTypeSize(ResElTy)) {
8059 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008060 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008061 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008062 // V and GEP are both pointer types --> BitCast
8063 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008064 }
Chris Lattner2a893292005-09-13 18:36:04 +00008065
8066 // Transform things like:
8067 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8068 // (where tmp = 8*tmp2) into:
8069 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8070
8071 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008072 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008073 uint64_t ArrayEltSize =
8074 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8075
8076 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8077 // allow either a mul, shift, or constant here.
8078 Value *NewIdx = 0;
8079 ConstantInt *Scale = 0;
8080 if (ArrayEltSize == 1) {
8081 NewIdx = GEP.getOperand(1);
8082 Scale = ConstantInt::get(NewIdx->getType(), 1);
8083 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008084 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008085 Scale = CI;
8086 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8087 if (Inst->getOpcode() == Instruction::Shl &&
8088 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00008089 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8090 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8091 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +00008092 NewIdx = Inst->getOperand(0);
8093 } else if (Inst->getOpcode() == Instruction::Mul &&
8094 isa<ConstantInt>(Inst->getOperand(1))) {
8095 Scale = cast<ConstantInt>(Inst->getOperand(1));
8096 NewIdx = Inst->getOperand(0);
8097 }
8098 }
8099
8100 // If the index will be to exactly the right offset with the scale taken
8101 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008102 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008103 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008104 Scale = ConstantInt::get(Scale->getType(),
8105 Scale->getZExtValue() / ArrayEltSize);
8106 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008107 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8108 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008109 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8110 NewIdx = InsertNewInstBefore(Sc, GEP);
8111 }
8112
8113 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008114 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008115 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008116 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008117 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8118 // The NewGEP must be pointer typed, so must the old one -> BitCast
8119 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008120 }
8121 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008122 }
Chris Lattnerca081252001-12-14 16:52:21 +00008123 }
8124
Chris Lattnerca081252001-12-14 16:52:21 +00008125 return 0;
8126}
8127
Chris Lattner1085bdf2002-11-04 16:18:53 +00008128Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8129 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8130 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008131 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8132 const Type *NewTy =
8133 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008134 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008135
8136 // Create and insert the replacement instruction...
8137 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008138 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008139 else {
8140 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008141 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008142 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008143
8144 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008145
Chris Lattner1085bdf2002-11-04 16:18:53 +00008146 // Scan to the end of the allocation instructions, to skip over a block of
8147 // allocas if possible...
8148 //
8149 BasicBlock::iterator It = New;
8150 while (isa<AllocationInst>(*It)) ++It;
8151
8152 // Now that I is pointing to the first non-allocation-inst in the block,
8153 // insert our getelementptr instruction...
8154 //
Reid Spencerc635f472006-12-31 05:48:39 +00008155 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008156 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8157 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008158
8159 // Now make everything use the getelementptr instead of the original
8160 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008161 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008162 } else if (isa<UndefValue>(AI.getArraySize())) {
8163 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008164 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008165
8166 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8167 // Note that we only do this for alloca's, because malloc should allocate and
8168 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008169 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008170 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008171 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8172
Chris Lattner1085bdf2002-11-04 16:18:53 +00008173 return 0;
8174}
8175
Chris Lattner8427bff2003-12-07 01:24:23 +00008176Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8177 Value *Op = FI.getOperand(0);
8178
8179 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8180 if (CastInst *CI = dyn_cast<CastInst>(Op))
8181 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8182 FI.setOperand(0, CI->getOperand(0));
8183 return &FI;
8184 }
8185
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008186 // free undef -> unreachable.
8187 if (isa<UndefValue>(Op)) {
8188 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008189 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008190 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008191 return EraseInstFromFunction(FI);
8192 }
8193
Chris Lattnerf3a36602004-02-28 04:57:37 +00008194 // If we have 'free null' delete the instruction. This can happen in stl code
8195 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008196 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008197 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008198
Chris Lattner8427bff2003-12-07 01:24:23 +00008199 return 0;
8200}
8201
8202
Chris Lattner72684fe2005-01-31 05:51:45 +00008203/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008204static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8205 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008206 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008207
8208 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008209 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008210 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008211
Reid Spencer31a4ef42007-01-22 05:51:25 +00008212 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008213 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008214 // If the source is an array, the code below will not succeed. Check to
8215 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8216 // constants.
8217 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8218 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8219 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008220 Value *Idxs[2];
8221 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8222 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008223 SrcTy = cast<PointerType>(CastOp->getType());
8224 SrcPTy = SrcTy->getElementType();
8225 }
8226
Reid Spencer31a4ef42007-01-22 05:51:25 +00008227 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008228 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008229 // Do not allow turning this into a load of an integer, which is then
8230 // casted to a pointer, this pessimizes pointer analysis a lot.
8231 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008232 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8233 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008234
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008235 // Okay, we are casting from one integer or pointer type to another of
8236 // the same size. Instead of casting the pointer before the load, cast
8237 // the result of the loaded value.
8238 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8239 CI->getName(),
8240 LI.isVolatile()),LI);
8241 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008242 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008243 }
Chris Lattner35e24772004-07-13 01:49:43 +00008244 }
8245 }
8246 return 0;
8247}
8248
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008249/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008250/// from this value cannot trap. If it is not obviously safe to load from the
8251/// specified pointer, we do a quick local scan of the basic block containing
8252/// ScanFrom, to determine if the address is already accessed.
8253static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8254 // If it is an alloca or global variable, it is always safe to load from.
8255 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8256
8257 // Otherwise, be a little bit agressive by scanning the local block where we
8258 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008259 // from/to. If so, the previous load or store would have already trapped,
8260 // so there is no harm doing an extra load (also, CSE will later eliminate
8261 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008262 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8263
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008264 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008265 --BBI;
8266
8267 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8268 if (LI->getOperand(0) == V) return true;
8269 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8270 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008271
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008272 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008273 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008274}
8275
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008276Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8277 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008278
Chris Lattnera9d84e32005-05-01 04:24:53 +00008279 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008280 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008281 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8282 return Res;
8283
8284 // None of the following transforms are legal for volatile loads.
8285 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008286
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008287 if (&LI.getParent()->front() != &LI) {
8288 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008289 // If the instruction immediately before this is a store to the same
8290 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008291 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8292 if (SI->getOperand(1) == LI.getOperand(0))
8293 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008294 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8295 if (LIB->getOperand(0) == LI.getOperand(0))
8296 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008297 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008298
8299 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8300 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8301 isa<UndefValue>(GEPI->getOperand(0))) {
8302 // Insert a new store to null instruction before the load to indicate
8303 // that this code is not reachable. We do this instead of inserting
8304 // an unreachable instruction directly because we cannot modify the
8305 // CFG.
8306 new StoreInst(UndefValue::get(LI.getType()),
8307 Constant::getNullValue(Op->getType()), &LI);
8308 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8309 }
8310
Chris Lattner81a7a232004-10-16 18:11:37 +00008311 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008312 // load null/undef -> undef
8313 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008314 // Insert a new store to null instruction before the load to indicate that
8315 // this code is not reachable. We do this instead of inserting an
8316 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008317 new StoreInst(UndefValue::get(LI.getType()),
8318 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008319 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008320 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008321
Chris Lattner81a7a232004-10-16 18:11:37 +00008322 // Instcombine load (constant global) into the value loaded.
8323 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008324 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008325 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008326
Chris Lattner81a7a232004-10-16 18:11:37 +00008327 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8329 if (CE->getOpcode() == Instruction::GetElementPtr) {
8330 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008331 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008332 if (Constant *V =
8333 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008334 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008335 if (CE->getOperand(0)->isNullValue()) {
8336 // Insert a new store to null instruction before the load to indicate
8337 // that this code is not reachable. We do this instead of inserting
8338 // an unreachable instruction directly because we cannot modify the
8339 // CFG.
8340 new StoreInst(UndefValue::get(LI.getType()),
8341 Constant::getNullValue(Op->getType()), &LI);
8342 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8343 }
8344
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008345 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008346 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8347 return Res;
8348 }
8349 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008350
Chris Lattnera9d84e32005-05-01 04:24:53 +00008351 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008352 // Change select and PHI nodes to select values instead of addresses: this
8353 // helps alias analysis out a lot, allows many others simplifications, and
8354 // exposes redundancy in the code.
8355 //
8356 // Note that we cannot do the transformation unless we know that the
8357 // introduced loads cannot trap! Something like this is valid as long as
8358 // the condition is always false: load (select bool %C, int* null, int* %G),
8359 // but it would not be valid if we transformed it to load from null
8360 // unconditionally.
8361 //
8362 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8363 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008364 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8365 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008366 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008367 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008368 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008369 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008370 return new SelectInst(SI->getCondition(), V1, V2);
8371 }
8372
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008373 // load (select (cond, null, P)) -> load P
8374 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8375 if (C->isNullValue()) {
8376 LI.setOperand(0, SI->getOperand(2));
8377 return &LI;
8378 }
8379
8380 // load (select (cond, P, null)) -> load P
8381 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8382 if (C->isNullValue()) {
8383 LI.setOperand(0, SI->getOperand(1));
8384 return &LI;
8385 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008386 }
8387 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008388 return 0;
8389}
8390
Reid Spencere928a152007-01-19 21:20:31 +00008391/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008392/// when possible.
8393static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8394 User *CI = cast<User>(SI.getOperand(1));
8395 Value *CastOp = CI->getOperand(0);
8396
8397 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8398 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8399 const Type *SrcPTy = SrcTy->getElementType();
8400
Reid Spencer31a4ef42007-01-22 05:51:25 +00008401 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008402 // If the source is an array, the code below will not succeed. Check to
8403 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8404 // constants.
8405 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8406 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8407 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008408 Value* Idxs[2];
8409 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8410 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008411 SrcTy = cast<PointerType>(CastOp->getType());
8412 SrcPTy = SrcTy->getElementType();
8413 }
8414
Reid Spencer9a4bed02007-01-20 23:35:48 +00008415 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8416 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8417 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008418
8419 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008420 // the same size. Instead of casting the pointer before
8421 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008422 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008423 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008424 Instruction::CastOps opcode = Instruction::BitCast;
8425 const Type* CastSrcTy = SIOp0->getType();
8426 const Type* CastDstTy = SrcPTy;
8427 if (isa<PointerType>(CastDstTy)) {
8428 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008429 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008430 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008431 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008432 opcode = Instruction::PtrToInt;
8433 }
8434 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008435 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008436 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008437 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008438 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8439 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008440 return new StoreInst(NewCast, CastOp);
8441 }
8442 }
8443 }
8444 return 0;
8445}
8446
Chris Lattner31f486c2005-01-31 05:36:43 +00008447Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8448 Value *Val = SI.getOperand(0);
8449 Value *Ptr = SI.getOperand(1);
8450
8451 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008452 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008453 ++NumCombined;
8454 return 0;
8455 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008456
8457 // If the RHS is an alloca with a single use, zapify the store, making the
8458 // alloca dead.
8459 if (Ptr->hasOneUse()) {
8460 if (isa<AllocaInst>(Ptr)) {
8461 EraseInstFromFunction(SI);
8462 ++NumCombined;
8463 return 0;
8464 }
8465
8466 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8467 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8468 GEP->getOperand(0)->hasOneUse()) {
8469 EraseInstFromFunction(SI);
8470 ++NumCombined;
8471 return 0;
8472 }
8473 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008474
Chris Lattner5997cf92006-02-08 03:25:32 +00008475 // Do really simple DSE, to catch cases where there are several consequtive
8476 // stores to the same location, separated by a few arithmetic operations. This
8477 // situation often occurs with bitfield accesses.
8478 BasicBlock::iterator BBI = &SI;
8479 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8480 --ScanInsts) {
8481 --BBI;
8482
8483 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8484 // Prev store isn't volatile, and stores to the same location?
8485 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8486 ++NumDeadStore;
8487 ++BBI;
8488 EraseInstFromFunction(*PrevSI);
8489 continue;
8490 }
8491 break;
8492 }
8493
Chris Lattnerdab43b22006-05-26 19:19:20 +00008494 // If this is a load, we have to stop. However, if the loaded value is from
8495 // the pointer we're loading and is producing the pointer we're storing,
8496 // then *this* store is dead (X = load P; store X -> P).
8497 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8498 if (LI == Val && LI->getOperand(0) == Ptr) {
8499 EraseInstFromFunction(SI);
8500 ++NumCombined;
8501 return 0;
8502 }
8503 // Otherwise, this is a load from some other location. Stores before it
8504 // may not be dead.
8505 break;
8506 }
8507
Chris Lattner5997cf92006-02-08 03:25:32 +00008508 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008509 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008510 break;
8511 }
8512
8513
8514 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008515
8516 // store X, null -> turns into 'unreachable' in SimplifyCFG
8517 if (isa<ConstantPointerNull>(Ptr)) {
8518 if (!isa<UndefValue>(Val)) {
8519 SI.setOperand(0, UndefValue::get(Val->getType()));
8520 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008521 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008522 ++NumCombined;
8523 }
8524 return 0; // Do not modify these!
8525 }
8526
8527 // store undef, Ptr -> noop
8528 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008529 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008530 ++NumCombined;
8531 return 0;
8532 }
8533
Chris Lattner72684fe2005-01-31 05:51:45 +00008534 // If the pointer destination is a cast, see if we can fold the cast into the
8535 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008536 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008537 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8538 return Res;
8539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008540 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008541 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8542 return Res;
8543
Chris Lattner219175c2005-09-12 23:23:25 +00008544
8545 // If this store is the last instruction in the basic block, and if the block
8546 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008547 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008548 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8549 if (BI->isUnconditional()) {
8550 // Check to see if the successor block has exactly two incoming edges. If
8551 // so, see if the other predecessor contains a store to the same location.
8552 // if so, insert a PHI node (if needed) and move the stores down.
8553 BasicBlock *Dest = BI->getSuccessor(0);
8554
8555 pred_iterator PI = pred_begin(Dest);
8556 BasicBlock *Other = 0;
8557 if (*PI != BI->getParent())
8558 Other = *PI;
8559 ++PI;
8560 if (PI != pred_end(Dest)) {
8561 if (*PI != BI->getParent())
8562 if (Other)
8563 Other = 0;
8564 else
8565 Other = *PI;
8566 if (++PI != pred_end(Dest))
8567 Other = 0;
8568 }
8569 if (Other) { // If only one other pred...
8570 BBI = Other->getTerminator();
8571 // Make sure this other block ends in an unconditional branch and that
8572 // there is an instruction before the branch.
8573 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8574 BBI != Other->begin()) {
8575 --BBI;
8576 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8577
8578 // If this instruction is a store to the same location.
8579 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8580 // Okay, we know we can perform this transformation. Insert a PHI
8581 // node now if we need it.
8582 Value *MergedVal = OtherStore->getOperand(0);
8583 if (MergedVal != SI.getOperand(0)) {
8584 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8585 PN->reserveOperandSpace(2);
8586 PN->addIncoming(SI.getOperand(0), SI.getParent());
8587 PN->addIncoming(OtherStore->getOperand(0), Other);
8588 MergedVal = InsertNewInstBefore(PN, Dest->front());
8589 }
8590
8591 // Advance to a place where it is safe to insert the new store and
8592 // insert it.
8593 BBI = Dest->begin();
8594 while (isa<PHINode>(BBI)) ++BBI;
8595 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8596 OtherStore->isVolatile()), *BBI);
8597
8598 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008599 EraseInstFromFunction(SI);
8600 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008601 ++NumCombined;
8602 return 0;
8603 }
8604 }
8605 }
8606 }
8607
Chris Lattner31f486c2005-01-31 05:36:43 +00008608 return 0;
8609}
8610
8611
Chris Lattner9eef8a72003-06-04 04:46:00 +00008612Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8613 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008614 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008615 BasicBlock *TrueDest;
8616 BasicBlock *FalseDest;
8617 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8618 !isa<Constant>(X)) {
8619 // Swap Destinations and condition...
8620 BI.setCondition(X);
8621 BI.setSuccessor(0, FalseDest);
8622 BI.setSuccessor(1, TrueDest);
8623 return &BI;
8624 }
8625
Reid Spencer266e42b2006-12-23 06:05:41 +00008626 // Cannonicalize fcmp_one -> fcmp_oeq
8627 FCmpInst::Predicate FPred; Value *Y;
8628 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8629 TrueDest, FalseDest)))
8630 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8631 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8632 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008633 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008634 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8635 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008636 // Swap Destinations and condition...
8637 BI.setCondition(NewSCC);
8638 BI.setSuccessor(0, FalseDest);
8639 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008640 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008641 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008642 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008643 return &BI;
8644 }
8645
8646 // Cannonicalize icmp_ne -> icmp_eq
8647 ICmpInst::Predicate IPred;
8648 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8649 TrueDest, FalseDest)))
8650 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8651 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8652 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8653 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008654 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008655 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8656 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008657 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008658 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008659 BI.setSuccessor(0, FalseDest);
8660 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008661 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008662 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008663 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008664 return &BI;
8665 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008666
Chris Lattner9eef8a72003-06-04 04:46:00 +00008667 return 0;
8668}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008669
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008670Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8671 Value *Cond = SI.getCondition();
8672 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8673 if (I->getOpcode() == Instruction::Add)
8674 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8675 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8676 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008677 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008678 AddRHS));
8679 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008680 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008681 return &SI;
8682 }
8683 }
8684 return 0;
8685}
8686
Chris Lattner6bc98652006-03-05 00:22:33 +00008687/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8688/// is to leave as a vector operation.
8689static bool CheapToScalarize(Value *V, bool isConstant) {
8690 if (isa<ConstantAggregateZero>(V))
8691 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008692 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008693 if (isConstant) return true;
8694 // If all elts are the same, we can extract.
8695 Constant *Op0 = C->getOperand(0);
8696 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8697 if (C->getOperand(i) != Op0)
8698 return false;
8699 return true;
8700 }
8701 Instruction *I = dyn_cast<Instruction>(V);
8702 if (!I) return false;
8703
8704 // Insert element gets simplified to the inserted element or is deleted if
8705 // this is constant idx extract element and its a constant idx insertelt.
8706 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8707 isa<ConstantInt>(I->getOperand(2)))
8708 return true;
8709 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8710 return true;
8711 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8712 if (BO->hasOneUse() &&
8713 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8714 CheapToScalarize(BO->getOperand(1), isConstant)))
8715 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008716 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8717 if (CI->hasOneUse() &&
8718 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8719 CheapToScalarize(CI->getOperand(1), isConstant)))
8720 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008721
8722 return false;
8723}
8724
Chris Lattner945e4372007-02-14 05:52:17 +00008725/// Read and decode a shufflevector mask.
8726///
8727/// It turns undef elements into values that are larger than the number of
8728/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008729static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8730 unsigned NElts = SVI->getType()->getNumElements();
8731 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8732 return std::vector<unsigned>(NElts, 0);
8733 if (isa<UndefValue>(SVI->getOperand(2)))
8734 return std::vector<unsigned>(NElts, 2*NElts);
8735
8736 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008737 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008738 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8739 if (isa<UndefValue>(CP->getOperand(i)))
8740 Result.push_back(NElts*2); // undef -> 8
8741 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008742 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008743 return Result;
8744}
8745
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008746/// FindScalarElement - Given a vector and an element number, see if the scalar
8747/// value is already around as a register, for example if it were inserted then
8748/// extracted from the vector.
8749static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008750 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8751 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008752 unsigned Width = PTy->getNumElements();
8753 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008754 return UndefValue::get(PTy->getElementType());
8755
8756 if (isa<UndefValue>(V))
8757 return UndefValue::get(PTy->getElementType());
8758 else if (isa<ConstantAggregateZero>(V))
8759 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008760 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008761 return CP->getOperand(EltNo);
8762 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8763 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008764 if (!isa<ConstantInt>(III->getOperand(2)))
8765 return 0;
8766 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008767
8768 // If this is an insert to the element we are looking for, return the
8769 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008770 if (EltNo == IIElt)
8771 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008772
8773 // Otherwise, the insertelement doesn't modify the value, recurse on its
8774 // vector input.
8775 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008776 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008777 unsigned InEl = getShuffleMask(SVI)[EltNo];
8778 if (InEl < Width)
8779 return FindScalarElement(SVI->getOperand(0), InEl);
8780 else if (InEl < Width*2)
8781 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8782 else
8783 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008784 }
8785
8786 // Otherwise, we don't know.
8787 return 0;
8788}
8789
Robert Bocchinoa8352962006-01-13 22:48:06 +00008790Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008791
Chris Lattner92346c32006-03-31 18:25:14 +00008792 // If packed val is undef, replace extract with scalar undef.
8793 if (isa<UndefValue>(EI.getOperand(0)))
8794 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8795
8796 // If packed val is constant 0, replace extract with scalar 0.
8797 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8798 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8799
Reid Spencerd84d35b2007-02-15 02:26:10 +00008800 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008801 // If packed val is constant with uniform operands, replace EI
8802 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008803 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008804 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008805 if (C->getOperand(i) != op0) {
8806 op0 = 0;
8807 break;
8808 }
8809 if (op0)
8810 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008811 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008812
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008813 // If extracting a specified index from the vector, see if we can recursively
8814 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008815 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008816 // This instruction only demands the single element from the input vector.
8817 // If the input vector has a single use, simplify it based on this use
8818 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008819 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008820 if (EI.getOperand(0)->hasOneUse()) {
8821 uint64_t UndefElts;
8822 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008823 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008824 UndefElts)) {
8825 EI.setOperand(0, V);
8826 return &EI;
8827 }
8828 }
8829
Reid Spencere0fc4df2006-10-20 07:07:24 +00008830 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008831 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008832 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008833
Chris Lattner83f65782006-05-25 22:53:38 +00008834 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008835 if (I->hasOneUse()) {
8836 // Push extractelement into predecessor operation if legal and
8837 // profitable to do so
8838 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008839 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8840 if (CheapToScalarize(BO, isConstantElt)) {
8841 ExtractElementInst *newEI0 =
8842 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8843 EI.getName()+".lhs");
8844 ExtractElementInst *newEI1 =
8845 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8846 EI.getName()+".rhs");
8847 InsertNewInstBefore(newEI0, EI);
8848 InsertNewInstBefore(newEI1, EI);
8849 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8850 }
Reid Spencerde46e482006-11-02 20:25:50 +00008851 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008852 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008853 PointerType::get(EI.getType()), EI);
8854 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008855 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008856 InsertNewInstBefore(GEP, EI);
8857 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008858 }
8859 }
8860 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8861 // Extracting the inserted element?
8862 if (IE->getOperand(2) == EI.getOperand(1))
8863 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8864 // If the inserted and extracted elements are constants, they must not
8865 // be the same value, extract from the pre-inserted value instead.
8866 if (isa<Constant>(IE->getOperand(2)) &&
8867 isa<Constant>(EI.getOperand(1))) {
8868 AddUsesToWorkList(EI);
8869 EI.setOperand(0, IE->getOperand(0));
8870 return &EI;
8871 }
8872 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8873 // If this is extracting an element from a shufflevector, figure out where
8874 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008875 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8876 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008877 Value *Src;
8878 if (SrcIdx < SVI->getType()->getNumElements())
8879 Src = SVI->getOperand(0);
8880 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8881 SrcIdx -= SVI->getType()->getNumElements();
8882 Src = SVI->getOperand(1);
8883 } else {
8884 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008885 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008886 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008887 }
8888 }
Chris Lattner83f65782006-05-25 22:53:38 +00008889 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008890 return 0;
8891}
8892
Chris Lattner90951862006-04-16 00:51:47 +00008893/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8894/// elements from either LHS or RHS, return the shuffle mask and true.
8895/// Otherwise, return false.
8896static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8897 std::vector<Constant*> &Mask) {
8898 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8899 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008900 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008901
8902 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008903 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008904 return true;
8905 } else if (V == LHS) {
8906 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008907 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008908 return true;
8909 } else if (V == RHS) {
8910 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008911 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008912 return true;
8913 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8914 // If this is an insert of an extract from some other vector, include it.
8915 Value *VecOp = IEI->getOperand(0);
8916 Value *ScalarOp = IEI->getOperand(1);
8917 Value *IdxOp = IEI->getOperand(2);
8918
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008919 if (!isa<ConstantInt>(IdxOp))
8920 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008921 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008922
8923 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8924 // Okay, we can handle this if the vector we are insertinting into is
8925 // transitively ok.
8926 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8927 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008928 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008929 return true;
8930 }
8931 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8932 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008933 EI->getOperand(0)->getType() == V->getType()) {
8934 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008935 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008936
8937 // This must be extracting from either LHS or RHS.
8938 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8939 // Okay, we can handle this if the vector we are insertinting into is
8940 // transitively ok.
8941 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8942 // If so, update the mask to reflect the inserted value.
8943 if (EI->getOperand(0) == LHS) {
8944 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008945 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008946 } else {
8947 assert(EI->getOperand(0) == RHS);
8948 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008949 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008950
8951 }
8952 return true;
8953 }
8954 }
8955 }
8956 }
8957 }
8958 // TODO: Handle shufflevector here!
8959
8960 return false;
8961}
8962
8963/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8964/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8965/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008966static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008967 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008968 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00008969 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008970 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008971 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00008972
8973 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008974 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008975 return V;
8976 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008977 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008978 return V;
8979 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8980 // If this is an insert of an extract from some other vector, include it.
8981 Value *VecOp = IEI->getOperand(0);
8982 Value *ScalarOp = IEI->getOperand(1);
8983 Value *IdxOp = IEI->getOperand(2);
8984
8985 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8986 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8987 EI->getOperand(0)->getType() == V->getType()) {
8988 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008989 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8990 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008991
8992 // Either the extracted from or inserted into vector must be RHSVec,
8993 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008994 if (EI->getOperand(0) == RHS || RHS == 0) {
8995 RHS = EI->getOperand(0);
8996 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008997 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008998 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008999 return V;
9000 }
9001
Chris Lattner90951862006-04-16 00:51:47 +00009002 if (VecOp == RHS) {
9003 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009004 // Everything but the extracted element is replaced with the RHS.
9005 for (unsigned i = 0; i != NumElts; ++i) {
9006 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009007 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009008 }
9009 return V;
9010 }
Chris Lattner90951862006-04-16 00:51:47 +00009011
9012 // If this insertelement is a chain that comes from exactly these two
9013 // vectors, return the vector and the effective shuffle.
9014 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9015 return EI->getOperand(0);
9016
Chris Lattner39fac442006-04-15 01:39:45 +00009017 }
9018 }
9019 }
Chris Lattner90951862006-04-16 00:51:47 +00009020 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009021
9022 // Otherwise, can't do anything fancy. Return an identity vector.
9023 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009024 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009025 return V;
9026}
9027
9028Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9029 Value *VecOp = IE.getOperand(0);
9030 Value *ScalarOp = IE.getOperand(1);
9031 Value *IdxOp = IE.getOperand(2);
9032
9033 // If the inserted element was extracted from some other vector, and if the
9034 // indexes are constant, try to turn this into a shufflevector operation.
9035 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9036 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9037 EI->getOperand(0)->getType() == IE.getType()) {
9038 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009039 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9040 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009041
9042 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9043 return ReplaceInstUsesWith(IE, VecOp);
9044
9045 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9046 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9047
9048 // If we are extracting a value from a vector, then inserting it right
9049 // back into the same place, just use the input vector.
9050 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9051 return ReplaceInstUsesWith(IE, VecOp);
9052
9053 // We could theoretically do this for ANY input. However, doing so could
9054 // turn chains of insertelement instructions into a chain of shufflevector
9055 // instructions, and right now we do not merge shufflevectors. As such,
9056 // only do this in a situation where it is clear that there is benefit.
9057 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9058 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9059 // the values of VecOp, except then one read from EIOp0.
9060 // Build a new shuffle mask.
9061 std::vector<Constant*> Mask;
9062 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009063 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009064 else {
9065 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009066 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009067 NumVectorElts));
9068 }
Reid Spencerc635f472006-12-31 05:48:39 +00009069 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009070 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009071 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009072 }
9073
9074 // If this insertelement isn't used by some other insertelement, turn it
9075 // (and any insertelements it points to), into one big shuffle.
9076 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9077 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009078 Value *RHS = 0;
9079 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9080 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9081 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009082 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009083 }
9084 }
9085 }
9086
9087 return 0;
9088}
9089
9090
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009091Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9092 Value *LHS = SVI.getOperand(0);
9093 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009094 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009095
9096 bool MadeChange = false;
9097
Chris Lattner2deeaea2006-10-05 06:55:50 +00009098 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009099 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009100 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9101
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009102 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009103 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009104 if (isa<UndefValue>(SVI.getOperand(1))) {
9105 // Scan to see if there are any references to the RHS. If so, replace them
9106 // with undef element refs and set MadeChange to true.
9107 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9108 if (Mask[i] >= e && Mask[i] != 2*e) {
9109 Mask[i] = 2*e;
9110 MadeChange = true;
9111 }
9112 }
9113
9114 if (MadeChange) {
9115 // Remap any references to RHS to use LHS.
9116 std::vector<Constant*> Elts;
9117 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9118 if (Mask[i] == 2*e)
9119 Elts.push_back(UndefValue::get(Type::Int32Ty));
9120 else
9121 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9122 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009123 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009124 }
9125 }
Chris Lattner39fac442006-04-15 01:39:45 +00009126
Chris Lattner12249be2006-05-25 23:48:38 +00009127 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9128 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9129 if (LHS == RHS || isa<UndefValue>(LHS)) {
9130 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009131 // shuffle(undef,undef,mask) -> undef.
9132 return ReplaceInstUsesWith(SVI, LHS);
9133 }
9134
Chris Lattner12249be2006-05-25 23:48:38 +00009135 // Remap any references to RHS to use LHS.
9136 std::vector<Constant*> Elts;
9137 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009138 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009139 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009140 else {
9141 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9142 (Mask[i] < e && isa<UndefValue>(LHS)))
9143 Mask[i] = 2*e; // Turn into undef.
9144 else
9145 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009146 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009147 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009148 }
Chris Lattner12249be2006-05-25 23:48:38 +00009149 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009150 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009151 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009152 LHS = SVI.getOperand(0);
9153 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009154 MadeChange = true;
9155 }
9156
Chris Lattner0e477162006-05-26 00:29:06 +00009157 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009158 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009159
Chris Lattner12249be2006-05-25 23:48:38 +00009160 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9161 if (Mask[i] >= e*2) continue; // Ignore undef values.
9162 // Is this an identity shuffle of the LHS value?
9163 isLHSID &= (Mask[i] == i);
9164
9165 // Is this an identity shuffle of the RHS value?
9166 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009167 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009168
Chris Lattner12249be2006-05-25 23:48:38 +00009169 // Eliminate identity shuffles.
9170 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9171 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009172
Chris Lattner0e477162006-05-26 00:29:06 +00009173 // If the LHS is a shufflevector itself, see if we can combine it with this
9174 // one without producing an unusual shuffle. Here we are really conservative:
9175 // we are absolutely afraid of producing a shuffle mask not in the input
9176 // program, because the code gen may not be smart enough to turn a merged
9177 // shuffle into two specific shuffles: it may produce worse code. As such,
9178 // we only merge two shuffles if the result is one of the two input shuffle
9179 // masks. In this case, merging the shuffles just removes one instruction,
9180 // which we know is safe. This is good for things like turning:
9181 // (splat(splat)) -> splat.
9182 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9183 if (isa<UndefValue>(RHS)) {
9184 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9185
9186 std::vector<unsigned> NewMask;
9187 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9188 if (Mask[i] >= 2*e)
9189 NewMask.push_back(2*e);
9190 else
9191 NewMask.push_back(LHSMask[Mask[i]]);
9192
9193 // If the result mask is equal to the src shuffle or this shuffle mask, do
9194 // the replacement.
9195 if (NewMask == LHSMask || NewMask == Mask) {
9196 std::vector<Constant*> Elts;
9197 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9198 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009199 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009200 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009201 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009202 }
9203 }
9204 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9205 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009206 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009207 }
9208 }
9209 }
Chris Lattner4284f642007-01-30 22:32:46 +00009210
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009211 return MadeChange ? &SVI : 0;
9212}
9213
9214
Robert Bocchinoa8352962006-01-13 22:48:06 +00009215
Chris Lattner39c98bb2004-12-08 23:43:58 +00009216
9217/// TryToSinkInstruction - Try to move the specified instruction from its
9218/// current block into the beginning of DestBlock, which can only happen if it's
9219/// safe to move the instruction past all of the instructions between it and the
9220/// end of its block.
9221static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9222 assert(I->hasOneUse() && "Invariants didn't hold!");
9223
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009224 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9225 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009226
Chris Lattner39c98bb2004-12-08 23:43:58 +00009227 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009228 if (isa<AllocaInst>(I) && I->getParent() ==
9229 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009230 return false;
9231
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009232 // We can only sink load instructions if there is nothing between the load and
9233 // the end of block that could change the value.
9234 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009235 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9236 Scan != E; ++Scan)
9237 if (Scan->mayWriteToMemory())
9238 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009239 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009240
9241 BasicBlock::iterator InsertPos = DestBlock->begin();
9242 while (isa<PHINode>(InsertPos)) ++InsertPos;
9243
Chris Lattner9f269e42005-08-08 19:11:57 +00009244 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009245 ++NumSunkInst;
9246 return true;
9247}
9248
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009249
9250/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9251/// all reachable code to the worklist.
9252///
9253/// This has a couple of tricks to make the code faster and more powerful. In
9254/// particular, we constant fold and DCE instructions as we go, to avoid adding
9255/// them to the worklist (this significantly speeds up instcombine on code where
9256/// many instructions are dead or constant). Additionally, if we find a branch
9257/// whose condition is a known constant, we only visit the reachable successors.
9258///
9259static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009260 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009261 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009262 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009263 std::vector<BasicBlock*> Worklist;
9264 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009265
Chris Lattner12b89cc2007-03-23 19:17:18 +00009266 while (!Worklist.empty()) {
9267 BB = Worklist.back();
9268 Worklist.pop_back();
9269
9270 // We have now visited this block! If we've already been here, ignore it.
9271 if (!Visited.insert(BB)) continue;
9272
9273 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9274 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009275
Chris Lattner12b89cc2007-03-23 19:17:18 +00009276 // DCE instruction if trivially dead.
9277 if (isInstructionTriviallyDead(Inst)) {
9278 ++NumDeadInst;
9279 DOUT << "IC: DCE: " << *Inst;
9280 Inst->eraseFromParent();
9281 continue;
9282 }
9283
9284 // ConstantProp instruction if trivially constant.
9285 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9286 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9287 Inst->replaceAllUsesWith(C);
9288 ++NumConstProp;
9289 Inst->eraseFromParent();
9290 continue;
9291 }
9292
9293 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009294 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009295
9296 // Recursively visit successors. If this is a branch or switch on a
9297 // constant, only visit the reachable successor.
9298 TerminatorInst *TI = BB->getTerminator();
9299 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9300 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9301 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9302 Worklist.push_back(BI->getSuccessor(!CondVal));
9303 continue;
9304 }
9305 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9306 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9307 // See if this is an explicit destination.
9308 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9309 if (SI->getCaseValue(i) == Cond) {
9310 Worklist.push_back(SI->getSuccessor(i));
9311 continue;
9312 }
9313
9314 // Otherwise it is the default destination.
9315 Worklist.push_back(SI->getSuccessor(0));
9316 continue;
9317 }
9318 }
9319
9320 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9321 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009322 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009323}
9324
Chris Lattner960a5432007-03-03 02:04:50 +00009325bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009326 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009327 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009328
9329 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9330 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009331
Chris Lattner4ed40f72005-07-07 20:40:38 +00009332 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009333 // Do a depth-first traversal of the function, populate the worklist with
9334 // the reachable instructions. Ignore blocks that are not reachable. Keep
9335 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009336 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009337 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009338
Chris Lattner4ed40f72005-07-07 20:40:38 +00009339 // Do a quick scan over the function. If we find any blocks that are
9340 // unreachable, remove any instructions inside of them. This prevents
9341 // the instcombine code from having to deal with some bad special cases.
9342 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9343 if (!Visited.count(BB)) {
9344 Instruction *Term = BB->getTerminator();
9345 while (Term != BB->begin()) { // Remove instrs bottom-up
9346 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009347
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009348 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009349 ++NumDeadInst;
9350
9351 if (!I->use_empty())
9352 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9353 I->eraseFromParent();
9354 }
9355 }
9356 }
Chris Lattnerca081252001-12-14 16:52:21 +00009357
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009358 while (!Worklist.empty()) {
9359 Instruction *I = RemoveOneFromWorkList();
9360 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009361
Chris Lattner1443bc52006-05-11 17:11:52 +00009362 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009363 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009364 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009365 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009366 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009367 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009368
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009369 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009370
9371 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009372 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009373 continue;
9374 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009375
Chris Lattner1443bc52006-05-11 17:11:52 +00009376 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009377 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009378 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009379
Chris Lattner1443bc52006-05-11 17:11:52 +00009380 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009381 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009382 ReplaceInstUsesWith(*I, C);
9383
Chris Lattner99f48c62002-09-02 04:59:56 +00009384 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009385 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009386 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009387 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009388 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009389
Chris Lattner39c98bb2004-12-08 23:43:58 +00009390 // See if we can trivially sink this instruction to a successor basic block.
9391 if (I->hasOneUse()) {
9392 BasicBlock *BB = I->getParent();
9393 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9394 if (UserParent != BB) {
9395 bool UserIsSuccessor = false;
9396 // See if the user is one of our successors.
9397 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9398 if (*SI == UserParent) {
9399 UserIsSuccessor = true;
9400 break;
9401 }
9402
9403 // If the user is one of our immediate successors, and if that successor
9404 // only has us as a predecessors (we'd have to split the critical edge
9405 // otherwise), we can keep going.
9406 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9407 next(pred_begin(UserParent)) == pred_end(UserParent))
9408 // Okay, the CFG is simple enough, try to sink this instruction.
9409 Changed |= TryToSinkInstruction(I, UserParent);
9410 }
9411 }
9412
Chris Lattnerca081252001-12-14 16:52:21 +00009413 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009414#ifndef NDEBUG
9415 std::string OrigI;
9416#endif
9417 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009418 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009419 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009420 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009421 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009422 DOUT << "IC: Old = " << *I
9423 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009424
Chris Lattner396dbfe2004-06-09 05:08:07 +00009425 // Everything uses the new instruction now.
9426 I->replaceAllUsesWith(Result);
9427
9428 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009429 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009430 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009431
Chris Lattner6e0123b2007-02-11 01:23:03 +00009432 // Move the name to the new instruction first.
9433 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009434
9435 // Insert the new instruction into the basic block...
9436 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009437 BasicBlock::iterator InsertPos = I;
9438
9439 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9440 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9441 ++InsertPos;
9442
9443 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009444
Chris Lattner63d75af2004-05-01 23:27:23 +00009445 // Make sure that we reprocess all operands now that we reduced their
9446 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009447 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009448
Chris Lattner396dbfe2004-06-09 05:08:07 +00009449 // Instructions can end up on the worklist more than once. Make sure
9450 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009451 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009452
9453 // Erase the old instruction.
9454 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009455 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009456#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009457 DOUT << "IC: Mod = " << OrigI
9458 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009459#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009460
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009461 // If the instruction was modified, it's possible that it is now dead.
9462 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009463 if (isInstructionTriviallyDead(I)) {
9464 // Make sure we process all operands now that we are reducing their
9465 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009466 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009467
Chris Lattner63d75af2004-05-01 23:27:23 +00009468 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009469 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009470 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009471 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009472 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009473 AddToWorkList(I);
9474 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009475 }
Chris Lattner053c0932002-05-14 15:24:07 +00009476 }
Chris Lattner260ab202002-04-18 17:39:14 +00009477 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009478 }
9479 }
9480
Chris Lattner960a5432007-03-03 02:04:50 +00009481 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009482 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009483}
9484
Chris Lattner960a5432007-03-03 02:04:50 +00009485
9486bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009487 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9488
Chris Lattner960a5432007-03-03 02:04:50 +00009489 bool EverMadeChange = false;
9490
9491 // Iterate while there is work to do.
9492 unsigned Iteration = 0;
9493 while (DoOneIteration(F, Iteration++))
9494 EverMadeChange = true;
9495 return EverMadeChange;
9496}
9497
Brian Gaeke38b79e82004-07-27 17:43:21 +00009498FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009499 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009500}
Brian Gaeke960707c2003-11-11 22:41:34 +00009501