blob: b3496c343996d7864d611d6e00651f0e15a93e27 [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 Lattnera74deaf2007-04-03 17:43:25 +0000186 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
187 Instruction *LHS,
188 ConstantInt *RHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000189
Reid Spencer266e42b2006-12-23 06:05:41 +0000190 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
191 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000192 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000193 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000194 Instruction *commonCastTransforms(CastInst &CI);
195 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000196 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner74ff60f2007-04-11 06:57:46 +0000197 Instruction *visitTrunc(TruncInst &CI);
198 Instruction *visitZExt(ZExtInst &CI);
199 Instruction *visitSExt(SExtInst &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000200 Instruction *visitFPTrunc(CastInst &CI);
201 Instruction *visitFPExt(CastInst &CI);
202 Instruction *visitFPToUI(CastInst &CI);
203 Instruction *visitFPToSI(CastInst &CI);
204 Instruction *visitUIToFP(CastInst &CI);
205 Instruction *visitSIToFP(CastInst &CI);
206 Instruction *visitPtrToInt(CastInst &CI);
207 Instruction *visitIntToPtr(CastInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000208 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000209 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
210 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000211 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000212 Instruction *visitCallInst(CallInst &CI);
213 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000214 Instruction *visitPHINode(PHINode &PN);
215 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000216 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000217 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000218 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000219 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000220 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000221 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000222 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000223 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000224 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000225
226 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000227 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000228
Chris Lattner970c33a2003-06-19 17:00:31 +0000229 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000230 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000231 bool transformConstExprCastCall(CallSite CS);
232
Chris Lattner69193f92004-04-05 01:30:19 +0000233 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000234 // InsertNewInstBefore - insert an instruction New before instruction Old
235 // in the program. Add the new instruction to the worklist.
236 //
Chris Lattner623826c2004-09-28 21:48:02 +0000237 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000238 assert(New && New->getParent() == 0 &&
239 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 BasicBlock *BB = Old.getParent();
241 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000242 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000243 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000244 }
245
Chris Lattner7e794272004-09-24 15:21:34 +0000246 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
247 /// This also adds the cast to the worklist. Finally, this returns the
248 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000249 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
250 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000251 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000252
Chris Lattnere79d2492006-04-06 19:19:17 +0000253 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000254 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000255
Reid Spencer13bc5d72006-12-12 09:18:51 +0000256 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000257 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000258 return C;
259 }
260
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000261 // ReplaceInstUsesWith - This method is to be used when an instruction is
262 // found to be dead, replacable with another preexisting expression. Here
263 // we add all uses of I to the worklist, replace all uses of I with the new
264 // value, then return I, so that the inst combiner will know that I was
265 // modified.
266 //
267 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000268 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000269 if (&I != V) {
270 I.replaceAllUsesWith(V);
271 return &I;
272 } else {
273 // If we are replacing the instruction with itself, this must be in a
274 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000275 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000276 return &I;
277 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000278 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000279
Chris Lattner2590e512006-02-07 06:56:34 +0000280 // UpdateValueUsesWith - This method is to be used when an value is
281 // found to be replacable with another preexisting expression or was
282 // updated. Here we add all uses of I to the worklist, replace all uses of
283 // I with the new value (unless the instruction was just updated), then
284 // return true, so that the inst combiner will know that I was modified.
285 //
286 bool UpdateValueUsesWith(Value *Old, Value *New) {
287 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
288 if (Old != New)
289 Old->replaceAllUsesWith(New);
290 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000291 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000292 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000293 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000294 return true;
295 }
296
Chris Lattner51ea1272004-02-28 05:22:00 +0000297 // EraseInstFromFunction - When dealing with an instruction that has side
298 // effects or produces a void value, we can't rely on DCE to delete the
299 // instruction. Instead, visit methods should return the value returned by
300 // this function.
301 Instruction *EraseInstFromFunction(Instruction &I) {
302 assert(I.use_empty() && "Cannot erase instruction that is used!");
303 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000304 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000305 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000306 return 0; // Don't do anything with FI
307 }
308
Chris Lattner3ac7c262003-08-13 20:16:26 +0000309 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000310 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
311 /// InsertBefore instruction. This is specialized a bit to avoid inserting
312 /// casts that are known to not do anything...
313 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000314 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
315 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000316 Instruction *InsertBefore);
317
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 /// SimplifyCommutative - This performs a few simplifications for
319 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000320 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000321
Reid Spencer266e42b2006-12-23 06:05:41 +0000322 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
323 /// most-complex to least-complex order.
324 bool SimplifyCompare(CmpInst &I);
325
Reid Spencer959a21d2007-03-23 21:24:59 +0000326 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
327 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000328 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
329 APInt& KnownZero, APInt& KnownOne,
330 unsigned Depth = 0);
331
Chris Lattner2deeaea2006-10-05 06:55:50 +0000332 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
333 uint64_t &UndefElts, unsigned Depth = 0);
334
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000335 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
336 // PHI node as operand #0, see if we can fold the instruction into the PHI
337 // (which is only possible if all operands to the PHI are constants).
338 Instruction *FoldOpIntoPhi(Instruction &I);
339
Chris Lattner7515cab2004-11-14 19:13:23 +0000340 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
341 // operator and they all are only used by the PHI, PHI together their
342 // inputs, and do the operation once, to the result of the PHI.
343 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000344 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
345
346
Zhou Sheng75b871f2007-01-11 12:24:14 +0000347 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
348 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000349
Zhou Sheng75b871f2007-01-11 12:24:14 +0000350 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000351 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000352 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000353 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner1db224d2007-04-27 17:44:50 +0000354 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000355 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner14a251b2007-04-15 00:07:55 +0000356 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000357
Reid Spencer74a528b2006-12-13 18:21:21 +0000358 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000359 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000360
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000361 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000362}
363
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000364// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000365// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000366static unsigned getComplexity(Value *V) {
367 if (isa<Instruction>(V)) {
368 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000369 return 3;
370 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000371 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000372 if (isa<Argument>(V)) return 3;
373 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000374}
Chris Lattner260ab202002-04-18 17:39:14 +0000375
Chris Lattner7fb29e12003-03-11 00:12:48 +0000376// isOnlyUse - Return true if this instruction will be deleted if we stop using
377// it.
378static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000379 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000380}
381
Chris Lattnere79e8542004-02-23 06:38:22 +0000382// getPromotedType - Return the specified type promoted as it would be to pass
383// though a va_arg area...
384static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000385 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
386 if (ITy->getBitWidth() < 32)
387 return Type::Int32Ty;
388 } else if (Ty == Type::FloatTy)
389 return Type::DoubleTy;
390 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000391}
392
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000393/// getBitCastOperand - If the specified operand is a CastInst or a constant
394/// expression bitcast, return the operand value, otherwise return null.
395static Value *getBitCastOperand(Value *V) {
396 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000397 return I->getOperand(0);
398 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000400 return CE->getOperand(0);
401 return 0;
402}
403
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000404/// This function is a wrapper around CastInst::isEliminableCastPair. It
405/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000406static Instruction::CastOps
407isEliminableCastPair(
408 const CastInst *CI, ///< The first cast instruction
409 unsigned opcode, ///< The opcode of the second cast instruction
410 const Type *DstTy, ///< The target type for the second cast instruction
411 TargetData *TD ///< The target data for pointer size
412) {
413
414 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
415 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000416
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000417 // Get the opcodes of the two Cast instructions
418 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
419 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000420
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000421 return Instruction::CastOps(
422 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
423 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000424}
425
426/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
427/// in any code being generated. It does not require codegen if V is simple
428/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000429static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
430 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 if (V->getType() == Ty || isa<Constant>(V)) return false;
432
Chris Lattner99155be2006-05-25 23:24:33 +0000433 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000434 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000435 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000436 return false;
437 return true;
438}
439
440/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
441/// InsertBefore instruction. This is specialized a bit to avoid inserting
442/// casts that are known to not do anything...
443///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
445 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000446 Instruction *InsertBefore) {
447 if (V->getType() == DestTy) return V;
448 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000449 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000450
Reid Spencer13bc5d72006-12-12 09:18:51 +0000451 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000452}
453
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454// SimplifyCommutative - This performs a few simplifications for commutative
455// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000456//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000457// 1. Order operands such that they are listed from right (least complex) to
458// left (most complex). This puts constants before unary operators before
459// binary operators.
460//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000461// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
462// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000463//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000464bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000465 bool Changed = false;
466 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
467 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000468
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000469 if (!I.isAssociative()) return Changed;
470 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000471 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
472 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
473 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000474 Constant *Folded = ConstantExpr::get(I.getOpcode(),
475 cast<Constant>(I.getOperand(1)),
476 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000477 I.setOperand(0, Op->getOperand(0));
478 I.setOperand(1, Folded);
479 return true;
480 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
481 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
482 isOnlyUse(Op) && isOnlyUse(Op1)) {
483 Constant *C1 = cast<Constant>(Op->getOperand(1));
484 Constant *C2 = cast<Constant>(Op1->getOperand(1));
485
486 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000487 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000488 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
489 Op1->getOperand(0),
490 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000491 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492 I.setOperand(0, New);
493 I.setOperand(1, Folded);
494 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000495 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000496 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000497 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000498}
Chris Lattnerca081252001-12-14 16:52:21 +0000499
Reid Spencer266e42b2006-12-23 06:05:41 +0000500/// SimplifyCompare - For a CmpInst this function just orders the operands
501/// so that theyare listed from right (least complex) to left (most complex).
502/// This puts constants before unary operators before binary operators.
503bool InstCombiner::SimplifyCompare(CmpInst &I) {
504 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
505 return false;
506 I.swapOperands();
507 // Compare instructions are not associative so there's nothing else we can do.
508 return true;
509}
510
Chris Lattnerbb74e222003-03-10 23:06:50 +0000511// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000513//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514static inline Value *dyn_castNegVal(Value *V) {
515 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000516 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517
Chris Lattner9ad0d552004-12-14 20:08:06 +0000518 // Constants can be considered to be negated values if they can be folded.
519 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000522}
523
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524static inline Value *dyn_castNotVal(Value *V) {
525 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000526 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000527
528 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000529 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000530 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000531 return 0;
532}
533
Chris Lattner7fb29e12003-03-11 00:12:48 +0000534// dyn_castFoldableMul - If this value is a multiply that can be folded into
535// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536// non-constant operand of the multiply, and set CST to point to the multiplier.
537// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000538//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000539static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000540 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000541 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000544 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000548 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000549 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000550 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000551 return I->getOperand(0);
552 }
553 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000554 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000555}
Chris Lattner31ae8632002-08-14 17:51:49 +0000556
Chris Lattner0798af32005-01-13 20:14:25 +0000557/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
558/// expression, return it.
559static User *dyn_castGetElementPtr(Value *V) {
560 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
561 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
562 if (CE->getOpcode() == Instruction::GetElementPtr)
563 return cast<User>(V);
564 return false;
565}
566
Reid Spencer80263aa2007-03-25 05:33:51 +0000567/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000568static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000569 APInt Val(C->getValue());
570 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000571}
Reid Spencer80263aa2007-03-25 05:33:51 +0000572/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000573static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000574 APInt Val(C->getValue());
575 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000576}
577/// Add - Add two ConstantInts together
578static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
579 return ConstantInt::get(C1->getValue() + C2->getValue());
580}
581/// And - Bitwise AND two ConstantInts together
582static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
583 return ConstantInt::get(C1->getValue() & C2->getValue());
584}
585/// Subtract - Subtract one ConstantInt from another
586static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
587 return ConstantInt::get(C1->getValue() - C2->getValue());
588}
589/// Multiply - Multiply two ConstantInts together
590static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
591 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000592}
593
Chris Lattner4534dd592006-02-09 07:38:58 +0000594/// ComputeMaskedBits - Determine which of the bits specified in Mask are
595/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000596/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
597/// processing.
598/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
599/// we cannot optimize based on the assumption that it is zero without changing
600/// it to be an explicit zero. If we don't change it to zero, other code could
601/// optimized based on the contradictory assumption that it is non-zero.
602/// Because instcombine aggressively folds operations with undef args anyway,
603/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000604static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000605 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000606 assert(V && "No Value?");
607 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000608 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000609 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000610 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000611 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000612 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000613 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
614 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000615 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000616 KnownZero = ~KnownOne & Mask;
617 return;
618 }
619
Reid Spenceraa696402007-03-08 01:46:38 +0000620 if (Depth == 6 || Mask == 0)
621 return; // Limit search depth.
622
623 Instruction *I = dyn_cast<Instruction>(V);
624 if (!I) return;
625
Zhou Shengaf4341d2007-03-13 02:23:10 +0000626 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000627 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000628
629 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000630 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000631 // If either the LHS or the RHS are Zero, the result is zero.
632 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000633 APInt Mask2(Mask & ~KnownZero);
634 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
636 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
637
638 // Output known-1 bits are only known if set in both the LHS & RHS.
639 KnownOne &= KnownOne2;
640 // Output known-0 are known to be clear if zero in either the LHS | RHS.
641 KnownZero |= KnownZero2;
642 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000643 }
644 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000645 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000646 APInt Mask2(Mask & ~KnownOne);
647 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
650
651 // Output known-0 bits are only known if clear in both the LHS & RHS.
652 KnownZero &= KnownZero2;
653 // Output known-1 are known to be set if set in either the LHS | RHS.
654 KnownOne |= KnownOne2;
655 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000656 }
Reid Spenceraa696402007-03-08 01:46:38 +0000657 case Instruction::Xor: {
658 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
659 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
660 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
661 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
662
663 // Output known-0 bits are known if clear or set in both the LHS & RHS.
664 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
665 // Output known-1 are known to be set if set in only one of the LHS, RHS.
666 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
667 KnownZero = KnownZeroOut;
668 return;
669 }
670 case Instruction::Select:
671 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
672 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
674 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
675
676 // Only known if known in both the LHS and RHS.
677 KnownOne &= KnownOne2;
678 KnownZero &= KnownZero2;
679 return;
680 case Instruction::FPTrunc:
681 case Instruction::FPExt:
682 case Instruction::FPToUI:
683 case Instruction::FPToSI:
684 case Instruction::SIToFP:
685 case Instruction::PtrToInt:
686 case Instruction::UIToFP:
687 case Instruction::IntToPtr:
688 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000689 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000690 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000691 uint32_t SrcBitWidth =
692 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000693 APInt MaskIn(Mask);
694 MaskIn.zext(SrcBitWidth);
695 KnownZero.zext(SrcBitWidth);
696 KnownOne.zext(SrcBitWidth);
697 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000698 KnownZero.trunc(BitWidth);
699 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000700 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000701 }
Reid Spenceraa696402007-03-08 01:46:38 +0000702 case Instruction::BitCast: {
703 const Type *SrcTy = I->getOperand(0)->getType();
704 if (SrcTy->isInteger()) {
705 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
706 return;
707 }
708 break;
709 }
710 case Instruction::ZExt: {
711 // Compute the bits in the result that are not present in the input.
712 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000713 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000714
Zhou Sheng57e3f732007-03-28 02:19:03 +0000715 APInt MaskIn(Mask);
716 MaskIn.trunc(SrcBitWidth);
717 KnownZero.trunc(SrcBitWidth);
718 KnownOne.trunc(SrcBitWidth);
719 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000720 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
721 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000722 KnownZero.zext(BitWidth);
723 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000724 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000725 return;
726 }
727 case Instruction::SExt: {
728 // Compute the bits in the result that are not present in the input.
729 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000730 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000731
Zhou Sheng57e3f732007-03-28 02:19:03 +0000732 APInt MaskIn(Mask);
733 MaskIn.trunc(SrcBitWidth);
734 KnownZero.trunc(SrcBitWidth);
735 KnownOne.trunc(SrcBitWidth);
736 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000737 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000738 KnownZero.zext(BitWidth);
739 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000740
741 // If the sign bit of the input is known set or clear, then we know the
742 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000743 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000744 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000745 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000746 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000747 return;
748 }
749 case Instruction::Shl:
750 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
751 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +0000752 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencerd8aad612007-03-25 02:03:12 +0000753 APInt Mask2(Mask.lshr(ShiftAmt));
754 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000755 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000756 KnownZero <<= ShiftAmt;
757 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000758 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000759 return;
760 }
761 break;
762 case Instruction::LShr:
763 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
764 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
765 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000766 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000767
768 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000769 APInt Mask2(Mask.shl(ShiftAmt));
770 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000771 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
772 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
773 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000774 // high bits known zero.
775 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000776 return;
777 }
778 break;
779 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000780 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000781 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
782 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000783 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000784
785 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000786 APInt Mask2(Mask.shl(ShiftAmt));
787 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000788 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
789 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
790 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
791
Zhou Sheng57e3f732007-03-28 02:19:03 +0000792 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
793 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000794 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000795 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000796 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000797 return;
798 }
799 break;
800 }
801}
802
Reid Spencerbb5741f2007-03-08 01:52:58 +0000803/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
804/// this predicate to simplify operations downstream. Mask is known to be zero
805/// for bits that V cannot have.
806static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000807 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000808 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
809 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
810 return (KnownZero & Mask) == Mask;
811}
812
Chris Lattner0157e7f2006-02-11 09:31:47 +0000813/// ShrinkDemandedConstant - Check to see if the specified operand of the
814/// specified instruction is a constant integer. If so, check to see if there
815/// are any bits set in the constant that are not demanded. If so, shrink the
816/// constant and return true.
817static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000818 APInt Demanded) {
819 assert(I && "No instruction?");
820 assert(OpNo < I->getNumOperands() && "Operand index too large");
821
822 // If the operand is not a constant integer, nothing to do.
823 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
824 if (!OpC) return false;
825
826 // If there are no bits set that aren't demanded, nothing to do.
827 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
828 if ((~Demanded & OpC->getValue()) == 0)
829 return false;
830
831 // This instruction is producing bits that are not demanded. Shrink the RHS.
832 Demanded &= OpC->getValue();
833 I->setOperand(OpNo, ConstantInt::get(Demanded));
834 return true;
835}
836
Chris Lattneree0f2802006-02-12 02:07:56 +0000837// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
838// set of known zero and one bits, compute the maximum and minimum values that
839// could have the specified known zero and known one bits, returning them in
840// min/max.
841static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000842 const APInt& KnownZero,
843 const APInt& KnownOne,
844 APInt& Min, APInt& Max) {
845 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
846 assert(KnownZero.getBitWidth() == BitWidth &&
847 KnownOne.getBitWidth() == BitWidth &&
848 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
849 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000850 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000851
Chris Lattneree0f2802006-02-12 02:07:56 +0000852 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
853 // bit if it is unknown.
854 Min = KnownOne;
855 Max = KnownOne|UnknownBits;
856
Zhou Shengc2d33092007-03-28 05:15:57 +0000857 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000858 Min.set(BitWidth-1);
859 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000860 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000861}
862
863// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
864// a set of known zero and one bits, compute the maximum and minimum values that
865// could have the specified known zero and known one bits, returning them in
866// min/max.
867static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000868 const APInt& KnownZero,
869 const APInt& KnownOne,
870 APInt& Min,
871 APInt& Max) {
872 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
873 assert(KnownZero.getBitWidth() == BitWidth &&
874 KnownOne.getBitWidth() == BitWidth &&
875 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
876 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000877 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000878
879 // The minimum value is when the unknown bits are all zeros.
880 Min = KnownOne;
881 // The maximum value is when the unknown bits are all ones.
882 Max = KnownOne|UnknownBits;
883}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884
Reid Spencer1791f232007-03-12 17:25:59 +0000885/// SimplifyDemandedBits - This function attempts to replace V with a simpler
886/// value based on the demanded bits. When this function is called, it is known
887/// that only the bits set in DemandedMask of the result of V are ever used
888/// downstream. Consequently, depending on the mask and V, it may be possible
889/// to replace V with a constant or one of its operands. In such cases, this
890/// function does the replacement and returns true. In all other cases, it
891/// returns false after analyzing the expression and setting KnownOne and known
892/// to be one in the expression. KnownZero contains all the bits that are known
893/// to be zero in the expression. These are provided to potentially allow the
894/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
895/// the expression. KnownOne and KnownZero always follow the invariant that
896/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
897/// the bits in KnownOne and KnownZero may only be accurate for those bits set
898/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
899/// and KnownOne must all be the same.
900bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
901 APInt& KnownZero, APInt& KnownOne,
902 unsigned Depth) {
903 assert(V != 0 && "Null pointer of Value???");
904 assert(Depth <= 6 && "Limit Search Depth");
905 uint32_t BitWidth = DemandedMask.getBitWidth();
906 const IntegerType *VTy = cast<IntegerType>(V->getType());
907 assert(VTy->getBitWidth() == BitWidth &&
908 KnownZero.getBitWidth() == BitWidth &&
909 KnownOne.getBitWidth() == BitWidth &&
910 "Value *V, DemandedMask, KnownZero and KnownOne \
911 must have same BitWidth");
912 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
913 // We know all of the bits for a constant!
914 KnownOne = CI->getValue() & DemandedMask;
915 KnownZero = ~KnownOne & DemandedMask;
916 return false;
917 }
918
Zhou Shengb9128442007-03-14 03:21:24 +0000919 KnownZero.clear();
920 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000921 if (!V->hasOneUse()) { // Other users may use these bits.
922 if (Depth != 0) { // Not at the root.
923 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
924 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
925 return false;
926 }
927 // If this is the root being simplified, allow it to have multiple uses,
928 // just set the DemandedMask to all bits.
929 DemandedMask = APInt::getAllOnesValue(BitWidth);
930 } else if (DemandedMask == 0) { // Not demanding any bits from V.
931 if (V != UndefValue::get(VTy))
932 return UpdateValueUsesWith(V, UndefValue::get(VTy));
933 return false;
934 } else if (Depth == 6) { // Limit search depth.
935 return false;
936 }
937
938 Instruction *I = dyn_cast<Instruction>(V);
939 if (!I) return false; // Only analyze instructions.
940
Reid Spencer1791f232007-03-12 17:25:59 +0000941 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
942 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
943 switch (I->getOpcode()) {
944 default: break;
945 case Instruction::And:
946 // If either the LHS or the RHS are Zero, the result is zero.
947 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
948 RHSKnownZero, RHSKnownOne, Depth+1))
949 return true;
950 assert((RHSKnownZero & RHSKnownOne) == 0 &&
951 "Bits known to be one AND zero?");
952
953 // If something is known zero on the RHS, the bits aren't demanded on the
954 // LHS.
955 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
956 LHSKnownZero, LHSKnownOne, Depth+1))
957 return true;
958 assert((LHSKnownZero & LHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960
961 // If all of the demanded bits are known 1 on one side, return the other.
962 // These bits cannot contribute to the result of the 'and'.
963 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
964 (DemandedMask & ~LHSKnownZero))
965 return UpdateValueUsesWith(I, I->getOperand(0));
966 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
967 (DemandedMask & ~RHSKnownZero))
968 return UpdateValueUsesWith(I, I->getOperand(1));
969
970 // If all of the demanded bits in the inputs are known zeros, return zero.
971 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
972 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
973
974 // If the RHS is a constant, see if we can simplify it.
975 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
976 return UpdateValueUsesWith(I, I);
977
978 // Output known-1 bits are only known if set in both the LHS & RHS.
979 RHSKnownOne &= LHSKnownOne;
980 // Output known-0 are known to be clear if zero in either the LHS | RHS.
981 RHSKnownZero |= LHSKnownZero;
982 break;
983 case Instruction::Or:
984 // If either the LHS or the RHS are One, the result is One.
985 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1))
987 return true;
988 assert((RHSKnownZero & RHSKnownOne) == 0 &&
989 "Bits known to be one AND zero?");
990 // If something is known one on the RHS, the bits aren't demanded on the
991 // LHS.
992 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
993 LHSKnownZero, LHSKnownOne, Depth+1))
994 return true;
995 assert((LHSKnownZero & LHSKnownOne) == 0 &&
996 "Bits known to be one AND zero?");
997
998 // If all of the demanded bits are known zero on one side, return the other.
999 // These bits cannot contribute to the result of the 'or'.
1000 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1001 (DemandedMask & ~LHSKnownOne))
1002 return UpdateValueUsesWith(I, I->getOperand(0));
1003 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1004 (DemandedMask & ~RHSKnownOne))
1005 return UpdateValueUsesWith(I, I->getOperand(1));
1006
1007 // If all of the potentially set bits on one side are known to be set on
1008 // the other side, just use the 'other' side.
1009 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1010 (DemandedMask & (~RHSKnownZero)))
1011 return UpdateValueUsesWith(I, I->getOperand(0));
1012 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1013 (DemandedMask & (~LHSKnownZero)))
1014 return UpdateValueUsesWith(I, I->getOperand(1));
1015
1016 // If the RHS is a constant, see if we can simplify it.
1017 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1018 return UpdateValueUsesWith(I, I);
1019
1020 // Output known-0 bits are only known if clear in both the LHS & RHS.
1021 RHSKnownZero &= LHSKnownZero;
1022 // Output known-1 are known to be set if set in either the LHS | RHS.
1023 RHSKnownOne |= LHSKnownOne;
1024 break;
1025 case Instruction::Xor: {
1026 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1027 RHSKnownZero, RHSKnownOne, Depth+1))
1028 return true;
1029 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1030 "Bits known to be one AND zero?");
1031 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1032 LHSKnownZero, LHSKnownOne, Depth+1))
1033 return true;
1034 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1035 "Bits known to be one AND zero?");
1036
1037 // If all of the demanded bits are known zero on one side, return the other.
1038 // These bits cannot contribute to the result of the 'xor'.
1039 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1040 return UpdateValueUsesWith(I, I->getOperand(0));
1041 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1042 return UpdateValueUsesWith(I, I->getOperand(1));
1043
1044 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1045 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1046 (RHSKnownOne & LHSKnownOne);
1047 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1048 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1049 (RHSKnownOne & LHSKnownZero);
1050
1051 // If all of the demanded bits are known to be zero on one side or the
1052 // other, turn this into an *inclusive* or.
1053 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1054 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1055 Instruction *Or =
1056 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1057 I->getName());
1058 InsertNewInstBefore(Or, *I);
1059 return UpdateValueUsesWith(I, Or);
1060 }
1061
1062 // If all of the demanded bits on one side are known, and all of the set
1063 // bits on that side are also known to be set on the other side, turn this
1064 // into an AND, as we know the bits will be cleared.
1065 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1066 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1067 // all known
1068 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1069 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1070 Instruction *And =
1071 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1072 InsertNewInstBefore(And, *I);
1073 return UpdateValueUsesWith(I, And);
1074 }
1075 }
1076
1077 // If the RHS is a constant, see if we can simplify it.
1078 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1079 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1080 return UpdateValueUsesWith(I, I);
1081
1082 RHSKnownZero = KnownZeroOut;
1083 RHSKnownOne = KnownOneOut;
1084 break;
1085 }
1086 case Instruction::Select:
1087 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1088 RHSKnownZero, RHSKnownOne, Depth+1))
1089 return true;
1090 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1091 LHSKnownZero, LHSKnownOne, Depth+1))
1092 return true;
1093 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1094 "Bits known to be one AND zero?");
1095 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1096 "Bits known to be one AND zero?");
1097
1098 // If the operands are constants, see if we can simplify them.
1099 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1100 return UpdateValueUsesWith(I, I);
1101 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1102 return UpdateValueUsesWith(I, I);
1103
1104 // Only known if known in both the LHS and RHS.
1105 RHSKnownOne &= LHSKnownOne;
1106 RHSKnownZero &= LHSKnownZero;
1107 break;
1108 case Instruction::Trunc: {
1109 uint32_t truncBf =
1110 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +00001111 DemandedMask.zext(truncBf);
1112 RHSKnownZero.zext(truncBf);
1113 RHSKnownOne.zext(truncBf);
1114 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1115 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001116 return true;
1117 DemandedMask.trunc(BitWidth);
1118 RHSKnownZero.trunc(BitWidth);
1119 RHSKnownOne.trunc(BitWidth);
1120 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1121 "Bits known to be one AND zero?");
1122 break;
1123 }
1124 case Instruction::BitCast:
1125 if (!I->getOperand(0)->getType()->isInteger())
1126 return false;
1127
1128 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
1130 return true;
1131 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1132 "Bits known to be one AND zero?");
1133 break;
1134 case Instruction::ZExt: {
1135 // Compute the bits in the result that are not present in the input.
1136 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001137 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001138
Zhou Sheng444af492007-03-29 04:45:55 +00001139 DemandedMask.trunc(SrcBitWidth);
1140 RHSKnownZero.trunc(SrcBitWidth);
1141 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001142 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001144 return true;
1145 DemandedMask.zext(BitWidth);
1146 RHSKnownZero.zext(BitWidth);
1147 RHSKnownOne.zext(BitWidth);
1148 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1149 "Bits known to be one AND zero?");
1150 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001151 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001152 break;
1153 }
1154 case Instruction::SExt: {
1155 // Compute the bits in the result that are not present in the input.
1156 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001157 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001158
Reid Spencer1791f232007-03-12 17:25:59 +00001159 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001160 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001161
Zhou Shenga4475572007-03-29 02:26:30 +00001162 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001163 // If any of the sign extended bits are demanded, we know that the sign
1164 // bit is demanded.
1165 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001166 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001167
Zhou Sheng444af492007-03-29 04:45:55 +00001168 InputDemandedBits.trunc(SrcBitWidth);
1169 RHSKnownZero.trunc(SrcBitWidth);
1170 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001171 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1172 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001173 return true;
1174 InputDemandedBits.zext(BitWidth);
1175 RHSKnownZero.zext(BitWidth);
1176 RHSKnownOne.zext(BitWidth);
1177 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1178 "Bits known to be one AND zero?");
1179
1180 // If the sign bit of the input is known set or clear, then we know the
1181 // top bits of the result.
1182
1183 // If the input sign bit is known zero, or if the NewBits are not demanded
1184 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001185 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001186 {
1187 // Convert to ZExt cast
1188 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1189 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001190 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001191 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001192 }
1193 break;
1194 }
1195 case Instruction::Add: {
1196 // Figure out what the input bits are. If the top bits of the and result
1197 // are not demanded, then the add doesn't demand them from its input
1198 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001199 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001200
1201 // If there is a constant on the RHS, there are a variety of xformations
1202 // we can do.
1203 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1204 // If null, this should be simplified elsewhere. Some of the xforms here
1205 // won't work if the RHS is zero.
1206 if (RHS->isZero())
1207 break;
1208
1209 // If the top bit of the output is demanded, demand everything from the
1210 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001211 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001212
1213 // Find information about known zero/one bits in the input.
1214 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1215 LHSKnownZero, LHSKnownOne, Depth+1))
1216 return true;
1217
1218 // If the RHS of the add has bits set that can't affect the input, reduce
1219 // the constant.
1220 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1221 return UpdateValueUsesWith(I, I);
1222
1223 // Avoid excess work.
1224 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1225 break;
1226
1227 // Turn it into OR if input bits are zero.
1228 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1229 Instruction *Or =
1230 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1231 I->getName());
1232 InsertNewInstBefore(Or, *I);
1233 return UpdateValueUsesWith(I, Or);
1234 }
1235
1236 // We can say something about the output known-zero and known-one bits,
1237 // depending on potential carries from the input constant and the
1238 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1239 // bits set and the RHS constant is 0x01001, then we know we have a known
1240 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1241
1242 // To compute this, we first compute the potential carry bits. These are
1243 // the bits which may be modified. I'm not aware of a better way to do
1244 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001245 const APInt& RHSVal = RHS->getValue();
1246 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001247
1248 // Now that we know which bits have carries, compute the known-1/0 sets.
1249
1250 // Bits are known one if they are known zero in one operand and one in the
1251 // other, and there is no input carry.
1252 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1253 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1254
1255 // Bits are known zero if they are known zero in both operands and there
1256 // is no input carry.
1257 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1258 } else {
1259 // If the high-bits of this ADD are not demanded, then it does not demand
1260 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001261 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001262 // Right fill the mask of bits for this ADD to demand the most
1263 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001264 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001265 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1266 LHSKnownZero, LHSKnownOne, Depth+1))
1267 return true;
1268 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1269 LHSKnownZero, LHSKnownOne, Depth+1))
1270 return true;
1271 }
1272 }
1273 break;
1274 }
1275 case Instruction::Sub:
1276 // If the high-bits of this SUB are not demanded, then it does not demand
1277 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001278 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001279 // Right fill the mask of bits for this SUB to demand the most
1280 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001281 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001282 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001283 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1284 LHSKnownZero, LHSKnownOne, Depth+1))
1285 return true;
1286 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1287 LHSKnownZero, LHSKnownOne, Depth+1))
1288 return true;
1289 }
1290 break;
1291 case Instruction::Shl:
1292 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001293 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001294 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001296 RHSKnownZero, RHSKnownOne, Depth+1))
1297 return true;
1298 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1299 "Bits known to be one AND zero?");
1300 RHSKnownZero <<= ShiftAmt;
1301 RHSKnownOne <<= ShiftAmt;
1302 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001303 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001304 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001305 }
1306 break;
1307 case Instruction::LShr:
1308 // For a logical shift right
1309 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001310 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001311
Reid Spencer1791f232007-03-12 17:25:59 +00001312 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001313 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1314 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001315 RHSKnownZero, RHSKnownOne, Depth+1))
1316 return true;
1317 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1318 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001319 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1320 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001321 if (ShiftAmt) {
1322 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001323 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001324 RHSKnownZero |= HighBits; // high bits known zero.
1325 }
Reid Spencer1791f232007-03-12 17:25:59 +00001326 }
1327 break;
1328 case Instruction::AShr:
1329 // If this is an arithmetic shift right and only the low-bit is set, we can
1330 // always convert this into a logical shr, even if the shift amount is
1331 // variable. The low bit of the shift cannot be an input sign bit unless
1332 // the shift amount is >= the size of the datatype, which is undefined.
1333 if (DemandedMask == 1) {
1334 // Perform the logical shift right.
1335 Value *NewVal = BinaryOperator::createLShr(
1336 I->getOperand(0), I->getOperand(1), I->getName());
1337 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1338 return UpdateValueUsesWith(I, NewVal);
1339 }
1340
1341 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001342 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001343
Reid Spencer1791f232007-03-12 17:25:59 +00001344 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001345 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001346 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001347 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001348 RHSKnownZero, RHSKnownOne, Depth+1))
1349 return true;
1350 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1351 "Bits known to be one AND zero?");
1352 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001353 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001354 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1356
1357 // Handle the sign bits.
1358 APInt SignBit(APInt::getSignBit(BitWidth));
1359 // Adjust to where it is now in the mask.
1360 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1361
1362 // If the input sign bit is known to be zero, or if none of the top bits
1363 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001364 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001365 (HighBits & ~DemandedMask) == HighBits) {
1366 // Perform the logical shift right.
1367 Value *NewVal = BinaryOperator::createLShr(
1368 I->getOperand(0), SA, I->getName());
1369 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1370 return UpdateValueUsesWith(I, NewVal);
1371 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1372 RHSKnownOne |= HighBits;
1373 }
1374 }
1375 break;
1376 }
1377
1378 // If the client is only demanding bits that we know, return the known
1379 // constant.
1380 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1381 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1382 return false;
1383}
1384
Chris Lattner2deeaea2006-10-05 06:55:50 +00001385
1386/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1387/// 64 or fewer elements. DemandedElts contains the set of elements that are
1388/// actually used by the caller. This method analyzes which elements of the
1389/// operand are undef and returns that information in UndefElts.
1390///
1391/// If the information about demanded elements can be used to simplify the
1392/// operation, the operation is simplified, then the resultant value is
1393/// returned. This returns null if no change was made.
1394Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1395 uint64_t &UndefElts,
1396 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001397 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001398 assert(VWidth <= 64 && "Vector too wide to analyze!");
1399 uint64_t EltMask = ~0ULL >> (64-VWidth);
1400 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1401 "Invalid DemandedElts!");
1402
1403 if (isa<UndefValue>(V)) {
1404 // If the entire vector is undefined, just return this info.
1405 UndefElts = EltMask;
1406 return 0;
1407 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1408 UndefElts = EltMask;
1409 return UndefValue::get(V->getType());
1410 }
1411
1412 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001413 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1414 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001415 Constant *Undef = UndefValue::get(EltTy);
1416
1417 std::vector<Constant*> Elts;
1418 for (unsigned i = 0; i != VWidth; ++i)
1419 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1420 Elts.push_back(Undef);
1421 UndefElts |= (1ULL << i);
1422 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1423 Elts.push_back(Undef);
1424 UndefElts |= (1ULL << i);
1425 } else { // Otherwise, defined.
1426 Elts.push_back(CP->getOperand(i));
1427 }
1428
1429 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001430 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001431 return NewCP != CP ? NewCP : 0;
1432 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001433 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001434 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001435 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001436 Constant *Zero = Constant::getNullValue(EltTy);
1437 Constant *Undef = UndefValue::get(EltTy);
1438 std::vector<Constant*> Elts;
1439 for (unsigned i = 0; i != VWidth; ++i)
1440 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1441 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001442 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001443 }
1444
1445 if (!V->hasOneUse()) { // Other users may use these bits.
1446 if (Depth != 0) { // Not at the root.
1447 // TODO: Just compute the UndefElts information recursively.
1448 return false;
1449 }
1450 return false;
1451 } else if (Depth == 10) { // Limit search depth.
1452 return false;
1453 }
1454
1455 Instruction *I = dyn_cast<Instruction>(V);
1456 if (!I) return false; // Only analyze instructions.
1457
1458 bool MadeChange = false;
1459 uint64_t UndefElts2;
1460 Value *TmpV;
1461 switch (I->getOpcode()) {
1462 default: break;
1463
1464 case Instruction::InsertElement: {
1465 // If this is a variable index, we don't know which element it overwrites.
1466 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001467 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001468 if (Idx == 0) {
1469 // Note that we can't propagate undef elt info, because we don't know
1470 // which elt is getting updated.
1471 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1472 UndefElts2, Depth+1);
1473 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1474 break;
1475 }
1476
1477 // If this is inserting an element that isn't demanded, remove this
1478 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001479 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001480 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1481 return AddSoonDeadInstToWorklist(*I, 0);
1482
1483 // Otherwise, the element inserted overwrites whatever was there, so the
1484 // input demanded set is simpler than the output set.
1485 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1486 DemandedElts & ~(1ULL << IdxNo),
1487 UndefElts, Depth+1);
1488 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1489
1490 // The inserted element is defined.
1491 UndefElts |= 1ULL << IdxNo;
1492 break;
1493 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001494 case Instruction::BitCast: {
1495 // Packed->packed casts only.
1496 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1497 if (!VTy) break;
1498 unsigned InVWidth = VTy->getNumElements();
1499 uint64_t InputDemandedElts = 0;
1500 unsigned Ratio;
1501
1502 if (VWidth == InVWidth) {
1503 // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1504 // elements as are demanded of us.
1505 Ratio = 1;
1506 InputDemandedElts = DemandedElts;
1507 } else if (VWidth > InVWidth) {
1508 // Untested so far.
1509 break;
1510
1511 // If there are more elements in the result than there are in the source,
1512 // then an input element is live if any of the corresponding output
1513 // elements are live.
1514 Ratio = VWidth/InVWidth;
1515 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1516 if (DemandedElts & (1ULL << OutIdx))
1517 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1518 }
1519 } else {
1520 // Untested so far.
1521 break;
1522
1523 // If there are more elements in the source than there are in the result,
1524 // then an input element is live if the corresponding output element is
1525 // live.
1526 Ratio = InVWidth/VWidth;
1527 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528 if (DemandedElts & (1ULL << InIdx/Ratio))
1529 InputDemandedElts |= 1ULL << InIdx;
1530 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001531
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001532 // div/rem demand all inputs, because they don't want divide by zero.
1533 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1534 UndefElts2, Depth+1);
1535 if (TmpV) {
1536 I->setOperand(0, TmpV);
1537 MadeChange = true;
1538 }
1539
1540 UndefElts = UndefElts2;
1541 if (VWidth > InVWidth) {
1542 assert(0 && "Unimp");
1543 // If there are more elements in the result than there are in the source,
1544 // then an output element is undef if the corresponding input element is
1545 // undef.
1546 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1547 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1548 UndefElts |= 1ULL << OutIdx;
1549 } else if (VWidth < InVWidth) {
1550 assert(0 && "Unimp");
1551 // If there are more elements in the source than there are in the result,
1552 // then a result element is undef if all of the corresponding input
1553 // elements are undef.
1554 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1555 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1556 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1557 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1558 }
1559 break;
1560 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001561 case Instruction::And:
1562 case Instruction::Or:
1563 case Instruction::Xor:
1564 case Instruction::Add:
1565 case Instruction::Sub:
1566 case Instruction::Mul:
1567 // div/rem demand all inputs, because they don't want divide by zero.
1568 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1569 UndefElts, Depth+1);
1570 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1572 UndefElts2, Depth+1);
1573 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1574
1575 // Output elements are undefined if both are undefined. Consider things
1576 // like undef&0. The result is known zero, not undef.
1577 UndefElts &= UndefElts2;
1578 break;
1579
1580 case Instruction::Call: {
1581 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1582 if (!II) break;
1583 switch (II->getIntrinsicID()) {
1584 default: break;
1585
1586 // Binary vector operations that work column-wise. A dest element is a
1587 // function of the corresponding input elements from the two inputs.
1588 case Intrinsic::x86_sse_sub_ss:
1589 case Intrinsic::x86_sse_mul_ss:
1590 case Intrinsic::x86_sse_min_ss:
1591 case Intrinsic::x86_sse_max_ss:
1592 case Intrinsic::x86_sse2_sub_sd:
1593 case Intrinsic::x86_sse2_mul_sd:
1594 case Intrinsic::x86_sse2_min_sd:
1595 case Intrinsic::x86_sse2_max_sd:
1596 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1597 UndefElts, Depth+1);
1598 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1599 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1600 UndefElts2, Depth+1);
1601 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1602
1603 // If only the low elt is demanded and this is a scalarizable intrinsic,
1604 // scalarize it now.
1605 if (DemandedElts == 1) {
1606 switch (II->getIntrinsicID()) {
1607 default: break;
1608 case Intrinsic::x86_sse_sub_ss:
1609 case Intrinsic::x86_sse_mul_ss:
1610 case Intrinsic::x86_sse2_sub_sd:
1611 case Intrinsic::x86_sse2_mul_sd:
1612 // TODO: Lower MIN/MAX/ABS/etc
1613 Value *LHS = II->getOperand(1);
1614 Value *RHS = II->getOperand(2);
1615 // Extract the element as scalars.
1616 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1617 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1618
1619 switch (II->getIntrinsicID()) {
1620 default: assert(0 && "Case stmts out of sync!");
1621 case Intrinsic::x86_sse_sub_ss:
1622 case Intrinsic::x86_sse2_sub_sd:
1623 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1624 II->getName()), *II);
1625 break;
1626 case Intrinsic::x86_sse_mul_ss:
1627 case Intrinsic::x86_sse2_mul_sd:
1628 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1629 II->getName()), *II);
1630 break;
1631 }
1632
1633 Instruction *New =
1634 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1635 II->getName());
1636 InsertNewInstBefore(New, *II);
1637 AddSoonDeadInstToWorklist(*II, 0);
1638 return New;
1639 }
1640 }
1641
1642 // Output elements are undefined if both are undefined. Consider things
1643 // like undef&0. The result is known zero, not undef.
1644 UndefElts &= UndefElts2;
1645 break;
1646 }
1647 break;
1648 }
1649 }
1650 return MadeChange ? I : 0;
1651}
1652
Reid Spencer266e42b2006-12-23 06:05:41 +00001653/// @returns true if the specified compare instruction is
1654/// true when both operands are equal...
1655/// @brief Determine if the ICmpInst returns true if both operands are equal
1656static bool isTrueWhenEqual(ICmpInst &ICI) {
1657 ICmpInst::Predicate pred = ICI.getPredicate();
1658 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1659 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1660 pred == ICmpInst::ICMP_SLE;
1661}
1662
Chris Lattnerb8b97502003-08-13 19:01:45 +00001663/// AssociativeOpt - Perform an optimization on an associative operator. This
1664/// function is designed to check a chain of associative operators for a
1665/// potential to apply a certain optimization. Since the optimization may be
1666/// applicable if the expression was reassociated, this checks the chain, then
1667/// reassociates the expression as necessary to expose the optimization
1668/// opportunity. This makes use of a special Functor, which must define
1669/// 'shouldApply' and 'apply' methods.
1670///
1671template<typename Functor>
1672Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1673 unsigned Opcode = Root.getOpcode();
1674 Value *LHS = Root.getOperand(0);
1675
1676 // Quick check, see if the immediate LHS matches...
1677 if (F.shouldApply(LHS))
1678 return F.apply(Root);
1679
1680 // Otherwise, if the LHS is not of the same opcode as the root, return.
1681 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001682 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001683 // Should we apply this transform to the RHS?
1684 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1685
1686 // If not to the RHS, check to see if we should apply to the LHS...
1687 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1688 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1689 ShouldApply = true;
1690 }
1691
1692 // If the functor wants to apply the optimization to the RHS of LHSI,
1693 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1694 if (ShouldApply) {
1695 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001696
Chris Lattnerb8b97502003-08-13 19:01:45 +00001697 // Now all of the instructions are in the current basic block, go ahead
1698 // and perform the reassociation.
1699 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1700
1701 // First move the selected RHS to the LHS of the root...
1702 Root.setOperand(0, LHSI->getOperand(1));
1703
1704 // Make what used to be the LHS of the root be the user of the root...
1705 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001706 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001707 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1708 return 0;
1709 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001710 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001711 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001712 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1713 BasicBlock::iterator ARI = &Root; ++ARI;
1714 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1715 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001716
1717 // Now propagate the ExtraOperand down the chain of instructions until we
1718 // get to LHSI.
1719 while (TmpLHSI != LHSI) {
1720 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001721 // Move the instruction to immediately before the chain we are
1722 // constructing to avoid breaking dominance properties.
1723 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1724 BB->getInstList().insert(ARI, NextLHSI);
1725 ARI = NextLHSI;
1726
Chris Lattnerb8b97502003-08-13 19:01:45 +00001727 Value *NextOp = NextLHSI->getOperand(1);
1728 NextLHSI->setOperand(1, ExtraOperand);
1729 TmpLHSI = NextLHSI;
1730 ExtraOperand = NextOp;
1731 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001732
Chris Lattnerb8b97502003-08-13 19:01:45 +00001733 // Now that the instructions are reassociated, have the functor perform
1734 // the transformation...
1735 return F.apply(Root);
1736 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001737
Chris Lattnerb8b97502003-08-13 19:01:45 +00001738 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1739 }
1740 return 0;
1741}
1742
1743
1744// AddRHS - Implements: X + X --> X << 1
1745struct AddRHS {
1746 Value *RHS;
1747 AddRHS(Value *rhs) : RHS(rhs) {}
1748 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1749 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001750 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001751 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001752 }
1753};
1754
1755// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1756// iff C1&C2 == 0
1757struct AddMaskingAnd {
1758 Constant *C2;
1759 AddMaskingAnd(Constant *c) : C2(c) {}
1760 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001761 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001762 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001763 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001764 }
1765 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001766 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001767 }
1768};
1769
Chris Lattner86102b82005-01-01 16:22:27 +00001770static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001771 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001772 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001773 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001774 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001775
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001776 return IC->InsertNewInstBefore(CastInst::create(
1777 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001778 }
1779
Chris Lattner183b3362004-04-09 19:05:30 +00001780 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001781 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1782 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001783
Chris Lattner183b3362004-04-09 19:05:30 +00001784 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1785 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001786 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1787 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001788 }
1789
1790 Value *Op0 = SO, *Op1 = ConstOperand;
1791 if (!ConstIsRHS)
1792 std::swap(Op0, Op1);
1793 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001794 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1795 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001796 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1797 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1798 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001799 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001800 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001801 abort();
1802 }
Chris Lattner86102b82005-01-01 16:22:27 +00001803 return IC->InsertNewInstBefore(New, I);
1804}
1805
1806// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1807// constant as the other operand, try to fold the binary operator into the
1808// select arguments. This also works for Cast instructions, which obviously do
1809// not have a second operand.
1810static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1811 InstCombiner *IC) {
1812 // Don't modify shared select instructions
1813 if (!SI->hasOneUse()) return 0;
1814 Value *TV = SI->getOperand(1);
1815 Value *FV = SI->getOperand(2);
1816
1817 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001818 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001819 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001820
Chris Lattner86102b82005-01-01 16:22:27 +00001821 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1822 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1823
1824 return new SelectInst(SI->getCondition(), SelectTrueVal,
1825 SelectFalseVal);
1826 }
1827 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001828}
1829
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001830
1831/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1832/// node as operand #0, see if we can fold the instruction into the PHI (which
1833/// is only possible if all operands to the PHI are constants).
1834Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1835 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001836 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001837 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001838
Chris Lattner04689872006-09-09 22:02:56 +00001839 // Check to see if all of the operands of the PHI are constants. If there is
1840 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001841 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001842 BasicBlock *NonConstBB = 0;
1843 for (unsigned i = 0; i != NumPHIValues; ++i)
1844 if (!isa<Constant>(PN->getIncomingValue(i))) {
1845 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001846 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001847 NonConstBB = PN->getIncomingBlock(i);
1848
1849 // If the incoming non-constant value is in I's block, we have an infinite
1850 // loop.
1851 if (NonConstBB == I.getParent())
1852 return 0;
1853 }
1854
1855 // If there is exactly one non-constant value, we can insert a copy of the
1856 // operation in that block. However, if this is a critical edge, we would be
1857 // inserting the computation one some other paths (e.g. inside a loop). Only
1858 // do this if the pred block is unconditionally branching into the phi block.
1859 if (NonConstBB) {
1860 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1861 if (!BI || !BI->isUnconditional()) return 0;
1862 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001863
1864 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001865 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001866 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001867 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001868 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001869
1870 // Next, add all of the operands to the PHI.
1871 if (I.getNumOperands() == 2) {
1872 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001873 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001874 Value *InV;
1875 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001876 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1877 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1878 else
1879 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001880 } else {
1881 assert(PN->getIncomingBlock(i) == NonConstBB);
1882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1883 InV = BinaryOperator::create(BO->getOpcode(),
1884 PN->getIncomingValue(i), C, "phitmp",
1885 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001886 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1887 InV = CmpInst::create(CI->getOpcode(),
1888 CI->getPredicate(),
1889 PN->getIncomingValue(i), C, "phitmp",
1890 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001891 else
1892 assert(0 && "Unknown binop!");
1893
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001894 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001895 }
1896 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001897 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001898 } else {
1899 CastInst *CI = cast<CastInst>(&I);
1900 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001901 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001902 Value *InV;
1903 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001904 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001905 } else {
1906 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001907 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1908 I.getType(), "phitmp",
1909 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001910 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001911 }
1912 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001913 }
1914 }
1915 return ReplaceInstUsesWith(I, NewPN);
1916}
1917
Chris Lattner113f4f42002-06-25 16:13:24 +00001918Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001919 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001920 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001921
Chris Lattnercf4a9962004-04-10 22:01:55 +00001922 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001923 // X + undef -> undef
1924 if (isa<UndefValue>(RHS))
1925 return ReplaceInstUsesWith(I, RHS);
1926
Chris Lattnercf4a9962004-04-10 22:01:55 +00001927 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001928 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001929 if (RHSC->isNullValue())
1930 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001931 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1932 if (CFP->isExactlyValue(-0.0))
1933 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001934 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001935
Chris Lattnercf4a9962004-04-10 22:01:55 +00001936 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001937 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001938 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00001939 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00001940 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001941 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001942
1943 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1944 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001945 if (!isa<VectorType>(I.getType())) {
1946 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1947 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1948 KnownZero, KnownOne))
1949 return &I;
1950 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001951 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001952
1953 if (isa<PHINode>(LHS))
1954 if (Instruction *NV = FoldOpIntoPhi(I))
1955 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001956
Chris Lattner330628a2006-01-06 17:59:59 +00001957 ConstantInt *XorRHS = 0;
1958 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001959 if (isa<ConstantInt>(RHSC) &&
1960 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00001961 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001962 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00001963
Zhou Sheng56cda952007-04-02 08:20:41 +00001964 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00001965 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1966 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001967 do {
1968 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001969 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1970 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001971 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1972 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001973 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00001974 if (!MaskedValueIsZero(XorLHS,
1975 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001976 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001977 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001978 }
1979 }
1980 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001981 C0080Val = APIntOps::lshr(C0080Val, Size);
1982 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1983 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001984
Reid Spencera5c18bf2007-03-28 01:36:16 +00001985 // FIXME: This shouldn't be necessary. When the backends can handle types
1986 // with funny bit widths then this whole cascade of if statements should
1987 // be removed. It is just here to get the size of the "middle" type back
1988 // up to something that the back ends can handle.
1989 const Type *MiddleType = 0;
1990 switch (Size) {
1991 default: break;
1992 case 32: MiddleType = Type::Int32Ty; break;
1993 case 16: MiddleType = Type::Int16Ty; break;
1994 case 8: MiddleType = Type::Int8Ty; break;
1995 }
1996 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001997 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001998 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001999 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002000 }
2001 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002002 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002003
Chris Lattnerb8b97502003-08-13 19:01:45 +00002004 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002005 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002006 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002007
2008 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2009 if (RHSI->getOpcode() == Instruction::Sub)
2010 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2011 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2012 }
2013 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2014 if (LHSI->getOpcode() == Instruction::Sub)
2015 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2016 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2017 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002018 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002019
Chris Lattner147e9752002-05-08 22:46:53 +00002020 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002021 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002022 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002023
2024 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002025 if (!isa<Constant>(RHS))
2026 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002027 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002028
Misha Brukmanb1c93172005-04-21 23:48:37 +00002029
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002030 ConstantInt *C2;
2031 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2032 if (X == RHS) // X*C + X --> X * (C+1)
2033 return BinaryOperator::createMul(RHS, AddOne(C2));
2034
2035 // X*C1 + X*C2 --> X * (C1+C2)
2036 ConstantInt *C1;
2037 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00002038 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002039 }
2040
2041 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002042 if (dyn_castFoldableMul(RHS, C2) == LHS)
2043 return BinaryOperator::createMul(LHS, AddOne(C2));
2044
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002045 // X + ~X --> -1 since ~X = -X-1
2046 if (dyn_castNotVal(LHS) == RHS ||
2047 dyn_castNotVal(RHS) == LHS)
2048 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2049
Chris Lattner57c8d992003-02-18 19:57:07 +00002050
Chris Lattnerb8b97502003-08-13 19:01:45 +00002051 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002052 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002053 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2054 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002055
Chris Lattnerb9cde762003-10-02 15:11:26 +00002056 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002057 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002058 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2059 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002060
Chris Lattnerbff91d92004-10-08 05:07:56 +00002061 // (X & FF00) + xx00 -> (X+xx00) & FF00
2062 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002063 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002064 if (Anded == CRHS) {
2065 // See if all bits from the first bit set in the Add RHS up are included
2066 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002067 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002068
2069 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002070 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002071
2072 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002073 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002074
Chris Lattnerbff91d92004-10-08 05:07:56 +00002075 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2076 // Okay, the xform is safe. Insert the new add pronto.
2077 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2078 LHS->getName()), I);
2079 return BinaryOperator::createAnd(NewAdd, C2);
2080 }
2081 }
2082 }
2083
Chris Lattnerd4252a72004-07-30 07:50:03 +00002084 // Try to fold constant add into select arguments.
2085 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002086 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002087 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002088 }
2089
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002090 // add (cast *A to intptrtype) B ->
2091 // cast (GEP (cast *A to sbyte*) B) ->
2092 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002093 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002094 CastInst *CI = dyn_cast<CastInst>(LHS);
2095 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002096 if (!CI) {
2097 CI = dyn_cast<CastInst>(RHS);
2098 Other = LHS;
2099 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002100 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002101 (CI->getType()->getPrimitiveSizeInBits() ==
2102 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002103 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002104 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002105 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002106 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002107 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002108 }
2109 }
2110
Chris Lattner113f4f42002-06-25 16:13:24 +00002111 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002112}
2113
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002114// isSignBit - Return true if the value represented by the constant only has the
2115// highest order bit set.
2116static bool isSignBit(ConstantInt *CI) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002117 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002118 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002119}
2120
Chris Lattner113f4f42002-06-25 16:13:24 +00002121Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002122 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002123
Chris Lattnere6794492002-08-12 21:17:25 +00002124 if (Op0 == Op1) // sub X, X -> 0
2125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002126
Chris Lattnere6794492002-08-12 21:17:25 +00002127 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002128 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002129 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002130
Chris Lattner81a7a232004-10-16 18:11:37 +00002131 if (isa<UndefValue>(Op0))
2132 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2133 if (isa<UndefValue>(Op1))
2134 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2135
Chris Lattner8f2f5982003-11-05 01:06:05 +00002136 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2137 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002138 if (C->isAllOnesValue())
2139 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002140
Chris Lattner8f2f5982003-11-05 01:06:05 +00002141 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002142 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002143 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002144 return BinaryOperator::createAdd(X, AddOne(C));
2145
Chris Lattner27df1db2007-01-15 07:02:54 +00002146 // -(X >>u 31) -> (X >>s 31)
2147 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002148 if (C->isZero()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002149 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002150 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002151 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002152 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002153 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002154 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002155 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002156 return BinaryOperator::create(Instruction::AShr,
2157 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002158 }
2159 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002160 }
2161 else if (SI->getOpcode() == Instruction::AShr) {
2162 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2163 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002164 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002165 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002166 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002167 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002168 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002169 }
2170 }
2171 }
Chris Lattner022167f2004-03-13 00:11:49 +00002172 }
Chris Lattner183b3362004-04-09 19:05:30 +00002173
2174 // Try to fold constant sub into select arguments.
2175 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002176 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002177 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002178
2179 if (isa<PHINode>(Op0))
2180 if (Instruction *NV = FoldOpIntoPhi(I))
2181 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002182 }
2183
Chris Lattnera9be4492005-04-07 16:15:25 +00002184 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2185 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002186 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002187 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002188 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002189 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002190 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002191 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2192 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2193 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002194 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002195 Op1I->getOperand(0));
2196 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002197 }
2198
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002199 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002200 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2201 // is not used by anyone else...
2202 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002203 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002204 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002205 // Swap the two operands of the subexpr...
2206 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2207 Op1I->setOperand(0, IIOp1);
2208 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002209
Chris Lattner3082c5a2003-02-18 19:28:33 +00002210 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002211 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002212 }
2213
2214 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2215 //
2216 if (Op1I->getOpcode() == Instruction::And &&
2217 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2218 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2219
Chris Lattner396dbfe2004-06-09 05:08:07 +00002220 Value *NewNot =
2221 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002222 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002223 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002224
Reid Spencer3c514952006-10-16 23:08:08 +00002225 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002226 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002227 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Shengaafe4e22007-04-19 05:39:12 +00002228 if (CSI->isZero())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002229 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002230 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002231 ConstantExpr::getNeg(DivRHS));
2232
Chris Lattner57c8d992003-02-18 19:57:07 +00002233 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002234 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002235 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002236 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002237 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002238 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002239 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002240 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002241
Chris Lattner7a002fe2006-12-02 00:13:08 +00002242 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002243 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2244 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002245 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2246 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2247 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2248 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002249 } else if (Op0I->getOpcode() == Instruction::Sub) {
2250 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2251 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002252 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002253
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002254 ConstantInt *C1;
2255 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002256 if (X == Op1) // X*C - X --> X * (C-1)
2257 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002258
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002259 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2260 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002261 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002262 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002263 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002264}
2265
Reid Spencer266e42b2006-12-23 06:05:41 +00002266/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002267/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002268static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2269 switch (pred) {
2270 case ICmpInst::ICMP_SLT:
2271 // True if LHS s< RHS and RHS == 0
Zhou Shengaafe4e22007-04-19 05:39:12 +00002272 return RHS->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00002273 case ICmpInst::ICMP_SLE:
2274 // True if LHS s<= RHS and RHS == -1
2275 return RHS->isAllOnesValue();
2276 case ICmpInst::ICMP_UGE:
2277 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002278 return RHS->getValue() ==
2279 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002280 case ICmpInst::ICMP_UGT:
2281 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002282 return RHS->getValue() ==
2283 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002284 default:
2285 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002286 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002287}
2288
Chris Lattner113f4f42002-06-25 16:13:24 +00002289Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002290 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002291 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002292
Chris Lattner81a7a232004-10-16 18:11:37 +00002293 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2295
Chris Lattnere6794492002-08-12 21:17:25 +00002296 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002297 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2298 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002299
2300 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002301 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002302 if (SI->getOpcode() == Instruction::Shl)
2303 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002304 return BinaryOperator::createMul(SI->getOperand(0),
2305 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002306
Zhou Shengaafe4e22007-04-19 05:39:12 +00002307 if (CI->isZero())
Chris Lattnercce81be2003-09-11 22:24:54 +00002308 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2309 if (CI->equalsInt(1)) // X * 1 == X
2310 return ReplaceInstUsesWith(I, Op0);
2311 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002312 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002313
Zhou Sheng4961cf12007-03-29 01:57:21 +00002314 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002315 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002316 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002317 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002318 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002319 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002320 if (Op1F->isNullValue())
2321 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002322
Chris Lattner3082c5a2003-02-18 19:28:33 +00002323 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2324 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2325 if (Op1F->getValue() == 1.0)
2326 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2327 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002328
2329 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2330 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2331 isa<ConstantInt>(Op0I->getOperand(1))) {
2332 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2333 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2334 Op1, "tmp");
2335 InsertNewInstBefore(Add, I);
2336 Value *C1C2 = ConstantExpr::getMul(Op1,
2337 cast<Constant>(Op0I->getOperand(1)));
2338 return BinaryOperator::createAdd(Add, C1C2);
2339
2340 }
Chris Lattner183b3362004-04-09 19:05:30 +00002341
2342 // Try to fold constant mul into select arguments.
2343 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002344 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002345 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002346
2347 if (isa<PHINode>(Op0))
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2349 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002350 }
2351
Chris Lattner934a64cf2003-03-10 23:23:04 +00002352 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2353 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002354 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002355
Chris Lattner2635b522004-02-23 05:39:21 +00002356 // If one of the operands of the multiply is a cast from a boolean value, then
2357 // we know the bool is either zero or one, so this is a 'masking' multiply.
2358 // See if we can simplify things based on how the boolean was originally
2359 // formed.
2360 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002361 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002362 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002363 BoolCast = CI;
2364 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002365 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002366 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002367 BoolCast = CI;
2368 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002369 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002370 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2371 const Type *SCOpTy = SCIOp0->getType();
2372
Reid Spencer266e42b2006-12-23 06:05:41 +00002373 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002374 // multiply into a shift/and combination.
2375 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002376 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002377 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002378 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002379 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002380 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002381 InsertNewInstBefore(
2382 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002383 BoolCast->getOperand(0)->getName()+
2384 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002385
2386 // If the multiply type is not the same as the source type, sign extend
2387 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002388 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002389 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2390 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002391 Instruction::CastOps opcode =
2392 (SrcBits == DstBits ? Instruction::BitCast :
2393 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2394 V = InsertCastBefore(opcode, V, I.getType(), I);
2395 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002396
Chris Lattner2635b522004-02-23 05:39:21 +00002397 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002398 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002399 }
2400 }
2401 }
2402
Chris Lattner113f4f42002-06-25 16:13:24 +00002403 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002404}
2405
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002406/// This function implements the transforms on div instructions that work
2407/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2408/// used by the visitors to those instructions.
2409/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002410Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002412
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002413 // undef / X -> 0
2414 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002415 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416
2417 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002418 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002419 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002420
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002421 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002422 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2423 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002424 // same basic block, then we replace the select with Y, and the condition
2425 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002426 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002427 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002428 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2429 if (ST->isNullValue()) {
2430 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2431 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002432 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002433 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2434 I.setOperand(1, SI->getOperand(2));
2435 else
2436 UpdateValueUsesWith(SI, SI->getOperand(2));
2437 return &I;
2438 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002439
Chris Lattnerd79dc792006-09-09 20:26:32 +00002440 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2441 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2442 if (ST->isNullValue()) {
2443 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2444 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002445 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002446 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2447 I.setOperand(1, SI->getOperand(1));
2448 else
2449 UpdateValueUsesWith(SI, SI->getOperand(1));
2450 return &I;
2451 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002452 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002453
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002454 return 0;
2455}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002456
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002457/// This function implements the transforms common to both integer division
2458/// instructions (udiv and sdiv). It is called by the visitors to those integer
2459/// division instructions.
2460/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002461Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2463
2464 if (Instruction *Common = commonDivTransforms(I))
2465 return Common;
2466
2467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2468 // div X, 1 == X
2469 if (RHS->equalsInt(1))
2470 return ReplaceInstUsesWith(I, Op0);
2471
2472 // (X / C1) / C2 -> X / (C1*C2)
2473 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2474 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2475 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2476 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002477 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002478 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002479
Reid Spencer6d392062007-03-23 20:05:17 +00002480 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2483 return R;
2484 if (isa<PHINode>(Op0))
2485 if (Instruction *NV = FoldOpIntoPhi(I))
2486 return NV;
2487 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002488 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002489
Chris Lattner3082c5a2003-02-18 19:28:33 +00002490 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002491 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002492 if (LHS->equalsInt(0))
2493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2494
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002495 return 0;
2496}
2497
2498Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2499 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2500
2501 // Handle the integer div common cases
2502 if (Instruction *Common = commonIDivTransforms(I))
2503 return Common;
2504
2505 // X udiv C^2 -> X >> C
2506 // Check to see if this is an unsigned division with an exact power of 2,
2507 // if so, convert to a right shift.
2508 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002509 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002510 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002511 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002512 }
2513
2514 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002515 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002516 if (RHSI->getOpcode() == Instruction::Shl &&
2517 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002518 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002519 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002520 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002521 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002522 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002523 Constant *C2V = ConstantInt::get(NTy, C2);
2524 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002525 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002526 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002527 }
2528 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002529 }
2530
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002531 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2532 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002533 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002534 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002535 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002536 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002537 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002538 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002539 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002540 // Construct the "on true" case of the select
2541 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2542 Instruction *TSI = BinaryOperator::createLShr(
2543 Op0, TC, SI->getName()+".t");
2544 TSI = InsertNewInstBefore(TSI, I);
2545
2546 // Construct the "on false" case of the select
2547 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2548 Instruction *FSI = BinaryOperator::createLShr(
2549 Op0, FC, SI->getName()+".f");
2550 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002551
Reid Spencer3939b1a2007-03-05 23:36:13 +00002552 // construct the select instruction and return it.
2553 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002554 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002555 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002556 return 0;
2557}
2558
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002559Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2561
2562 // Handle the integer div common cases
2563 if (Instruction *Common = commonIDivTransforms(I))
2564 return Common;
2565
2566 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2567 // sdiv X, -1 == -X
2568 if (RHS->isAllOnesValue())
2569 return BinaryOperator::createNeg(Op0);
2570
2571 // -X/C -> X/-C
2572 if (Value *LHSNeg = dyn_castNegVal(Op0))
2573 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2574 }
2575
2576 // If the sign bits of both operands are zero (i.e. we can prove they are
2577 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002578 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002579 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002580 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2581 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2582 }
2583 }
2584
2585 return 0;
2586}
2587
2588Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2589 return commonDivTransforms(I);
2590}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002591
Chris Lattner85dda9a2006-03-02 06:50:58 +00002592/// GetFactor - If we can prove that the specified value is at least a multiple
2593/// of some factor, return that factor.
2594static Constant *GetFactor(Value *V) {
2595 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2596 return CI;
2597
2598 // Unless we can be tricky, we know this is a multiple of 1.
2599 Constant *Result = ConstantInt::get(V->getType(), 1);
2600
2601 Instruction *I = dyn_cast<Instruction>(V);
2602 if (!I) return Result;
2603
2604 if (I->getOpcode() == Instruction::Mul) {
2605 // Handle multiplies by a constant, etc.
2606 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2607 GetFactor(I->getOperand(1)));
2608 } else if (I->getOpcode() == Instruction::Shl) {
2609 // (X<<C) -> X * (1 << C)
2610 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2611 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2612 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2613 }
2614 } else if (I->getOpcode() == Instruction::And) {
2615 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2616 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002617 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002618 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2619 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002620 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002621 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002622 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002623 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002624 if (!CI->isIntegerCast())
2625 return Result;
2626 Value *Op = CI->getOperand(0);
2627 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002628 }
2629 return Result;
2630}
2631
Reid Spencer7eb55b32006-11-02 01:53:59 +00002632/// This function implements the transforms on rem instructions that work
2633/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2634/// is used by the visitors to those instructions.
2635/// @brief Transforms common to all three rem instructions
2636Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002638
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002639 // 0 % X == 0, we don't need to preserve faults!
2640 if (Constant *LHS = dyn_cast<Constant>(Op0))
2641 if (LHS->isNullValue())
2642 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2643
2644 if (isa<UndefValue>(Op0)) // undef % X -> 0
2645 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2646 if (isa<UndefValue>(Op1))
2647 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002648
2649 // Handle cases involving: rem X, (select Cond, Y, Z)
2650 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2651 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2652 // the same basic block, then we replace the select with Y, and the
2653 // condition of the select with false (if the cond value is in the same
2654 // BB). If the select has uses other than the div, this allows them to be
2655 // simplified also.
2656 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2657 if (ST->isNullValue()) {
2658 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2659 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002660 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002661 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2662 I.setOperand(1, SI->getOperand(2));
2663 else
2664 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002665 return &I;
2666 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002667 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2668 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2669 if (ST->isNullValue()) {
2670 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2671 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002672 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002673 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2674 I.setOperand(1, SI->getOperand(1));
2675 else
2676 UpdateValueUsesWith(SI, SI->getOperand(1));
2677 return &I;
2678 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002679 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002680
Reid Spencer7eb55b32006-11-02 01:53:59 +00002681 return 0;
2682}
2683
2684/// This function implements the transforms common to both integer remainder
2685/// instructions (urem and srem). It is called by the visitors to those integer
2686/// remainder instructions.
2687/// @brief Common integer remainder transforms
2688Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2690
2691 if (Instruction *common = commonRemTransforms(I))
2692 return common;
2693
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002694 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002695 // X % 0 == undef, we don't need to preserve faults!
2696 if (RHS->equalsInt(0))
2697 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2698
Chris Lattner3082c5a2003-02-18 19:28:33 +00002699 if (RHS->equalsInt(1)) // X % 1 == 0
2700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2701
Chris Lattnerb70f1412006-02-28 05:49:21 +00002702 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2703 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2704 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2705 return R;
2706 } else if (isa<PHINode>(Op0I)) {
2707 if (Instruction *NV = FoldOpIntoPhi(I))
2708 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002709 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002710 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2711 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002712 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002713 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002714 }
2715
Reid Spencer7eb55b32006-11-02 01:53:59 +00002716 return 0;
2717}
2718
2719Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2720 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2721
2722 if (Instruction *common = commonIRemTransforms(I))
2723 return common;
2724
2725 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2726 // X urem C^2 -> X and C
2727 // Check to see if this is an unsigned remainder with an exact power of 2,
2728 // if so, convert to a bitwise and.
2729 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002730 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002731 return BinaryOperator::createAnd(Op0, SubOne(C));
2732 }
2733
Chris Lattner2e90b732006-02-05 07:54:04 +00002734 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002735 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2736 if (RHSI->getOpcode() == Instruction::Shl &&
2737 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002738 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002739 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2740 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2741 "tmp"), I);
2742 return BinaryOperator::createAnd(Op0, Add);
2743 }
2744 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002745 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002746
Reid Spencer7eb55b32006-11-02 01:53:59 +00002747 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2748 // where C1&C2 are powers of two.
2749 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2750 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2751 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2752 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002753 if ((STO->getValue().isPowerOf2()) &&
2754 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002755 Value *TrueAnd = InsertNewInstBefore(
2756 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2757 Value *FalseAnd = InsertNewInstBefore(
2758 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2759 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2760 }
2761 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002762 }
2763
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002764 return 0;
2765}
2766
Reid Spencer7eb55b32006-11-02 01:53:59 +00002767Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2769
2770 if (Instruction *common = commonIRemTransforms(I))
2771 return common;
2772
2773 if (Value *RHSNeg = dyn_castNegVal(Op1))
2774 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002775 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002776 // X % -Y -> X % Y
2777 AddUsesToWorkList(I);
2778 I.setOperand(1, RHSNeg);
2779 return &I;
2780 }
2781
2782 // If the top bits of both operands are zero (i.e. we can prove they are
2783 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002784 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002785 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2786 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2787 return BinaryOperator::createURem(Op0, Op1, I.getName());
2788 }
2789
2790 return 0;
2791}
2792
2793Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002794 return commonRemTransforms(I);
2795}
2796
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002797// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002798static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002799 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002800 if (isSigned) {
2801 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002802 APInt Val(APInt::getSignedMaxValue(TypeBits));
2803 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002804 }
Reid Spenceref599b02007-03-19 21:10:28 +00002805 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002806}
2807
2808// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002809static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2810 if (isSigned) {
2811 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002812 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2813 APInt Val(APInt::getSignedMinValue(TypeBits));
2814 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002815 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002816 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002817}
2818
Chris Lattner35167c32004-06-09 07:59:58 +00002819// isOneBitSet - Return true if there is exactly one bit set in the specified
2820// constant.
2821static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002822 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002823}
2824
Chris Lattner8fc5af42004-09-23 21:46:38 +00002825// isHighOnes - Return true if the constant is of the form 1+0+.
2826// This is the same as lowones(~X).
2827static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002828 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002829}
2830
Reid Spencer266e42b2006-12-23 06:05:41 +00002831/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002832/// are carefully arranged to allow folding of expressions such as:
2833///
2834/// (A < B) | (A > B) --> (A != B)
2835///
Reid Spencer266e42b2006-12-23 06:05:41 +00002836/// Note that this is only valid if the first and second predicates have the
2837/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002838///
Reid Spencer266e42b2006-12-23 06:05:41 +00002839/// Three bits are used to represent the condition, as follows:
2840/// 0 A > B
2841/// 1 A == B
2842/// 2 A < B
2843///
2844/// <=> Value Definition
2845/// 000 0 Always false
2846/// 001 1 A > B
2847/// 010 2 A == B
2848/// 011 3 A >= B
2849/// 100 4 A < B
2850/// 101 5 A != B
2851/// 110 6 A <= B
2852/// 111 7 Always true
2853///
2854static unsigned getICmpCode(const ICmpInst *ICI) {
2855 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002856 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002857 case ICmpInst::ICMP_UGT: return 1; // 001
2858 case ICmpInst::ICMP_SGT: return 1; // 001
2859 case ICmpInst::ICMP_EQ: return 2; // 010
2860 case ICmpInst::ICMP_UGE: return 3; // 011
2861 case ICmpInst::ICMP_SGE: return 3; // 011
2862 case ICmpInst::ICMP_ULT: return 4; // 100
2863 case ICmpInst::ICMP_SLT: return 4; // 100
2864 case ICmpInst::ICMP_NE: return 5; // 101
2865 case ICmpInst::ICMP_ULE: return 6; // 110
2866 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002867 // True -> 7
2868 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002869 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002870 return 0;
2871 }
2872}
2873
Reid Spencer266e42b2006-12-23 06:05:41 +00002874/// getICmpValue - This is the complement of getICmpCode, which turns an
2875/// opcode and two operands into either a constant true or false, or a brand
2876/// new /// ICmp instruction. The sign is passed in to determine which kind
2877/// of predicate to use in new icmp instructions.
2878static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2879 switch (code) {
2880 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002881 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002882 case 1:
2883 if (sign)
2884 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2885 else
2886 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2887 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2888 case 3:
2889 if (sign)
2890 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2891 else
2892 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2893 case 4:
2894 if (sign)
2895 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2896 else
2897 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2898 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2899 case 6:
2900 if (sign)
2901 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2902 else
2903 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002904 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002905 }
2906}
2907
Reid Spencer266e42b2006-12-23 06:05:41 +00002908static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2909 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2910 (ICmpInst::isSignedPredicate(p1) &&
2911 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2912 (ICmpInst::isSignedPredicate(p2) &&
2913 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2914}
2915
2916namespace {
2917// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2918struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002919 InstCombiner &IC;
2920 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002921 ICmpInst::Predicate pred;
2922 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2923 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2924 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002925 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002926 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2927 if (PredicatesFoldable(pred, ICI->getPredicate()))
2928 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2929 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002930 return false;
2931 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002932 Instruction *apply(Instruction &Log) const {
2933 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2934 if (ICI->getOperand(0) != LHS) {
2935 assert(ICI->getOperand(1) == LHS);
2936 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002937 }
2938
Chris Lattnerd1bce952007-03-13 14:27:42 +00002939 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002940 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002941 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002942 unsigned Code;
2943 switch (Log.getOpcode()) {
2944 case Instruction::And: Code = LHSCode & RHSCode; break;
2945 case Instruction::Or: Code = LHSCode | RHSCode; break;
2946 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002947 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002948 }
2949
Chris Lattnerd1bce952007-03-13 14:27:42 +00002950 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2951 ICmpInst::isSignedPredicate(ICI->getPredicate());
2952
2953 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002954 if (Instruction *I = dyn_cast<Instruction>(RV))
2955 return I;
2956 // Otherwise, it's a constant boolean value...
2957 return IC.ReplaceInstUsesWith(Log, RV);
2958 }
2959};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002960} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002961
Chris Lattnerba1cb382003-09-19 17:17:26 +00002962// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2963// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002964// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002965Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002966 ConstantInt *OpRHS,
2967 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002968 BinaryOperator &TheAnd) {
2969 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002970 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002971 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002972 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002973
Chris Lattnerba1cb382003-09-19 17:17:26 +00002974 switch (Op->getOpcode()) {
2975 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002976 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002977 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002978 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002979 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002980 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002981 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002982 }
2983 break;
2984 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002985 if (Together == AndRHS) // (X | C) & C --> C
2986 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002987
Chris Lattner86102b82005-01-01 16:22:27 +00002988 if (Op->hasOneUse() && Together != OpRHS) {
2989 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002990 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002991 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002992 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002993 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002994 }
2995 break;
2996 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002997 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002998 // Adding a one to a single bit bit-field should be turned into an XOR
2999 // of the bit. First thing to check is to see if this AND is with a
3000 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003001 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003002
3003 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003004 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003005 // Ok, at this point, we know that we are masking the result of the
3006 // ADD down to exactly one bit. If the constant we are adding has
3007 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003008 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003009
Chris Lattnerba1cb382003-09-19 17:17:26 +00003010 // Check to see if any bits below the one bit set in AndRHSV are set.
3011 if ((AddRHS & (AndRHSV-1)) == 0) {
3012 // If not, the only thing that can effect the output of the AND is
3013 // the bit specified by AndRHSV. If that bit is set, the effect of
3014 // the XOR is to toggle the bit. If it is clear, then the ADD has
3015 // no effect.
3016 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3017 TheAnd.setOperand(0, X);
3018 return &TheAnd;
3019 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003020 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003021 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003022 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003023 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003024 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003025 }
3026 }
3027 }
3028 }
3029 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003030
3031 case Instruction::Shl: {
3032 // We know that the AND will not produce any of the bits shifted in, so if
3033 // the anded constant includes them, clear them now!
3034 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003035 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003036 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003037 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3038 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003039
Zhou Shengb3a80b12007-03-29 08:15:12 +00003040 if (CI->getValue() == ShlMask) {
3041 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003042 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3043 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003044 TheAnd.setOperand(1, CI);
3045 return &TheAnd;
3046 }
3047 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003048 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003049 case Instruction::LShr:
3050 {
Chris Lattner2da29172003-09-19 19:05:02 +00003051 // We know that the AND will not produce any of the bits shifted in, so if
3052 // the anded constant includes them, clear them now! This only applies to
3053 // unsigned shifts, because a signed shr may bring in set bits!
3054 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003055 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003056 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003057 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3058 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003059
Zhou Shengb3a80b12007-03-29 08:15:12 +00003060 if (CI->getValue() == ShrMask) {
3061 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003062 return ReplaceInstUsesWith(TheAnd, Op);
3063 } else if (CI != AndRHS) {
3064 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3065 return &TheAnd;
3066 }
3067 break;
3068 }
3069 case Instruction::AShr:
3070 // Signed shr.
3071 // See if this is shifting in some sign extension, then masking it out
3072 // with an and.
3073 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003074 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003075 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003076 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3077 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003078 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003079 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003080 // Make the argument unsigned.
3081 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003082 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003083 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003084 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003085 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003086 }
Chris Lattner2da29172003-09-19 19:05:02 +00003087 }
3088 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003089 }
3090 return 0;
3091}
3092
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003093
Chris Lattner6862fbd2004-09-29 17:40:11 +00003094/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3095/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003096/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3097/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003098/// insert new instructions.
3099Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003100 bool isSigned, bool Inside,
3101 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003102 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003103 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003104 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003105
Chris Lattner6862fbd2004-09-29 17:40:11 +00003106 if (Inside) {
3107 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003108 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003109
Reid Spencer266e42b2006-12-23 06:05:41 +00003110 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003111 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003112 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003113 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3114 return new ICmpInst(pred, V, Hi);
3115 }
3116
3117 // Emit V-Lo <u Hi-Lo
3118 Constant *NegLo = ConstantExpr::getNeg(Lo);
3119 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003120 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003121 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3122 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003123 }
3124
3125 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003126 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003127
Reid Spencerf4071162007-03-21 23:19:50 +00003128 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003129 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003130 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003131 ICmpInst::Predicate pred = (isSigned ?
3132 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3133 return new ICmpInst(pred, V, Hi);
3134 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003135
Reid Spencerf4071162007-03-21 23:19:50 +00003136 // Emit V-Lo >u Hi-1-Lo
3137 // Note that Hi has already had one subtracted from it, above.
3138 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003139 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003140 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003141 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3142 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003143}
3144
Chris Lattnerb4b25302005-09-18 07:22:02 +00003145// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3146// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3147// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3148// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003149static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003150 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003151 uint32_t BitWidth = Val->getType()->getBitWidth();
3152 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003153
3154 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003155 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003156 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003157 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003158 return true;
3159}
3160
Chris Lattnerb4b25302005-09-18 07:22:02 +00003161/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3162/// where isSub determines whether the operator is a sub. If we can fold one of
3163/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003164///
3165/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3166/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3167/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3168///
3169/// return (A +/- B).
3170///
3171Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003172 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003173 Instruction &I) {
3174 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3175 if (!LHSI || LHSI->getNumOperands() != 2 ||
3176 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3177
3178 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3179
3180 switch (LHSI->getOpcode()) {
3181 default: return 0;
3182 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003183 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003184 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003185 if ((Mask->getValue().countLeadingZeros() +
3186 Mask->getValue().countPopulation()) ==
3187 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003188 break;
3189
3190 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3191 // part, we don't need any explicit masks to take them out of A. If that
3192 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003193 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003194 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003195 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003196 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003197 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003198 break;
3199 }
3200 }
Chris Lattneraf517572005-09-18 04:24:45 +00003201 return 0;
3202 case Instruction::Or:
3203 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003204 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003205 if ((Mask->getValue().countLeadingZeros() +
3206 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003207 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003208 break;
3209 return 0;
3210 }
3211
3212 Instruction *New;
3213 if (isSub)
3214 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3215 else
3216 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3217 return InsertNewInstBefore(New, I);
3218}
3219
Chris Lattner113f4f42002-06-25 16:13:24 +00003220Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003221 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003223
Chris Lattner81a7a232004-10-16 18:11:37 +00003224 if (isa<UndefValue>(Op1)) // X & undef -> 0
3225 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3226
Chris Lattner86102b82005-01-01 16:22:27 +00003227 // and X, X = X
3228 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003229 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003230
Chris Lattner5b2edb12006-02-12 08:02:11 +00003231 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003232 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003233 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003234 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3235 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3236 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003237 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003238 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003239 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003240 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003241 if (CP->isAllOnesValue())
3242 return ReplaceInstUsesWith(I, I.getOperand(0));
3243 }
3244 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003245
Zhou Sheng75b871f2007-01-11 12:24:14 +00003246 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003247 const APInt& AndRHSMask = AndRHS->getValue();
3248 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003249
Chris Lattnerba1cb382003-09-19 17:17:26 +00003250 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003251 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003252 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003253 Value *Op0LHS = Op0I->getOperand(0);
3254 Value *Op0RHS = Op0I->getOperand(1);
3255 switch (Op0I->getOpcode()) {
3256 case Instruction::Xor:
3257 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003258 // If the mask is only needed on one incoming arm, push it up.
3259 if (Op0I->hasOneUse()) {
3260 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3261 // Not masking anything out for the LHS, move to RHS.
3262 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3263 Op0RHS->getName()+".masked");
3264 InsertNewInstBefore(NewRHS, I);
3265 return BinaryOperator::create(
3266 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003267 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003268 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003269 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3270 // Not masking anything out for the RHS, move to LHS.
3271 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3272 Op0LHS->getName()+".masked");
3273 InsertNewInstBefore(NewLHS, I);
3274 return BinaryOperator::create(
3275 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3276 }
3277 }
3278
Chris Lattner86102b82005-01-01 16:22:27 +00003279 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003280 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003281 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3282 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3283 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3284 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3285 return BinaryOperator::createAnd(V, AndRHS);
3286 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3287 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003288 break;
3289
3290 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003291 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3292 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3293 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3294 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3295 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003296 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003297 }
3298
Chris Lattner16464b32003-07-23 19:25:52 +00003299 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003300 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003301 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003302 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003303 // If this is an integer truncation or change from signed-to-unsigned, and
3304 // if the source is an and/or with immediate, transform it. This
3305 // frequently occurs for bitfield accesses.
3306 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003307 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003308 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003309 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003310 if (CastOp->getOpcode() == Instruction::And) {
3311 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003312 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3313 // This will fold the two constants together, which may allow
3314 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003315 Instruction *NewCast = CastInst::createTruncOrBitCast(
3316 CastOp->getOperand(0), I.getType(),
3317 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003318 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003319 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003320 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003321 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003322 return BinaryOperator::createAnd(NewCast, C3);
3323 } else if (CastOp->getOpcode() == Instruction::Or) {
3324 // Change: and (cast (or X, C1) to T), C2
3325 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003326 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003327 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3328 return ReplaceInstUsesWith(I, AndRHS);
3329 }
3330 }
Chris Lattner33217db2003-07-23 19:36:21 +00003331 }
Chris Lattner183b3362004-04-09 19:05:30 +00003332
3333 // Try to fold constant and into select arguments.
3334 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003335 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003336 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003337 if (isa<PHINode>(Op0))
3338 if (Instruction *NV = FoldOpIntoPhi(I))
3339 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003340 }
3341
Chris Lattnerbb74e222003-03-10 23:06:50 +00003342 Value *Op0NotVal = dyn_castNotVal(Op0);
3343 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003344
Chris Lattner023a4832004-06-18 06:07:51 +00003345 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3346 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3347
Misha Brukman9c003d82004-07-30 12:50:08 +00003348 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003349 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003350 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3351 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003352 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003353 return BinaryOperator::createNot(Or);
3354 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003355
3356 {
3357 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003358 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3359 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3360 return ReplaceInstUsesWith(I, Op1);
3361 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3362 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3363 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003364
3365 if (Op0->hasOneUse() &&
3366 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3367 if (A == Op1) { // (A^B)&A -> A&(A^B)
3368 I.swapOperands(); // Simplify below
3369 std::swap(Op0, Op1);
3370 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3371 cast<BinaryOperator>(Op0)->swapOperands();
3372 I.swapOperands(); // Simplify below
3373 std::swap(Op0, Op1);
3374 }
3375 }
3376 if (Op1->hasOneUse() &&
3377 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3378 if (B == Op0) { // B&(A^B) -> B&(B^A)
3379 cast<BinaryOperator>(Op1)->swapOperands();
3380 std::swap(A, B);
3381 }
3382 if (A == Op0) { // A&(A^B) -> A & ~B
3383 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3384 InsertNewInstBefore(NotB, I);
3385 return BinaryOperator::createAnd(A, NotB);
3386 }
3387 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003388 }
3389
Reid Spencer266e42b2006-12-23 06:05:41 +00003390 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3391 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3392 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003393 return R;
3394
Chris Lattner623826c2004-09-28 21:48:02 +00003395 Value *LHSVal, *RHSVal;
3396 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003397 ICmpInst::Predicate LHSCC, RHSCC;
3398 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3399 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3400 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3401 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3402 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3403 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3404 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3405 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003406 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003407 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3408 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3409 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3410 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003411 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003412 std::swap(LHS, RHS);
3413 std::swap(LHSCst, RHSCst);
3414 std::swap(LHSCC, RHSCC);
3415 }
3416
Reid Spencer266e42b2006-12-23 06:05:41 +00003417 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003418 // comparing a value against two constants and and'ing the result
3419 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003420 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3421 // (from the FoldICmpLogical check above), that the two constants
3422 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003423 assert(LHSCst != RHSCst && "Compares not folded above?");
3424
3425 switch (LHSCC) {
3426 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003427 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003428 switch (RHSCC) {
3429 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003430 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3431 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3432 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003433 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003434 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3435 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3436 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003437 return ReplaceInstUsesWith(I, LHS);
3438 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003439 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003440 switch (RHSCC) {
3441 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003442 case ICmpInst::ICMP_ULT:
3443 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3444 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3445 break; // (X != 13 & X u< 15) -> no change
3446 case ICmpInst::ICMP_SLT:
3447 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3448 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3449 break; // (X != 13 & X s< 15) -> no change
3450 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3451 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3452 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003453 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003454 case ICmpInst::ICMP_NE:
3455 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003456 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3457 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3458 LHSVal->getName()+".off");
3459 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003460 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3461 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003462 }
3463 break; // (X != 13 & X != 15) -> no change
3464 }
3465 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003466 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003467 switch (RHSCC) {
3468 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003469 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3470 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003471 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003472 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3473 break;
3474 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3475 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003476 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003477 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3478 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003479 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003480 break;
3481 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003482 switch (RHSCC) {
3483 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003484 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3485 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003486 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003487 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3488 break;
3489 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3490 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003491 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003492 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3493 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003494 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003495 break;
3496 case ICmpInst::ICMP_UGT:
3497 switch (RHSCC) {
3498 default: assert(0 && "Unknown integer condition code!");
3499 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3500 return ReplaceInstUsesWith(I, LHS);
3501 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3502 return ReplaceInstUsesWith(I, RHS);
3503 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3504 break;
3505 case ICmpInst::ICMP_NE:
3506 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3507 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3508 break; // (X u> 13 & X != 15) -> no change
3509 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3510 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3511 true, I);
3512 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3513 break;
3514 }
3515 break;
3516 case ICmpInst::ICMP_SGT:
3517 switch (RHSCC) {
3518 default: assert(0 && "Unknown integer condition code!");
3519 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3520 return ReplaceInstUsesWith(I, LHS);
3521 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3522 return ReplaceInstUsesWith(I, RHS);
3523 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3524 break;
3525 case ICmpInst::ICMP_NE:
3526 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3527 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3528 break; // (X s> 13 & X != 15) -> no change
3529 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3530 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3531 true, I);
3532 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3533 break;
3534 }
3535 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003536 }
3537 }
3538 }
3539
Chris Lattner3af10532006-05-05 06:39:07 +00003540 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003541 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3542 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3543 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3544 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003545 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003546 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003547 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3548 I.getType(), TD) &&
3549 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3550 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003551 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3552 Op1C->getOperand(0),
3553 I.getName());
3554 InsertNewInstBefore(NewOp, I);
3555 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3556 }
Chris Lattner3af10532006-05-05 06:39:07 +00003557 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003558
3559 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003560 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3561 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3562 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003563 SI0->getOperand(1) == SI1->getOperand(1) &&
3564 (SI0->hasOneUse() || SI1->hasOneUse())) {
3565 Instruction *NewOp =
3566 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3567 SI1->getOperand(0),
3568 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003569 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3570 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003571 }
Chris Lattner3af10532006-05-05 06:39:07 +00003572 }
3573
Chris Lattner113f4f42002-06-25 16:13:24 +00003574 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003575}
3576
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003577/// CollectBSwapParts - Look to see if the specified value defines a single byte
3578/// in the result. If it does, and if the specified byte hasn't been filled in
3579/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003580static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003581 Instruction *I = dyn_cast<Instruction>(V);
3582 if (I == 0) return true;
3583
3584 // If this is an or instruction, it is an inner node of the bswap.
3585 if (I->getOpcode() == Instruction::Or)
3586 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3587 CollectBSwapParts(I->getOperand(1), ByteValues);
3588
Zhou Shengb25806f2007-03-30 09:29:48 +00003589 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003590 // If this is a shift by a constant int, and it is "24", then its operand
3591 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003592 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003593 // Not shifting the entire input by N-1 bytes?
Zhou Shengb25806f2007-03-30 09:29:48 +00003594 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003595 8*(ByteValues.size()-1))
3596 return true;
3597
3598 unsigned DestNo;
3599 if (I->getOpcode() == Instruction::Shl) {
3600 // X << 24 defines the top byte with the lowest of the input bytes.
3601 DestNo = ByteValues.size()-1;
3602 } else {
3603 // X >>u 24 defines the low byte with the highest of the input bytes.
3604 DestNo = 0;
3605 }
3606
3607 // If the destination byte value is already defined, the values are or'd
3608 // together, which isn't a bswap (unless it's an or of the same bits).
3609 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3610 return true;
3611 ByteValues[DestNo] = I->getOperand(0);
3612 return false;
3613 }
3614
3615 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3616 // don't have this.
3617 Value *Shift = 0, *ShiftLHS = 0;
3618 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3619 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3620 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3621 return true;
3622 Instruction *SI = cast<Instruction>(Shift);
3623
3624 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Shengb25806f2007-03-30 09:29:48 +00003625 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3626 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003627 return true;
3628
3629 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3630 unsigned DestByte;
Zhou Shengb25806f2007-03-30 09:29:48 +00003631 if (AndAmt->getValue().getActiveBits() > 64)
3632 return true;
3633 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003634 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Shengb25806f2007-03-30 09:29:48 +00003635 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003636 break;
3637 // Unknown mask for bswap.
3638 if (DestByte == ByteValues.size()) return true;
3639
Reid Spencere0fc4df2006-10-20 07:07:24 +00003640 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003641 unsigned SrcByte;
3642 if (SI->getOpcode() == Instruction::Shl)
3643 SrcByte = DestByte - ShiftBytes;
3644 else
3645 SrcByte = DestByte + ShiftBytes;
3646
3647 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3648 if (SrcByte != ByteValues.size()-DestByte-1)
3649 return true;
3650
3651 // If the destination byte value is already defined, the values are or'd
3652 // together, which isn't a bswap (unless it's an or of the same bits).
3653 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3654 return true;
3655 ByteValues[DestByte] = SI->getOperand(0);
3656 return false;
3657}
3658
3659/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3660/// If so, insert the new bswap intrinsic and return it.
3661Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003662 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3663 if (!ITy || ITy->getBitWidth() % 16)
3664 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003665
3666 /// ByteValues - For each byte of the result, we keep track of which value
3667 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003668 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003669 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003670
3671 // Try to find all the pieces corresponding to the bswap.
3672 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3673 CollectBSwapParts(I.getOperand(1), ByteValues))
3674 return 0;
3675
3676 // Check to see if all of the bytes come from the same value.
3677 Value *V = ByteValues[0];
3678 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3679
3680 // Check to make sure that all of the bytes come from the same value.
3681 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3682 if (ByteValues[i] != V)
3683 return 0;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003684 const Type *Tys[] = { ITy, ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003685 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003686 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003687 return new CallInst(F, V);
3688}
3689
3690
Chris Lattner113f4f42002-06-25 16:13:24 +00003691Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003692 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003694
Chris Lattner3a8248f2007-03-24 23:56:43 +00003695 if (isa<UndefValue>(Op1)) // X | undef -> -1
3696 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003697
Chris Lattner5b2edb12006-02-12 08:02:11 +00003698 // or X, X = X
3699 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003700 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003701
Chris Lattner5b2edb12006-02-12 08:02:11 +00003702 // See if we can simplify any instructions used by the instruction whose sole
3703 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003704 if (!isa<VectorType>(I.getType())) {
3705 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3706 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3707 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3708 KnownZero, KnownOne))
3709 return &I;
3710 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003711
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003712 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003713 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003714 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003715 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3716 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003717 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003718 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003719 Or->takeName(Op0);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003720 return BinaryOperator::createAnd(Or,
3721 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003722 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003723
Chris Lattnerd4252a72004-07-30 07:50:03 +00003724 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3725 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003726 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003727 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003728 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003729 return BinaryOperator::createXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003730 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003731 }
Chris Lattner183b3362004-04-09 19:05:30 +00003732
3733 // Try to fold constant and into select arguments.
3734 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003735 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003736 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003737 if (isa<PHINode>(Op0))
3738 if (Instruction *NV = FoldOpIntoPhi(I))
3739 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003740 }
3741
Chris Lattner330628a2006-01-06 17:59:59 +00003742 Value *A = 0, *B = 0;
3743 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003744
3745 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3746 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3747 return ReplaceInstUsesWith(I, Op1);
3748 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3749 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3750 return ReplaceInstUsesWith(I, Op0);
3751
Chris Lattnerb7845d62006-07-10 20:25:24 +00003752 // (A | B) | C and A | (B | C) -> bswap if possible.
3753 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003754 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003755 match(Op1, m_Or(m_Value(), m_Value())) ||
3756 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3757 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003758 if (Instruction *BSwap = MatchBSwap(I))
3759 return BSwap;
3760 }
3761
Chris Lattnerb62f5082005-05-09 04:58:36 +00003762 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3763 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003764 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003765 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3766 InsertNewInstBefore(NOr, I);
3767 NOr->takeName(Op0);
3768 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003769 }
3770
3771 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3772 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003773 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003774 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3775 InsertNewInstBefore(NOr, I);
3776 NOr->takeName(Op0);
3777 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003778 }
3779
Chris Lattner1150df92007-04-08 07:47:01 +00003780 // (A & C)|(B & D)
3781 Value *C, *D;
3782 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3783 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner7621a032007-04-08 07:55:22 +00003784 Value *V1 = 0, *V2 = 0, *V3 = 0;
3785 C1 = dyn_cast<ConstantInt>(C);
3786 C2 = dyn_cast<ConstantInt>(D);
3787 if (C1 && C2) { // (A & C1)|(B & C2)
3788 // If we have: ((V + N) & C1) | (V & C2)
3789 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3790 // replace with V+N.
3791 if (C1->getValue() == ~C2->getValue()) {
3792 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3793 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3794 // Add commutes, try both ways.
3795 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3796 return ReplaceInstUsesWith(I, A);
3797 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3798 return ReplaceInstUsesWith(I, A);
3799 }
3800 // Or commutes, try both ways.
3801 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3802 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3803 // Add commutes, try both ways.
3804 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3805 return ReplaceInstUsesWith(I, B);
3806 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3807 return ReplaceInstUsesWith(I, B);
3808 }
3809 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00003810 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00003811 }
3812
Chris Lattner1150df92007-04-08 07:47:01 +00003813 // Check to see if we have any common things being and'ed. If so, find the
3814 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00003815 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3816 if (A == B) // (A & C)|(A & D) == A & (C|D)
3817 V1 = A, V2 = C, V3 = D;
3818 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3819 V1 = A, V2 = B, V3 = C;
3820 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3821 V1 = C, V2 = A, V3 = D;
3822 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3823 V1 = C, V2 = A, V3 = B;
3824
3825 if (V1) {
3826 Value *Or =
3827 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3828 return BinaryOperator::createAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00003829 }
Chris Lattner1150df92007-04-08 07:47:01 +00003830
3831 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
Chris Lattnerc8d37882007-04-08 08:01:49 +00003832 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner1150df92007-04-08 07:47:01 +00003833 // Try all combination of terms to find V3 and ~V3.
3834 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3835 if (V3 == B)
3836 V1 = D, V2 = C;
3837 else if (V3 == D)
3838 V1 = B, V2 = C;
3839 }
3840 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3841 if (V3 == A)
3842 V1 = C, V2 = D;
3843 else if (V3 == C)
3844 V1 = A, V2 = D;
3845 }
3846 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3847 if (V3 == B)
3848 V1 = D, V2 = A;
3849 else if (V3 == D)
3850 V1 = B, V2 = A;
3851 }
3852 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3853 if (V3 == A)
3854 V1 = C, V2 = B;
3855 else if (V3 == C)
3856 V1 = A, V2 = B;
3857 }
3858 if (V1) {
3859 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3860 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3861 return BinaryOperator::createXor(A, V2);
3862 }
3863 }
3864 }
Chris Lattner15212982005-09-18 03:42:07 +00003865 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003866
3867 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003868 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3869 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3870 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003871 SI0->getOperand(1) == SI1->getOperand(1) &&
3872 (SI0->hasOneUse() || SI1->hasOneUse())) {
3873 Instruction *NewOp =
3874 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3875 SI1->getOperand(0),
3876 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003877 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3878 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003879 }
3880 }
Chris Lattner812aab72003-08-12 19:11:07 +00003881
Chris Lattnerd4252a72004-07-30 07:50:03 +00003882 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3883 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003884 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003885 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003886 } else {
3887 A = 0;
3888 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003889 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003890 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3891 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003892 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003893 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003894
Misha Brukman9c003d82004-07-30 12:50:08 +00003895 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003896 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3897 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3898 I.getName()+".demorgan"), I);
3899 return BinaryOperator::createNot(And);
3900 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003901 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003902
Reid Spencer266e42b2006-12-23 06:05:41 +00003903 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3904 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3905 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003906 return R;
3907
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003908 Value *LHSVal, *RHSVal;
3909 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003910 ICmpInst::Predicate LHSCC, RHSCC;
3911 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3912 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3913 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3914 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3915 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3916 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3917 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3918 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003919 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003920 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3921 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3922 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3923 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003924 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003925 std::swap(LHS, RHS);
3926 std::swap(LHSCst, RHSCst);
3927 std::swap(LHSCC, RHSCC);
3928 }
3929
Reid Spencer266e42b2006-12-23 06:05:41 +00003930 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003931 // comparing a value against two constants and or'ing the result
3932 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003933 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3934 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003935 // equal.
3936 assert(LHSCst != RHSCst && "Compares not folded above?");
3937
3938 switch (LHSCC) {
3939 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003940 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003941 switch (RHSCC) {
3942 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003943 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003944 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3945 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3946 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3947 LHSVal->getName()+".off");
3948 InsertNewInstBefore(Add, I);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003949 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003950 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003951 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003952 break; // (X == 13 | X == 15) -> no change
3953 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3954 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003955 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003956 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3957 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3958 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003959 return ReplaceInstUsesWith(I, RHS);
3960 }
3961 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003962 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003963 switch (RHSCC) {
3964 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003965 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3966 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3967 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003968 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003969 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3970 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3971 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003972 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003973 }
3974 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003975 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003976 switch (RHSCC) {
3977 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003978 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003979 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003980 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3981 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3982 false, I);
3983 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3984 break;
3985 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3986 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003987 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003988 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3989 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003990 }
3991 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003992 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003993 switch (RHSCC) {
3994 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003995 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3996 break;
3997 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3998 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3999 false, I);
4000 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4001 break;
4002 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4003 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4004 return ReplaceInstUsesWith(I, RHS);
4005 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4006 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004007 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004008 break;
4009 case ICmpInst::ICMP_UGT:
4010 switch (RHSCC) {
4011 default: assert(0 && "Unknown integer condition code!");
4012 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4013 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4014 return ReplaceInstUsesWith(I, LHS);
4015 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4016 break;
4017 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4018 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004019 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004020 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4021 break;
4022 }
4023 break;
4024 case ICmpInst::ICMP_SGT:
4025 switch (RHSCC) {
4026 default: assert(0 && "Unknown integer condition code!");
4027 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4028 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4029 return ReplaceInstUsesWith(I, LHS);
4030 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4031 break;
4032 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4033 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004034 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004035 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4036 break;
4037 }
4038 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004039 }
4040 }
4041 }
Chris Lattner3af10532006-05-05 06:39:07 +00004042
4043 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004044 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004045 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004046 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4047 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004048 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004049 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004050 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4051 I.getType(), TD) &&
4052 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4053 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004054 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4055 Op1C->getOperand(0),
4056 I.getName());
4057 InsertNewInstBefore(NewOp, I);
4058 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4059 }
Chris Lattner3af10532006-05-05 06:39:07 +00004060 }
Chris Lattner3af10532006-05-05 06:39:07 +00004061
Chris Lattner15212982005-09-18 03:42:07 +00004062
Chris Lattner113f4f42002-06-25 16:13:24 +00004063 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004064}
4065
Chris Lattnerc2076352004-02-16 01:20:27 +00004066// XorSelf - Implements: X ^ X --> 0
4067struct XorSelf {
4068 Value *RHS;
4069 XorSelf(Value *rhs) : RHS(rhs) {}
4070 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4071 Instruction *apply(BinaryOperator &Xor) const {
4072 return &Xor;
4073 }
4074};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004075
4076
Chris Lattner113f4f42002-06-25 16:13:24 +00004077Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004078 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004080
Chris Lattner81a7a232004-10-16 18:11:37 +00004081 if (isa<UndefValue>(Op1))
4082 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4083
Chris Lattnerc2076352004-02-16 01:20:27 +00004084 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4085 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4086 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004087 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004088 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004089
4090 // See if we can simplify any instructions used by the instruction whose sole
4091 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004092 if (!isa<VectorType>(I.getType())) {
4093 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4094 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4095 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4096 KnownZero, KnownOne))
4097 return &I;
4098 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004099
Zhou Sheng75b871f2007-01-11 12:24:14 +00004100 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004101 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4102 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004103 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004104 return new ICmpInst(ICI->getInversePredicate(),
4105 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004106
Reid Spencer266e42b2006-12-23 06:05:41 +00004107 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004108 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004109 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4110 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004111 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4112 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004113 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004114 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004115 }
Chris Lattner023a4832004-06-18 06:07:51 +00004116
4117 // ~(~X & Y) --> (X | ~Y)
4118 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4119 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4120 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4121 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004122 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004123 Op0I->getOperand(1)->getName()+".not");
4124 InsertNewInstBefore(NotY, I);
4125 return BinaryOperator::createOr(Op0NotVal, NotY);
4126 }
4127 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004128
Chris Lattner97638592003-07-23 21:37:07 +00004129 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004130 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004131 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004132 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004133 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4134 return BinaryOperator::createSub(
4135 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004136 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004137 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004138 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004139 // (X + C) ^ signbit -> (X + C + signbit)
4140 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4141 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004142
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004143 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004144 } else if (Op0I->getOpcode() == Instruction::Or) {
4145 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004146 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004147 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4148 // Anything in both C1 and C2 is known to be zero, remove it from
4149 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004150 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004151 NewRHS = ConstantExpr::getAnd(NewRHS,
4152 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004153 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004154 I.setOperand(0, Op0I->getOperand(0));
4155 I.setOperand(1, NewRHS);
4156 return &I;
4157 }
Chris Lattner97638592003-07-23 21:37:07 +00004158 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004159 }
Chris Lattner183b3362004-04-09 19:05:30 +00004160
4161 // Try to fold constant and into select arguments.
4162 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004163 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004164 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004165 if (isa<PHINode>(Op0))
4166 if (Instruction *NV = FoldOpIntoPhi(I))
4167 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004168 }
4169
Chris Lattnerbb74e222003-03-10 23:06:50 +00004170 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004171 if (X == Op1)
4172 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004173 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004174
Chris Lattnerbb74e222003-03-10 23:06:50 +00004175 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004176 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004177 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004178
Chris Lattner07418422007-03-18 22:51:34 +00004179
4180 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4181 if (Op1I) {
4182 Value *A, *B;
4183 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4184 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004185 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004186 I.swapOperands();
4187 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004188 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004189 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004190 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004191 }
Chris Lattner07418422007-03-18 22:51:34 +00004192 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4193 if (Op0 == A) // A^(A^B) == B
4194 return ReplaceInstUsesWith(I, B);
4195 else if (Op0 == B) // A^(B^A) == B
4196 return ReplaceInstUsesWith(I, A);
4197 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004198 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004199 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004200 std::swap(A, B);
4201 }
Chris Lattner07418422007-03-18 22:51:34 +00004202 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004203 I.swapOperands(); // Simplified below.
4204 std::swap(Op0, Op1);
4205 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004206 }
Chris Lattner07418422007-03-18 22:51:34 +00004207 }
4208
4209 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4210 if (Op0I) {
4211 Value *A, *B;
4212 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4213 if (A == Op1) // (B|A)^B == (A|B)^B
4214 std::swap(A, B);
4215 if (B == Op1) { // (A|B)^B == A & ~B
4216 Instruction *NotB =
4217 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4218 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004219 }
Chris Lattner07418422007-03-18 22:51:34 +00004220 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4221 if (Op1 == A) // (A^B)^A == B
4222 return ReplaceInstUsesWith(I, B);
4223 else if (Op1 == B) // (B^A)^A == B
4224 return ReplaceInstUsesWith(I, A);
4225 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4226 if (A == Op1) // (A&B)^A -> (B&A)^A
4227 std::swap(A, B);
4228 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004229 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004230 Instruction *N =
4231 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004232 return BinaryOperator::createAnd(N, Op1);
4233 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004234 }
Chris Lattner07418422007-03-18 22:51:34 +00004235 }
4236
4237 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4238 if (Op0I && Op1I && Op0I->isShift() &&
4239 Op0I->getOpcode() == Op1I->getOpcode() &&
4240 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4241 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4242 Instruction *NewOp =
4243 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4244 Op1I->getOperand(0),
4245 Op0I->getName()), I);
4246 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4247 Op1I->getOperand(1));
4248 }
4249
4250 if (Op0I && Op1I) {
4251 Value *A, *B, *C, *D;
4252 // (A & B)^(A | B) -> A ^ B
4253 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4254 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4255 if ((A == C && B == D) || (A == D && B == C))
4256 return BinaryOperator::createXor(A, B);
4257 }
4258 // (A | B)^(A & B) -> A ^ B
4259 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4260 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4261 if ((A == C && B == D) || (A == D && B == C))
4262 return BinaryOperator::createXor(A, B);
4263 }
4264
4265 // (A & B)^(C & D)
4266 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4267 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4268 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4269 // (X & Y)^(X & Y) -> (Y^Z) & X
4270 Value *X = 0, *Y = 0, *Z = 0;
4271 if (A == C)
4272 X = A, Y = B, Z = D;
4273 else if (A == D)
4274 X = A, Y = B, Z = C;
4275 else if (B == C)
4276 X = B, Y = A, Z = D;
4277 else if (B == D)
4278 X = B, Y = A, Z = C;
4279
4280 if (X) {
4281 Instruction *NewOp =
4282 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4283 return BinaryOperator::createAnd(NewOp, X);
4284 }
4285 }
4286 }
4287
Reid Spencer266e42b2006-12-23 06:05:41 +00004288 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4289 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4290 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004291 return R;
4292
Chris Lattner3af10532006-05-05 06:39:07 +00004293 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004294 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004295 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004296 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4297 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004298 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004299 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004300 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4301 I.getType(), TD) &&
4302 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4303 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004304 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4305 Op1C->getOperand(0),
4306 I.getName());
4307 InsertNewInstBefore(NewOp, I);
4308 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4309 }
Chris Lattner3af10532006-05-05 06:39:07 +00004310 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004311
Chris Lattner113f4f42002-06-25 16:13:24 +00004312 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004313}
4314
Chris Lattner6862fbd2004-09-29 17:40:11 +00004315/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4316/// overflowed for this type.
4317static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004318 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004319 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004320
Reid Spencerf4071162007-03-21 23:19:50 +00004321 if (IsSigned)
4322 if (In2->getValue().isNegative())
4323 return Result->getValue().sgt(In1->getValue());
4324 else
4325 return Result->getValue().slt(In1->getValue());
4326 else
4327 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004328}
4329
Chris Lattner0798af32005-01-13 20:14:25 +00004330/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4331/// code necessary to compute the offset from the base pointer (without adding
4332/// in the base pointer). Return the result as a signed integer of intptr size.
4333static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4334 TargetData &TD = IC.getTargetData();
4335 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004336 const Type *IntPtrTy = TD.getIntPtrType();
4337 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004338
4339 // Build a mask for high order bits.
Chris Lattner6e880872007-04-28 04:52:43 +00004340 unsigned IntPtrWidth = TD.getPointerSize()*8;
4341 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner0798af32005-01-13 20:14:25 +00004342
Chris Lattner0798af32005-01-13 20:14:25 +00004343 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4344 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004345 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner6e880872007-04-28 04:52:43 +00004346 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4347 if (OpC->isZero()) continue;
4348
4349 // Handle a struct index, which adds its field offset to the pointer.
4350 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4351 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4352
4353 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4354 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattneracbf6a42007-04-28 00:57:34 +00004355 else
Chris Lattner6e880872007-04-28 04:52:43 +00004356 Result = IC.InsertNewInstBefore(
4357 BinaryOperator::createAdd(Result,
4358 ConstantInt::get(IntPtrTy, Size),
4359 GEP->getName()+".offs"), I);
4360 continue;
Chris Lattneracbf6a42007-04-28 00:57:34 +00004361 }
Chris Lattner6e880872007-04-28 04:52:43 +00004362
4363 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4364 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4365 Scale = ConstantExpr::getMul(OC, Scale);
4366 if (Constant *RC = dyn_cast<Constant>(Result))
4367 Result = ConstantExpr::getAdd(RC, Scale);
4368 else {
4369 // Emit an add instruction.
4370 Result = IC.InsertNewInstBefore(
4371 BinaryOperator::createAdd(Result, Scale,
4372 GEP->getName()+".offs"), I);
Chris Lattneracbf6a42007-04-28 00:57:34 +00004373 }
Chris Lattner6e880872007-04-28 04:52:43 +00004374 continue;
Chris Lattner0798af32005-01-13 20:14:25 +00004375 }
Chris Lattner6e880872007-04-28 04:52:43 +00004376 // Convert to correct type.
4377 if (Op->getType() != IntPtrTy) {
4378 if (Constant *OpC = dyn_cast<Constant>(Op))
4379 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4380 else
4381 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4382 Op->getName()+".c"), I);
4383 }
4384 if (Size != 1) {
4385 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4386 if (Constant *OpC = dyn_cast<Constant>(Op))
4387 Op = ConstantExpr::getMul(OpC, Scale);
4388 else // We'll let instcombine(mul) convert this to a shl if possible.
4389 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4390 GEP->getName()+".idx"), I);
4391 }
4392
4393 // Emit an add instruction.
4394 if (isa<Constant>(Op) && isa<Constant>(Result))
4395 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4396 cast<Constant>(Result));
4397 else
4398 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4399 GEP->getName()+".offs"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004400 }
4401 return Result;
4402}
4403
Reid Spencer266e42b2006-12-23 06:05:41 +00004404/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004405/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004406Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4407 ICmpInst::Predicate Cond,
4408 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004409 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004410
4411 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4412 if (isa<PointerType>(CI->getOperand(0)->getType()))
4413 RHS = CI->getOperand(0);
4414
Chris Lattner0798af32005-01-13 20:14:25 +00004415 Value *PtrBase = GEPLHS->getOperand(0);
4416 if (PtrBase == RHS) {
4417 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004418 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4419 // each index is zero or not.
4420 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004421 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004422 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4423 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004424 bool EmitIt = true;
4425 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4426 if (isa<UndefValue>(C)) // undef index -> undef.
4427 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4428 if (C->isNullValue())
4429 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004430 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4431 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004432 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004433 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004434 ConstantInt::get(Type::Int1Ty,
4435 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004436 }
4437
4438 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004439 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004440 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004441 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4442 if (InVal == 0)
4443 InVal = Comp;
4444 else {
4445 InVal = InsertNewInstBefore(InVal, I);
4446 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004447 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004448 InVal = BinaryOperator::createOr(InVal, Comp);
4449 else // True if all are equal
4450 InVal = BinaryOperator::createAnd(InVal, Comp);
4451 }
4452 }
4453 }
4454
4455 if (InVal)
4456 return InVal;
4457 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004458 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004459 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4460 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004461 }
Chris Lattner0798af32005-01-13 20:14:25 +00004462
Reid Spencer266e42b2006-12-23 06:05:41 +00004463 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004464 // the result to fold to a constant!
4465 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4466 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4467 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004468 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4469 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004470 }
4471 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004472 // If the base pointers are different, but the indices are the same, just
4473 // compare the base pointer.
4474 if (PtrBase != GEPRHS->getOperand(0)) {
4475 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004476 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004477 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004478 if (IndicesTheSame)
4479 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4480 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4481 IndicesTheSame = false;
4482 break;
4483 }
4484
4485 // If all indices are the same, just compare the base pointers.
4486 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004487 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4488 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004489
4490 // Otherwise, the base pointers are different and the indices are
4491 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004492 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004493 }
Chris Lattner0798af32005-01-13 20:14:25 +00004494
Chris Lattner81e84172005-01-13 22:25:21 +00004495 // If one of the GEPs has all zero indices, recurse.
4496 bool AllZeros = true;
4497 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4498 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4499 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4500 AllZeros = false;
4501 break;
4502 }
4503 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004504 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4505 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004506
4507 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004508 AllZeros = true;
4509 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4510 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4511 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4512 AllZeros = false;
4513 break;
4514 }
4515 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004516 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004517
Chris Lattner4fa89822005-01-14 00:20:05 +00004518 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4519 // If the GEPs only differ by one index, compare it.
4520 unsigned NumDifferences = 0; // Keep track of # differences.
4521 unsigned DiffOperand = 0; // The operand that differs.
4522 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4523 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004524 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4525 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004526 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004527 NumDifferences = 2;
4528 break;
4529 } else {
4530 if (NumDifferences++) break;
4531 DiffOperand = i;
4532 }
4533 }
4534
4535 if (NumDifferences == 0) // SAME GEP?
4536 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004537 ConstantInt::get(Type::Int1Ty,
4538 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004539 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004540 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4541 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 // Make sure we do a signed comparison here.
4543 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004544 }
4545 }
4546
Reid Spencer266e42b2006-12-23 06:05:41 +00004547 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004548 // the result to fold to a constant!
4549 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4550 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4551 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4552 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4553 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004555 }
4556 }
4557 return 0;
4558}
4559
Reid Spencer266e42b2006-12-23 06:05:41 +00004560Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4561 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004563
Chris Lattner6ee923f2007-01-14 19:42:17 +00004564 // Fold trivial predicates.
4565 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4566 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4567 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4568 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4569
4570 // Simplify 'fcmp pred X, X'
4571 if (Op0 == Op1) {
4572 switch (I.getPredicate()) {
4573 default: assert(0 && "Unknown predicate!");
4574 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4575 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4576 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4577 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4578 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4579 case FCmpInst::FCMP_OLT: // True if ordered and less than
4580 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4581 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4582
4583 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4584 case FCmpInst::FCMP_ULT: // True if unordered or less than
4585 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4586 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4587 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4588 I.setPredicate(FCmpInst::FCMP_UNO);
4589 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4590 return &I;
4591
4592 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4593 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4594 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4595 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4596 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4597 I.setPredicate(FCmpInst::FCMP_ORD);
4598 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4599 return &I;
4600 }
4601 }
4602
Reid Spencer266e42b2006-12-23 06:05:41 +00004603 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004604 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004605
Reid Spencer266e42b2006-12-23 06:05:41 +00004606 // Handle fcmp with constant RHS
4607 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4608 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4609 switch (LHSI->getOpcode()) {
4610 case Instruction::PHI:
4611 if (Instruction *NV = FoldOpIntoPhi(I))
4612 return NV;
4613 break;
4614 case Instruction::Select:
4615 // If either operand of the select is a constant, we can fold the
4616 // comparison into the select arms, which will cause one to be
4617 // constant folded and the select turned into a bitwise or.
4618 Value *Op1 = 0, *Op2 = 0;
4619 if (LHSI->hasOneUse()) {
4620 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4621 // Fold the known value into the constant operand.
4622 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4623 // Insert a new FCmp of the other select operand.
4624 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4625 LHSI->getOperand(2), RHSC,
4626 I.getName()), I);
4627 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4628 // Fold the known value into the constant operand.
4629 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4630 // Insert a new FCmp of the other select operand.
4631 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4632 LHSI->getOperand(1), RHSC,
4633 I.getName()), I);
4634 }
4635 }
4636
4637 if (Op1)
4638 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4639 break;
4640 }
4641 }
4642
4643 return Changed ? &I : 0;
4644}
4645
4646Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4647 bool Changed = SimplifyCompare(I);
4648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4649 const Type *Ty = Op0->getType();
4650
4651 // icmp X, X
4652 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004653 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4654 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004655
4656 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004657 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004658
4659 // icmp of GlobalValues can never equal each other as long as they aren't
4660 // external weak linkage type.
4661 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4662 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4663 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004664 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4665 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004666
4667 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004668 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004669 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4670 isa<ConstantPointerNull>(Op0)) &&
4671 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004672 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004673 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4674 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004675
Reid Spencer266e42b2006-12-23 06:05:41 +00004676 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004677 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004678 switch (I.getPredicate()) {
4679 default: assert(0 && "Invalid icmp instruction!");
4680 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004681 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004682 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004683 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004684 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004685 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004686 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004687
Reid Spencer266e42b2006-12-23 06:05:41 +00004688 case ICmpInst::ICMP_UGT:
4689 case ICmpInst::ICMP_SGT:
4690 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004691 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004692 case ICmpInst::ICMP_ULT:
4693 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004694 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4695 InsertNewInstBefore(Not, I);
4696 return BinaryOperator::createAnd(Not, Op1);
4697 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004698 case ICmpInst::ICMP_UGE:
4699 case ICmpInst::ICMP_SGE:
4700 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004701 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004702 case ICmpInst::ICMP_ULE:
4703 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004704 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4705 InsertNewInstBefore(Not, I);
4706 return BinaryOperator::createOr(Not, Op1);
4707 }
4708 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004709 }
4710
Chris Lattner2dd01742004-06-09 04:24:29 +00004711 // See if we are doing a comparison between a constant and an instruction that
4712 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004713 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004714 switch (I.getPredicate()) {
4715 default: break;
4716 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4717 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004718 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004719 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4720 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4721 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4722 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00004723 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4724 if (CI->isMinValue(true))
4725 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4726 ConstantInt::getAllOnesValue(Op0->getType()));
4727
Reid Spencer266e42b2006-12-23 06:05:41 +00004728 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004729
Reid Spencer266e42b2006-12-23 06:05:41 +00004730 case ICmpInst::ICMP_SLT:
4731 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004732 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004733 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4734 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4735 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4736 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4737 break;
4738
4739 case ICmpInst::ICMP_UGT:
4740 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004741 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004742 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4743 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4744 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4745 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00004746
4747 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4748 if (CI->isMaxValue(true))
4749 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4750 ConstantInt::getNullValue(Op0->getType()));
Reid Spencer266e42b2006-12-23 06:05:41 +00004751 break;
4752
4753 case ICmpInst::ICMP_SGT:
4754 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004755 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004756 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4757 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4758 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4759 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4760 break;
4761
4762 case ICmpInst::ICMP_ULE:
4763 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004764 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004765 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4766 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4767 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4768 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4769 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004770
Reid Spencer266e42b2006-12-23 06:05:41 +00004771 case ICmpInst::ICMP_SLE:
4772 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004773 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004774 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4775 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4776 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4777 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4778 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004779
Reid Spencer266e42b2006-12-23 06:05:41 +00004780 case ICmpInst::ICMP_UGE:
4781 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004782 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004783 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4784 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4785 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4786 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4787 break;
4788
4789 case ICmpInst::ICMP_SGE:
4790 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004791 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004792 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4793 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4794 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4795 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4796 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004797 }
4798
Reid Spencer266e42b2006-12-23 06:05:41 +00004799 // If we still have a icmp le or icmp ge instruction, turn it into the
4800 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004801 // already been handled above, this requires little checking.
4802 //
Reid Spencer624766f2007-03-25 19:55:33 +00004803 switch (I.getPredicate()) {
4804 default: break;
4805 case ICmpInst::ICMP_ULE:
4806 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4807 case ICmpInst::ICMP_SLE:
4808 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4809 case ICmpInst::ICMP_UGE:
4810 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4811 case ICmpInst::ICMP_SGE:
4812 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4813 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004814
4815 // See if we can fold the comparison based on bits known to be zero or one
4816 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004817 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4818 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4819 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004820 KnownZero, KnownOne, 0))
4821 return &I;
4822
4823 // Given the known and unknown bits, compute a range that the LHS could be
4824 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004825 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004826 // Compute the Min, Max and RHS values based on the known bits. For the
4827 // EQ and NE we use unsigned values.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00004828 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4829 const APInt& RHSVal = CI->getValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00004830 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004831 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4832 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004833 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004834 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4835 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004836 }
4837 switch (I.getPredicate()) { // LE/GE have been folded already.
4838 default: assert(0 && "Unknown icmp opcode!");
4839 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004840 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004841 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004842 break;
4843 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004844 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004845 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004846 break;
4847 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004848 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004849 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004850 if (Min.uge(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004851 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004852 break;
4853 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004854 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004855 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004856 if (Max.ule(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004857 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004858 break;
4859 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004860 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004861 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004862 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004863 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004864 break;
4865 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004866 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004867 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00004868 if (Max.sle(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004869 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004871 }
4872 }
4873
Reid Spencer266e42b2006-12-23 06:05:41 +00004874 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004875 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004876 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004877 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00004878 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4879 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004880 }
4881
Chris Lattnera74deaf2007-04-03 17:43:25 +00004882 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00004883 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4884 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4885 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004886 case Instruction::GetElementPtr:
4887 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004888 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00004889 bool isAllZeros = true;
4890 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4891 if (!isa<Constant>(LHSI->getOperand(i)) ||
4892 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4893 isAllZeros = false;
4894 break;
4895 }
4896 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004897 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00004898 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4899 }
4900 break;
4901
Chris Lattner77c32c32005-04-23 15:31:55 +00004902 case Instruction::PHI:
4903 if (Instruction *NV = FoldOpIntoPhi(I))
4904 return NV;
4905 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00004906 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00004907 // If either operand of the select is a constant, we can fold the
4908 // comparison into the select arms, which will cause one to be
4909 // constant folded and the select turned into a bitwise or.
4910 Value *Op1 = 0, *Op2 = 0;
4911 if (LHSI->hasOneUse()) {
4912 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4913 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004914 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4915 // Insert a new ICmp of the other select operand.
4916 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4917 LHSI->getOperand(2), RHSC,
4918 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004919 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4920 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4922 // Insert a new ICmp of the other select operand.
4923 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4924 LHSI->getOperand(1), RHSC,
4925 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004926 }
4927 }
Jeff Cohen82639852005-04-23 21:38:35 +00004928
Chris Lattner77c32c32005-04-23 15:31:55 +00004929 if (Op1)
4930 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4931 break;
4932 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00004933 case Instruction::Malloc:
4934 // If we have (malloc != null), and if the malloc has a single use, we
4935 // can assume it is successful and remove the malloc.
4936 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4937 AddToWorkList(LHSI);
4938 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4939 !isTrueWhenEqual(I)));
4940 }
4941 break;
4942 }
Chris Lattner77c32c32005-04-23 15:31:55 +00004943 }
4944
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00004946 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004947 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004948 return NI;
4949 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004950 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4951 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004952 return NI;
4953
Reid Spencer266e42b2006-12-23 06:05:41 +00004954 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00004955 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4956 // now.
4957 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4958 if (isa<PointerType>(Op0->getType()) &&
4959 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004960 // We keep moving the cast from the left operand over to the right
4961 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00004962 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004963
Chris Lattner64d87b02007-01-06 01:45:59 +00004964 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4965 // so eliminate it as well.
4966 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4967 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004968
Chris Lattner16930792003-11-03 04:25:02 +00004969 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00004970 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00004971 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004972 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004973 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00004974 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00004975 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004976 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004977 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00004978 }
Chris Lattner64d87b02007-01-06 01:45:59 +00004979 }
4980
4981 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004982 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00004983 // This comes up when you have code like
4984 // int X = A < B;
4985 // if (X) ...
4986 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004987 // with a constant or another cast from the same type.
4988 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004989 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004990 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004991 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004992
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004993 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00004994 Value *A, *B, *C, *D;
4995 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4996 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4997 Value *OtherVal = A == Op1 ? B : A;
4998 return new ICmpInst(I.getPredicate(), OtherVal,
4999 Constant::getNullValue(A->getType()));
5000 }
5001
5002 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5003 // A^c1 == C^c2 --> A == C^(c1^c2)
5004 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5005 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5006 if (Op1->hasOneUse()) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00005007 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner17c7c032007-01-05 03:04:57 +00005008 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5009 return new ICmpInst(I.getPredicate(), A,
5010 InsertNewInstBefore(Xor, I));
5011 }
5012
5013 // A^B == A^D -> B == D
5014 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5015 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5016 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5017 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5018 }
5019 }
5020
5021 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5022 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005023 // A == (A^B) -> B == 0
5024 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 return new ICmpInst(I.getPredicate(), OtherVal,
5026 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005027 }
5028 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005029 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005030 return new ICmpInst(I.getPredicate(), B,
5031 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005032 }
5033 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005034 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005035 return new ICmpInst(I.getPredicate(), B,
5036 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005037 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005038
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005039 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5040 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5041 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5042 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5043 Value *X = 0, *Y = 0, *Z = 0;
5044
5045 if (A == C) {
5046 X = B; Y = D; Z = A;
5047 } else if (A == D) {
5048 X = B; Y = C; Z = A;
5049 } else if (B == C) {
5050 X = A; Y = D; Z = B;
5051 } else if (B == D) {
5052 X = A; Y = C; Z = B;
5053 }
5054
5055 if (X) { // Build (X^Y) & Z
5056 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5057 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5058 I.setOperand(0, Op1);
5059 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5060 return &I;
5061 }
5062 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005063 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005064 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005065}
5066
Chris Lattnera74deaf2007-04-03 17:43:25 +00005067/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5068///
5069Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5070 Instruction *LHSI,
5071 ConstantInt *RHS) {
5072 const APInt &RHSV = RHS->getValue();
5073
5074 switch (LHSI->getOpcode()) {
Duncan Sandsf01a47c2007-04-04 06:42:45 +00005075 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00005076 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5077 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5078 // fold the xor.
5079 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5080 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5081 Value *CompareVal = LHSI->getOperand(0);
5082
5083 // If the sign bit of the XorCST is not set, there is no change to
5084 // the operation, just stop using the Xor.
5085 if (!XorCST->getValue().isNegative()) {
5086 ICI.setOperand(0, CompareVal);
5087 AddToWorkList(LHSI);
5088 return &ICI;
5089 }
5090
5091 // Was the old condition true if the operand is positive?
5092 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5093
5094 // If so, the new one isn't.
5095 isTrueIfPositive ^= true;
5096
5097 if (isTrueIfPositive)
5098 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5099 else
5100 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5101 }
5102 }
5103 break;
5104 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5105 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5106 LHSI->getOperand(0)->hasOneUse()) {
5107 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5108
5109 // If the LHS is an AND of a truncating cast, we can widen the
5110 // and/compare to be the input width without changing the value
5111 // produced, eliminating a cast.
5112 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5113 // We can do this transformation if either the AND constant does not
5114 // have its sign bit set or if it is an equality comparison.
5115 // Extending a relational comparison when we're checking the sign
5116 // bit would not work.
5117 if (Cast->hasOneUse() &&
5118 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5119 RHSV.isPositive())) {
5120 uint32_t BitWidth =
5121 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5122 APInt NewCST = AndCST->getValue();
5123 NewCST.zext(BitWidth);
5124 APInt NewCI = RHSV;
5125 NewCI.zext(BitWidth);
5126 Instruction *NewAnd =
5127 BinaryOperator::createAnd(Cast->getOperand(0),
5128 ConstantInt::get(NewCST),LHSI->getName());
5129 InsertNewInstBefore(NewAnd, ICI);
5130 return new ICmpInst(ICI.getPredicate(), NewAnd,
5131 ConstantInt::get(NewCI));
5132 }
5133 }
5134
5135 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5136 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5137 // happens a LOT in code produced by the C front-end, for bitfield
5138 // access.
5139 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5140 if (Shift && !Shift->isShift())
5141 Shift = 0;
5142
5143 ConstantInt *ShAmt;
5144 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5145 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5146 const Type *AndTy = AndCST->getType(); // Type of the and.
5147
5148 // We can fold this as long as we can't shift unknown bits
5149 // into the mask. This can only happen with signed shift
5150 // rights, as they sign-extend.
5151 if (ShAmt) {
5152 bool CanFold = Shift->isLogicalShift();
5153 if (!CanFold) {
5154 // To test for the bad case of the signed shr, see if any
5155 // of the bits shifted in could be tested after the mask.
5156 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5157 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5158
5159 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5160 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5161 AndCST->getValue()) == 0)
5162 CanFold = true;
5163 }
5164
5165 if (CanFold) {
5166 Constant *NewCst;
5167 if (Shift->getOpcode() == Instruction::Shl)
5168 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5169 else
5170 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5171
5172 // Check to see if we are shifting out any of the bits being
5173 // compared.
5174 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5175 // If we shifted bits out, the fold is not going to work out.
5176 // As a special case, check to see if this means that the
5177 // result is always true or false now.
5178 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5179 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5180 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5181 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5182 } else {
5183 ICI.setOperand(1, NewCst);
5184 Constant *NewAndCST;
5185 if (Shift->getOpcode() == Instruction::Shl)
5186 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5187 else
5188 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5189 LHSI->setOperand(1, NewAndCST);
5190 LHSI->setOperand(0, Shift->getOperand(0));
5191 AddToWorkList(Shift); // Shift is dead.
5192 AddUsesToWorkList(ICI);
5193 return &ICI;
5194 }
5195 }
5196 }
5197
5198 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5199 // preferable because it allows the C<<Y expression to be hoisted out
5200 // of a loop if Y is invariant and X is not.
5201 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5202 ICI.isEquality() && !Shift->isArithmeticShift() &&
5203 isa<Instruction>(Shift->getOperand(0))) {
5204 // Compute C << Y.
5205 Value *NS;
5206 if (Shift->getOpcode() == Instruction::LShr) {
5207 NS = BinaryOperator::createShl(AndCST,
5208 Shift->getOperand(1), "tmp");
5209 } else {
5210 // Insert a logical shift.
5211 NS = BinaryOperator::createLShr(AndCST,
5212 Shift->getOperand(1), "tmp");
5213 }
5214 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5215
5216 // Compute X & (C << Y).
5217 Instruction *NewAnd =
5218 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5219 InsertNewInstBefore(NewAnd, ICI);
5220
5221 ICI.setOperand(0, NewAnd);
5222 return &ICI;
5223 }
5224 }
5225 break;
5226
5227 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5228 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5229 if (ICI.isEquality()) {
5230 uint32_t TypeBits = RHSV.getBitWidth();
5231
5232 // Check that the shift amount is in range. If not, don't perform
5233 // undefined shifts. When the shift is visited it will be
5234 // simplified.
5235 if (ShAmt->uge(TypeBits))
5236 break;
5237
5238 // If we are comparing against bits always shifted out, the
5239 // comparison cannot succeed.
5240 Constant *Comp =
5241 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5242 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5243 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5244 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5245 return ReplaceInstUsesWith(ICI, Cst);
5246 }
5247
5248 if (LHSI->hasOneUse()) {
5249 // Otherwise strength reduce the shift into an and.
5250 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5251 Constant *Mask =
5252 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5253
5254 Instruction *AndI =
5255 BinaryOperator::createAnd(LHSI->getOperand(0),
5256 Mask, LHSI->getName()+".mask");
5257 Value *And = InsertNewInstBefore(AndI, ICI);
5258 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnere5bbb3c2007-04-03 23:29:39 +00005259 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00005260 }
5261 }
5262 }
5263 break;
5264
5265 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5266 case Instruction::AShr:
5267 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5268 if (ICI.isEquality()) {
5269 // Check that the shift amount is in range. If not, don't perform
5270 // undefined shifts. When the shift is visited it will be
5271 // simplified.
5272 uint32_t TypeBits = RHSV.getBitWidth();
5273 if (ShAmt->uge(TypeBits))
5274 break;
5275 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5276
5277 // If we are comparing against bits always shifted out, the
5278 // comparison cannot succeed.
5279 APInt Comp = RHSV << ShAmtVal;
5280 if (LHSI->getOpcode() == Instruction::LShr)
5281 Comp = Comp.lshr(ShAmtVal);
5282 else
5283 Comp = Comp.ashr(ShAmtVal);
5284
5285 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5286 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5287 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5288 return ReplaceInstUsesWith(ICI, Cst);
5289 }
5290
5291 if (LHSI->hasOneUse() || RHSV == 0) {
5292 // Otherwise strength reduce the shift into an and.
5293 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5294 Constant *Mask = ConstantInt::get(Val);
5295
5296 Instruction *AndI =
5297 BinaryOperator::createAnd(LHSI->getOperand(0),
5298 Mask, LHSI->getName()+".mask");
5299 Value *And = InsertNewInstBefore(AndI, ICI);
5300 return new ICmpInst(ICI.getPredicate(), And,
5301 ConstantExpr::getShl(RHS, ShAmt));
5302 }
5303 }
5304 }
5305 break;
5306
5307 case Instruction::SDiv:
5308 case Instruction::UDiv:
5309 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5310 // Fold this div into the comparison, producing a range check.
5311 // Determine, based on the divide type, what the range is being
5312 // checked. If there is an overflow on the low or high side, remember
5313 // it, otherwise compute the range [low, hi) bounding the new value.
5314 // See: InsertRangeTest above for the kinds of replacements possible.
5315 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5316 // FIXME: If the operand types don't match the type of the divide
5317 // then don't attempt this transform. The code below doesn't have the
5318 // logic to deal with a signed divide and an unsigned compare (and
5319 // vice versa). This is because (x /s C1) <s C2 produces different
5320 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5321 // (x /u C1) <u C2. Simply casting the operands and result won't
5322 // work. :( The if statement below tests that condition and bails
5323 // if it finds it.
5324 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5325 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5326 break;
5327 if (DivRHS->isZero())
5328 break; // Don't hack on div by zero
5329
5330 // Initialize the variables that will indicate the nature of the
5331 // range check.
5332 bool LoOverflow = false, HiOverflow = false;
5333 ConstantInt *LoBound = 0, *HiBound = 0;
5334
5335 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5336 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5337 // C2 (CI). By solving for X we can turn this into a range check
5338 // instead of computing a divide.
5339 ConstantInt *Prod = Multiply(RHS, DivRHS);
5340
5341 // Determine if the product overflows by seeing if the product is
5342 // not equal to the divide. Make sure we do the same kind of divide
5343 // as in the LHS instruction that we're folding.
5344 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5345 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5346
5347 // Get the ICmp opcode
5348 ICmpInst::Predicate predicate = ICI.getPredicate();
5349
5350 if (!DivIsSigned) { // udiv
5351 LoBound = Prod;
5352 LoOverflow = ProdOV;
5353 HiOverflow = ProdOV ||
5354 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5355 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5356 if (RHSV == 0) { // (X / pos) op 0
5357 // Can't overflow.
5358 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5359 HiBound = DivRHS;
5360 } else if (RHSV.isPositive()) { // (X / pos) op pos
5361 LoBound = Prod;
5362 LoOverflow = ProdOV;
5363 HiOverflow = ProdOV ||
5364 AddWithOverflow(HiBound, Prod, DivRHS, true);
5365 } else { // (X / pos) op neg
5366 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5367 LoOverflow = AddWithOverflow(LoBound, Prod,
5368 cast<ConstantInt>(DivRHSH), true);
5369 HiBound = AddOne(Prod);
5370 HiOverflow = ProdOV;
5371 }
5372 } else { // Divisor is < 0.
5373 if (RHSV == 0) { // (X / neg) op 0
5374 LoBound = AddOne(DivRHS);
5375 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5376 if (HiBound == DivRHS)
5377 LoBound = 0; // - INTMIN = INTMIN
5378 } else if (RHSV.isPositive()) { // (X / neg) op pos
5379 HiOverflow = LoOverflow = ProdOV;
5380 if (!LoOverflow)
5381 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5382 true);
5383 HiBound = AddOne(Prod);
5384 } else { // (X / neg) op neg
5385 LoBound = Prod;
5386 LoOverflow = HiOverflow = ProdOV;
5387 HiBound = Subtract(Prod, DivRHS);
5388 }
5389
5390 // Dividing by a negate swaps the condition.
5391 predicate = ICmpInst::getSwappedPredicate(predicate);
5392 }
5393
5394 if (LoBound) {
5395 Value *X = LHSI->getOperand(0);
5396 switch (predicate) {
5397 default: assert(0 && "Unhandled icmp opcode!");
5398 case ICmpInst::ICMP_EQ:
5399 if (LoOverflow && HiOverflow)
5400 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5401 else if (HiOverflow)
5402 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5403 ICmpInst::ICMP_UGE, X, LoBound);
5404 else if (LoOverflow)
5405 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5406 ICmpInst::ICMP_ULT, X, HiBound);
5407 else
5408 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5409 true, ICI);
5410 case ICmpInst::ICMP_NE:
5411 if (LoOverflow && HiOverflow)
5412 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5413 else if (HiOverflow)
5414 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5415 ICmpInst::ICMP_ULT, X, LoBound);
5416 else if (LoOverflow)
5417 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5418 ICmpInst::ICMP_UGE, X, HiBound);
5419 else
5420 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5421 false, ICI);
5422 case ICmpInst::ICMP_ULT:
5423 case ICmpInst::ICMP_SLT:
5424 if (LoOverflow)
5425 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5426 return new ICmpInst(predicate, X, LoBound);
5427 case ICmpInst::ICMP_UGT:
5428 case ICmpInst::ICMP_SGT:
5429 if (HiOverflow)
5430 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5431 if (predicate == ICmpInst::ICMP_UGT)
5432 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5433 else
5434 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5435 }
5436 }
5437 }
5438 break;
5439 }
5440
5441 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5442 if (ICI.isEquality()) {
5443 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5444
5445 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5446 // the second operand is a constant, simplify a bit.
5447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5448 switch (BO->getOpcode()) {
5449 case Instruction::SRem:
5450 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5451 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5452 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5453 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5454 Instruction *NewRem =
5455 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5456 BO->getName());
5457 InsertNewInstBefore(NewRem, ICI);
5458 return new ICmpInst(ICI.getPredicate(), NewRem,
5459 Constant::getNullValue(BO->getType()));
5460 }
5461 }
5462 break;
5463 case Instruction::Add:
5464 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5465 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5466 if (BO->hasOneUse())
5467 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5468 Subtract(RHS, BOp1C));
5469 } else if (RHSV == 0) {
5470 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5471 // efficiently invertible, or if the add has just this one use.
5472 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5473
5474 if (Value *NegVal = dyn_castNegVal(BOp1))
5475 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5476 else if (Value *NegVal = dyn_castNegVal(BOp0))
5477 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5478 else if (BO->hasOneUse()) {
5479 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5480 InsertNewInstBefore(Neg, ICI);
5481 Neg->takeName(BO);
5482 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5483 }
5484 }
5485 break;
5486 case Instruction::Xor:
5487 // For the xor case, we can xor two constants together, eliminating
5488 // the explicit xor.
5489 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5490 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5491 ConstantExpr::getXor(RHS, BOC));
5492
5493 // FALLTHROUGH
5494 case Instruction::Sub:
5495 // Replace (([sub|xor] A, B) != 0) with (A != B)
5496 if (RHSV == 0)
5497 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5498 BO->getOperand(1));
5499 break;
5500
5501 case Instruction::Or:
5502 // If bits are being or'd in that are not present in the constant we
5503 // are comparing against, then the comparison could never succeed!
5504 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5505 Constant *NotCI = ConstantExpr::getNot(RHS);
5506 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5507 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5508 isICMP_NE));
5509 }
5510 break;
5511
5512 case Instruction::And:
5513 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5514 // If bits are being compared against that are and'd out, then the
5515 // comparison can never succeed!
5516 if ((RHSV & ~BOC->getValue()) != 0)
5517 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5518 isICMP_NE));
5519
5520 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5521 if (RHS == BOC && RHSV.isPowerOf2())
5522 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5523 ICmpInst::ICMP_NE, LHSI,
5524 Constant::getNullValue(RHS->getType()));
5525
5526 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5527 if (isSignBit(BOC)) {
5528 Value *X = BO->getOperand(0);
5529 Constant *Zero = Constant::getNullValue(X->getType());
5530 ICmpInst::Predicate pred = isICMP_NE ?
5531 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5532 return new ICmpInst(pred, X, Zero);
5533 }
5534
5535 // ((X & ~7) == 0) --> X < 8
5536 if (RHSV == 0 && isHighOnes(BOC)) {
5537 Value *X = BO->getOperand(0);
5538 Constant *NegX = ConstantExpr::getNeg(BOC);
5539 ICmpInst::Predicate pred = isICMP_NE ?
5540 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5541 return new ICmpInst(pred, X, NegX);
5542 }
5543 }
5544 default: break;
5545 }
5546 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5547 // Handle icmp {eq|ne} <intrinsic>, intcst.
5548 if (II->getIntrinsicID() == Intrinsic::bswap) {
5549 AddToWorkList(II);
5550 ICI.setOperand(0, II->getOperand(1));
5551 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5552 return &ICI;
5553 }
5554 }
5555 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattner28d921d2007-04-14 23:32:02 +00005556 // If the LHS is a cast from an integral value of the same size,
5557 // then since we know the RHS is a constant, try to simlify.
Chris Lattnera74deaf2007-04-03 17:43:25 +00005558 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5559 Value *CastOp = Cast->getOperand(0);
5560 const Type *SrcTy = CastOp->getType();
5561 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5562 if (SrcTy->isInteger() &&
5563 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5564 // If this is an unsigned comparison, try to make the comparison use
5565 // smaller constant values.
5566 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5567 // X u< 128 => X s> -1
5568 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5569 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5570 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5571 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5572 // X u> 127 => X s< 0
5573 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5574 Constant::getNullValue(SrcTy));
5575 }
5576 }
5577 }
5578 }
5579 return 0;
5580}
5581
5582/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5583/// We only handle extending casts so far.
5584///
Reid Spencer266e42b2006-12-23 06:05:41 +00005585Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5586 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005587 Value *LHSCIOp = LHSCI->getOperand(0);
5588 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005589 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005590 Value *RHSCIOp;
5591
Reid Spencer266e42b2006-12-23 06:05:41 +00005592 // We only handle extension cast instructions, so far. Enforce this.
5593 if (LHSCI->getOpcode() != Instruction::ZExt &&
5594 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005595 return 0;
5596
Reid Spencer266e42b2006-12-23 06:05:41 +00005597 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5598 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005599
Reid Spencer266e42b2006-12-23 06:05:41 +00005600 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005601 // Not an extension from the same type?
5602 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005603 if (RHSCIOp->getType() != LHSCIOp->getType())
5604 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005605
5606 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5607 // and the other is a zext), then we can't handle this.
5608 if (CI->getOpcode() != LHSCI->getOpcode())
5609 return 0;
5610
5611 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5612 // then we can't handle this.
5613 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5614 return 0;
5615
5616 // Okay, just insert a compare of the reduced operands now!
5617 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005618 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005619
Reid Spencer266e42b2006-12-23 06:05:41 +00005620 // If we aren't dealing with a constant on the RHS, exit early
5621 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5622 if (!CI)
5623 return 0;
5624
5625 // Compute the constant that would happen if we truncated to SrcTy then
5626 // reextended to DestTy.
5627 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5628 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5629
5630 // If the re-extended constant didn't change...
5631 if (Res2 == CI) {
5632 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5633 // For example, we might have:
5634 // %A = sext short %X to uint
5635 // %B = icmp ugt uint %A, 1330
5636 // It is incorrect to transform this into
5637 // %B = icmp ugt short %X, 1330
5638 // because %A may have negative value.
5639 //
5640 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5641 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005642 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005643 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5644 else
5645 return 0;
5646 }
5647
5648 // The re-extended constant changed so the constant cannot be represented
5649 // in the shorter type. Consequently, we cannot emit a simple comparison.
5650
5651 // First, handle some easy cases. We know the result cannot be equal at this
5652 // point so handle the ICI.isEquality() cases
5653 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005654 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005655 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005656 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005657
5658 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5659 // should have been folded away previously and not enter in here.
5660 Value *Result;
5661 if (isSignedCmp) {
5662 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005663 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005664 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005665 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005666 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005667 } else {
5668 // We're performing an unsigned comparison.
5669 if (isSignedExt) {
5670 // We're performing an unsigned comp with a sign extended value.
5671 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005672 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005673 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5674 NegOne, ICI.getName()), ICI);
5675 } else {
5676 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005677 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005678 }
5679 }
5680
5681 // Finally, return the value computed.
5682 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5683 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5684 return ReplaceInstUsesWith(ICI, Result);
5685 } else {
5686 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5687 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5688 "ICmp should be folded!");
5689 if (Constant *CI = dyn_cast<Constant>(Result))
5690 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5691 else
5692 return BinaryOperator::createNot(Result);
5693 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005694}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005695
Reid Spencer2341c222007-02-02 02:16:23 +00005696Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5697 return commonShiftTransforms(I);
5698}
5699
5700Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5701 return commonShiftTransforms(I);
5702}
5703
5704Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5705 return commonShiftTransforms(I);
5706}
5707
5708Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5709 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005710 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005711
5712 // shl X, 0 == X and shr X, 0 == X
5713 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005714 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005715 Op0 == Constant::getNullValue(Op0->getType()))
5716 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005717
Reid Spencer266e42b2006-12-23 06:05:41 +00005718 if (isa<UndefValue>(Op0)) {
5719 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005720 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005721 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005722 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5723 }
5724 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005725 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5726 return ReplaceInstUsesWith(I, Op0);
5727 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005728 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005729 }
5730
Chris Lattnerd4dee402006-11-10 23:38:52 +00005731 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5732 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005733 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005734 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005735 return ReplaceInstUsesWith(I, CSI);
5736
Chris Lattner183b3362004-04-09 19:05:30 +00005737 // Try to fold constant and into select arguments.
5738 if (isa<Constant>(Op0))
5739 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005740 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005741 return R;
5742
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005743 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005744 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005745 if (MaskedValueIsZero(Op0,
5746 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005747 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005748 }
5749 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005750
Reid Spencere0fc4df2006-10-20 07:07:24 +00005751 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005752 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5753 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005754 return 0;
5755}
5756
Reid Spencere0fc4df2006-10-20 07:07:24 +00005757Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005758 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005759 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005760
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005761 // See if we can simplify any instructions used by the instruction whose sole
5762 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005763 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5764 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5765 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005766 KnownZero, KnownOne))
5767 return &I;
5768
Chris Lattner14553932006-01-06 07:12:35 +00005769 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5770 // of a signed value.
5771 //
Zhou Shengb25806f2007-03-30 09:29:48 +00005772 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005773 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005774 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5775 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005776 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005777 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005778 }
Chris Lattner14553932006-01-06 07:12:35 +00005779 }
5780
5781 // ((X*C1) << C2) == (X * (C1 << C2))
5782 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5783 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5784 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5785 return BinaryOperator::createMul(BO->getOperand(0),
5786 ConstantExpr::getShl(BOOp, Op1));
5787
5788 // Try to fold constant and into select arguments.
5789 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5791 return R;
5792 if (isa<PHINode>(Op0))
5793 if (Instruction *NV = FoldOpIntoPhi(I))
5794 return NV;
5795
5796 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005797 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5798 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5799 Value *V1, *V2;
5800 ConstantInt *CC;
5801 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005802 default: break;
5803 case Instruction::Add:
5804 case Instruction::And:
5805 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005806 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005807 // These operators commute.
5808 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005809 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5810 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005811 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005812 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005813 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005814 Op0BO->getName());
5815 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005816 Instruction *X =
5817 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5818 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005819 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005820 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005821 return BinaryOperator::createAnd(X, ConstantInt::get(
5822 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005823 }
Chris Lattner14553932006-01-06 07:12:35 +00005824
Chris Lattner797dee72005-09-18 06:30:59 +00005825 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005826 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005827 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005828 match(Op0BOOp1,
5829 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005830 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5831 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005832 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005833 Op0BO->getOperand(0), Op1,
5834 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005835 InsertNewInstBefore(YS, I); // (Y << C)
5836 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005837 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005838 V1->getName()+".mask");
5839 InsertNewInstBefore(XM, I); // X & (CC << C)
5840
5841 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5842 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005843 }
Chris Lattner14553932006-01-06 07:12:35 +00005844
Reid Spencer2f34b982007-02-02 14:41:37 +00005845 // FALL THROUGH.
5846 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005847 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005848 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5849 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005850 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005851 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005852 Op0BO->getOperand(1), Op1,
5853 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005854 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005855 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005856 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005857 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005858 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005859 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005860 return BinaryOperator::createAnd(X, ConstantInt::get(
5861 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005862 }
Chris Lattner14553932006-01-06 07:12:35 +00005863
Chris Lattner1df0e982006-05-31 21:14:00 +00005864 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005865 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5866 match(Op0BO->getOperand(0),
5867 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005868 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005869 cast<BinaryOperator>(Op0BO->getOperand(0))
5870 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005871 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005872 Op0BO->getOperand(1), Op1,
5873 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005874 InsertNewInstBefore(YS, I); // (Y << C)
5875 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005876 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005877 V1->getName()+".mask");
5878 InsertNewInstBefore(XM, I); // X & (CC << C)
5879
Chris Lattner1df0e982006-05-31 21:14:00 +00005880 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005881 }
Chris Lattner14553932006-01-06 07:12:35 +00005882
Chris Lattner27cb9db2005-09-18 05:12:10 +00005883 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005884 }
Chris Lattner14553932006-01-06 07:12:35 +00005885 }
5886
5887
5888 // If the operand is an bitwise operator with a constant RHS, and the
5889 // shift is the only use, we can pull it out of the shift.
5890 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5891 bool isValid = true; // Valid only for And, Or, Xor
5892 bool highBitSet = false; // Transform if high bit of constant set?
5893
5894 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005895 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005896 case Instruction::Add:
5897 isValid = isLeftShift;
5898 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005899 case Instruction::Or:
5900 case Instruction::Xor:
5901 highBitSet = false;
5902 break;
5903 case Instruction::And:
5904 highBitSet = true;
5905 break;
Chris Lattner14553932006-01-06 07:12:35 +00005906 }
5907
5908 // If this is a signed shift right, and the high bit is modified
5909 // by the logical operation, do not perform the transformation.
5910 // The highBitSet boolean indicates the value of the high bit of
5911 // the constant which would cause it to be modified for this
5912 // operation.
5913 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005914 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005915 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005916 }
5917
5918 if (isValid) {
5919 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5920
5921 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005922 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005923 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005924 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005925
5926 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5927 NewRHS);
5928 }
5929 }
5930 }
5931 }
5932
Chris Lattnereb372a02006-01-06 07:52:12 +00005933 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005934 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5935 if (ShiftOp && !ShiftOp->isShift())
5936 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005937
Reid Spencere0fc4df2006-10-20 07:07:24 +00005938 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005939 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00005940 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5941 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00005942 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5943 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5944 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005945
Zhou Sheng56cda952007-04-02 08:20:41 +00005946 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005947 if (AmtSum > TypeBits)
5948 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005949
5950 const IntegerType *Ty = cast<IntegerType>(I.getType());
5951
5952 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005953 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005954 return BinaryOperator::create(I.getOpcode(), X,
5955 ConstantInt::get(Ty, AmtSum));
5956 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5957 I.getOpcode() == Instruction::AShr) {
5958 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5959 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5960 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5961 I.getOpcode() == Instruction::LShr) {
5962 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5963 Instruction *Shift =
5964 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5965 InsertNewInstBefore(Shift, I);
5966
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005967 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005968 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005969 }
5970
Chris Lattner3e009e82007-02-05 00:57:54 +00005971 // Okay, if we get here, one shift must be left, and the other shift must be
5972 // right. See if the amounts are equal.
5973 if (ShiftAmt1 == ShiftAmt2) {
5974 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5975 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005976 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005977 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005978 }
5979 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5980 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005981 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005982 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005983 }
5984 // We can simplify ((X << C) >>s C) into a trunc + sext.
5985 // NOTE: we could do this for any C, but that would make 'unusual' integer
5986 // types. For now, just stick to ones well-supported by the code
5987 // generators.
5988 const Type *SExtType = 0;
5989 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005990 case 1 :
5991 case 8 :
5992 case 16 :
5993 case 32 :
5994 case 64 :
5995 case 128:
5996 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5997 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005998 default: break;
5999 }
6000 if (SExtType) {
6001 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6002 InsertNewInstBefore(NewTrunc, I);
6003 return new SExtInst(NewTrunc, Ty);
6004 }
6005 // Otherwise, we can't handle it yet.
6006 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00006007 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00006008
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006009 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006010 if (I.getOpcode() == Instruction::Shl) {
6011 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6012 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006013 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00006014 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006015 InsertNewInstBefore(Shift, I);
6016
Reid Spencer52830322007-03-25 21:11:44 +00006017 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6018 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006019 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006020
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006021 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006022 if (I.getOpcode() == Instruction::LShr) {
6023 assert(ShiftOp->getOpcode() == Instruction::Shl);
6024 Instruction *Shift =
6025 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6026 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00006027
Reid Spencer769a5a82007-03-26 17:18:58 +00006028 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006029 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006030 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006031
6032 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6033 } else {
6034 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00006035 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006036
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006037 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006038 if (I.getOpcode() == Instruction::Shl) {
6039 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6040 ShiftOp->getOpcode() == Instruction::AShr);
6041 Instruction *Shift =
6042 BinaryOperator::create(ShiftOp->getOpcode(), X,
6043 ConstantInt::get(Ty, ShiftDiff));
6044 InsertNewInstBefore(Shift, I);
6045
Reid Spencer52830322007-03-25 21:11:44 +00006046 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006047 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006048 }
6049
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006050 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006051 if (I.getOpcode() == Instruction::LShr) {
6052 assert(ShiftOp->getOpcode() == Instruction::Shl);
6053 Instruction *Shift =
6054 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6055 InsertNewInstBefore(Shift, I);
6056
Reid Spencer441486c2007-03-26 23:45:51 +00006057 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006058 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006059 }
6060
6061 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006062 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006063 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006064 return 0;
6065}
6066
Chris Lattner48a44f72002-05-02 17:06:02 +00006067
Chris Lattner8f663e82005-10-29 04:36:15 +00006068/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6069/// expression. If so, decompose it, returning some value X, such that Val is
6070/// X*Scale+Offset.
6071///
6072static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006073 int &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006074 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006075 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006076 Offset = CI->getZExtValue();
6077 Scale = 1;
6078 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006079 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6080 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006081 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006082 if (I->getOpcode() == Instruction::Shl) {
6083 // This is a value scaled by '1 << the shift amt'.
6084 Scale = 1U << CUI->getZExtValue();
6085 Offset = 0;
6086 return I->getOperand(0);
6087 } else if (I->getOpcode() == Instruction::Mul) {
6088 // This value is scaled by 'CUI'.
6089 Scale = CUI->getZExtValue();
6090 Offset = 0;
6091 return I->getOperand(0);
6092 } else if (I->getOpcode() == Instruction::Add) {
6093 // We have X+C. Check to see if we really have (X*C2)+C1,
6094 // where C1 is divisible by C2.
6095 unsigned SubScale;
6096 Value *SubVal =
6097 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6098 Offset += CUI->getZExtValue();
6099 if (SubScale > 1 && (Offset % SubScale == 0)) {
6100 Scale = SubScale;
6101 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006102 }
6103 }
6104 }
6105 }
6106 }
6107
6108 // Otherwise, we can't look past this.
6109 Scale = 1;
6110 Offset = 0;
6111 return Val;
6112}
6113
6114
Chris Lattner216be912005-10-24 06:03:58 +00006115/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6116/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattner1db224d2007-04-27 17:44:50 +00006117Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattner216be912005-10-24 06:03:58 +00006118 AllocationInst &AI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00006119 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattner216be912005-10-24 06:03:58 +00006120
Chris Lattnerac87beb2005-10-24 06:22:12 +00006121 // Remove any uses of AI that are dead.
6122 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006123
Chris Lattnerac87beb2005-10-24 06:22:12 +00006124 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6125 Instruction *User = cast<Instruction>(*UI++);
6126 if (isInstructionTriviallyDead(User)) {
6127 while (UI != E && *UI == User)
6128 ++UI; // If this instruction uses AI more than once, don't break UI.
6129
Chris Lattnerac87beb2005-10-24 06:22:12 +00006130 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006131 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006132 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006133 }
6134 }
6135
Chris Lattner216be912005-10-24 06:03:58 +00006136 // Get the type really allocated and the type casted to.
6137 const Type *AllocElTy = AI.getAllocatedType();
6138 const Type *CastElTy = PTy->getElementType();
6139 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006140
Chris Lattner945e4372007-02-14 05:52:17 +00006141 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6142 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006143 if (CastElTyAlign < AllocElTyAlign) return 0;
6144
Chris Lattner46705b22005-10-24 06:35:18 +00006145 // If the allocation has multiple uses, only promote it if we are strictly
6146 // increasing the alignment of the resultant allocation. If we keep it the
6147 // same, we open the door to infinite loops of various kinds.
6148 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6149
Chris Lattner216be912005-10-24 06:03:58 +00006150 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6151 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006152 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006153
Chris Lattner8270c332005-10-29 03:19:53 +00006154 // See if we can satisfy the modulus by pulling a scale out of the array
6155 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006156 unsigned ArraySizeScale;
6157 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00006158 Value *NumElements = // See if the array size is a decomposable linear expr.
6159 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6160
Chris Lattner8270c332005-10-29 03:19:53 +00006161 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6162 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006163 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6164 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006165
Chris Lattner8270c332005-10-29 03:19:53 +00006166 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6167 Value *Amt = 0;
6168 if (Scale == 1) {
6169 Amt = NumElements;
6170 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006171 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006172 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6173 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00006174 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006175 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006176 else if (Scale != 1) {
6177 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6178 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006179 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006180 }
6181
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006182 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6183 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattner8f663e82005-10-29 04:36:15 +00006184 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6185 Amt = InsertNewInstBefore(Tmp, AI);
6186 }
6187
Chris Lattner216be912005-10-24 06:03:58 +00006188 AllocationInst *New;
6189 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006190 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006191 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006192 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006193 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006194 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006195
6196 // If the allocation has multiple uses, insert a cast and change all things
6197 // that used it to use the new cast. This will also hack on CI, but it will
6198 // die soon.
6199 if (!AI.hasOneUse()) {
6200 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006201 // New is the allocation instruction, pointer typed. AI is the original
6202 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6203 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006204 InsertNewInstBefore(NewCast, AI);
6205 AI.replaceAllUsesWith(NewCast);
6206 }
Chris Lattner216be912005-10-24 06:03:58 +00006207 return ReplaceInstUsesWith(CI, New);
6208}
6209
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006210/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006211/// and return it as type Ty without inserting any new casts and without
6212/// changing the computed value. This is used by code that tries to decide
6213/// whether promoting or shrinking integer operations to wider or smaller types
6214/// will allow us to eliminate a truncate or extend.
6215///
6216/// This is a truncation operation if Ty is smaller than V->getType(), or an
6217/// extension operation if Ty is larger.
6218static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006219 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006220 // We can always evaluate constants in another type.
6221 if (isa<ConstantInt>(V))
6222 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006223
6224 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006225 if (!I) return false;
6226
6227 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006228
6229 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006230 case Instruction::Add:
6231 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006232 case Instruction::And:
6233 case Instruction::Or:
6234 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006235 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006236 // These operators can all arbitrarily be extended or truncated.
6237 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6238 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006239
Chris Lattner960acb02006-11-29 07:18:39 +00006240 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006241 if (!I->hasOneUse()) return false;
6242 // If we are truncating the result of this SHL, and if it's a shift of a
6243 // constant amount, we can always perform a SHL in a smaller type.
6244 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006245 uint32_t BitWidth = Ty->getBitWidth();
6246 if (BitWidth < OrigTy->getBitWidth() &&
6247 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006248 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6249 }
6250 break;
6251 case Instruction::LShr:
6252 if (!I->hasOneUse()) return false;
6253 // If this is a truncate of a logical shr, we can truncate it to a smaller
6254 // lshr iff we know that the bits we would otherwise be shifting in are
6255 // already zeros.
6256 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006257 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6258 uint32_t BitWidth = Ty->getBitWidth();
6259 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006260 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00006261 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6262 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner28d921d2007-04-14 23:32:02 +00006263 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006264 }
6265 }
Chris Lattner960acb02006-11-29 07:18:39 +00006266 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006267 case Instruction::Trunc:
6268 case Instruction::ZExt:
6269 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006270 // If this is a cast from the destination type, we can trivially eliminate
6271 // it, and this will remove a cast overall.
6272 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006273 // If the first operand is itself a cast, and is eliminable, do not count
6274 // this as an eliminable cast. We would prefer to eliminate those two
6275 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006276 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006277 return true;
6278
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006279 ++NumCastsRemoved;
6280 return true;
6281 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006282 break;
6283 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006284 // TODO: Can handle more cases here.
6285 break;
6286 }
6287
6288 return false;
6289}
6290
6291/// EvaluateInDifferentType - Given an expression that
6292/// CanEvaluateInDifferentType returns true for, actually insert the code to
6293/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006294Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006295 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006296 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006297 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006298
6299 // Otherwise, it must be an instruction.
6300 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006301 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006302 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006303 case Instruction::Add:
6304 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006305 case Instruction::And:
6306 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006307 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006308 case Instruction::AShr:
6309 case Instruction::LShr:
6310 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006311 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006312 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6313 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6314 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006315 break;
6316 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006317 case Instruction::Trunc:
6318 case Instruction::ZExt:
6319 case Instruction::SExt:
6320 case Instruction::BitCast:
6321 // If the source type of the cast is the type we're trying for then we can
6322 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006323 if (I->getOperand(0)->getType() == Ty)
6324 return I->getOperand(0);
6325
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006326 // Some other kind of cast, which shouldn't happen, so just ..
6327 // FALL THROUGH
6328 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006329 // TODO: Can handle more cases here.
6330 assert(0 && "Unreachable!");
6331 break;
6332 }
6333
6334 return InsertNewInstBefore(Res, *I);
6335}
6336
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006337/// @brief Implement the transforms common to all CastInst visitors.
6338Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006339 Value *Src = CI.getOperand(0);
6340
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006341 // Casting undef to anything results in undef so might as just replace it and
6342 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006343 if (isa<UndefValue>(Src)) // cast undef -> undef
6344 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6345
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006346 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6347 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006348 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006349 if (Instruction::CastOps opc =
6350 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6351 // The first cast (CSrc) is eliminable so we need to fix up or replace
6352 // the second cast (CI). CSrc will then have a good chance of being dead.
6353 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006354 }
6355 }
Chris Lattner03841652004-05-25 04:29:21 +00006356
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006357 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006358 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6359 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6360 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006361
6362 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006363 if (isa<PHINode>(Src))
6364 if (Instruction *NV = FoldOpIntoPhi(CI))
6365 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006366
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006367 return 0;
6368}
6369
Chris Lattner1db224d2007-04-27 17:44:50 +00006370/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6371Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6372 Value *Src = CI.getOperand(0);
6373
Chris Lattner1db224d2007-04-27 17:44:50 +00006374 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattneracbf6a42007-04-28 00:57:34 +00006375 // If casting the result of a getelementptr instruction with no offset, turn
6376 // this into a cast of the original pointer!
Chris Lattner1db224d2007-04-27 17:44:50 +00006377 if (GEP->hasAllZeroIndices()) {
6378 // Changing the cast operand is usually not a good idea but it is safe
6379 // here because the pointer operand is being replaced with another
6380 // pointer operand so the opcode doesn't need to change.
Chris Lattneracbf6a42007-04-28 00:57:34 +00006381 AddToWorkList(GEP);
Chris Lattner1db224d2007-04-27 17:44:50 +00006382 CI.setOperand(0, GEP->getOperand(0));
6383 return &CI;
6384 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00006385
6386 // If the GEP has a single use, and the base pointer is a bitcast, and the
6387 // GEP computes a constant offset, see if we can convert these three
6388 // instructions into fewer. This typically happens with unions and other
6389 // non-type-safe code.
6390 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6391 if (GEP->hasAllConstantIndices()) {
6392 // We are guaranteed to get a constant from EmitGEPOffset.
6393 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6394 int64_t Offset = OffsetV->getSExtValue();
6395
6396 // Get the base pointer input of the bitcast, and the type it points to.
6397 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6398 const Type *GEPIdxTy =
6399 cast<PointerType>(OrigBase->getType())->getElementType();
6400 if (GEPIdxTy->isSized()) {
6401 SmallVector<Value*, 8> NewIndices;
6402
6403 // Start with the index over the outer type.
6404 const Type *IntPtrTy = TD->getIntPtrType();
6405 int64_t TySize = TD->getTypeSize(GEPIdxTy);
6406 int64_t FirstIdx = Offset/TySize;
6407 Offset %= TySize;
6408
6409 // Handle silly modulus not returning values values [0..TySize).
6410 if (Offset < 0) {
Chris Lattner089e35c2007-04-28 05:27:36 +00006411 --FirstIdx;
Chris Lattneracbf6a42007-04-28 00:57:34 +00006412 Offset += TySize;
6413 assert(Offset >= 0);
6414 }
6415
6416 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6417 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
6418
6419 // Index into the types. If we fail, set OrigBase to null.
6420 while (Offset) {
6421 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6422 const StructLayout *SL = TD->getStructLayout(STy);
6423 unsigned Elt = SL->getElementContainingOffset(Offset);
6424 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6425
6426 Offset -= SL->getElementOffset(Elt);
6427 GEPIdxTy = STy->getElementType(Elt);
6428 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6429 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6430 uint64_t EltSize = TD->getTypeSize(STy->getElementType());
6431 NewIndices.push_back(ConstantInt::get(IntPtrTy, Offset/EltSize));
6432 Offset %= EltSize;
6433 GEPIdxTy = STy->getElementType();
6434 } else {
6435 // Otherwise, we can't index into this, bail out.
6436 Offset = 0;
6437 OrigBase = 0;
6438 }
6439 }
6440 if (OrigBase) {
6441 // If we were able to index down into an element, create the GEP
6442 // and bitcast the result. This eliminates one bitcast, potentially
6443 // two.
6444 Instruction *NGEP = new GetElementPtrInst(OrigBase, &NewIndices[0],
6445 NewIndices.size(), "");
6446 InsertNewInstBefore(NGEP, CI);
6447 NGEP->takeName(GEP);
6448
Chris Lattneracbf6a42007-04-28 00:57:34 +00006449 if (isa<BitCastInst>(CI))
6450 return new BitCastInst(NGEP, CI.getType());
6451 assert(isa<PtrToIntInst>(CI));
6452 return new PtrToIntInst(NGEP, CI.getType());
6453 }
6454 }
6455 }
6456 }
Chris Lattner1db224d2007-04-27 17:44:50 +00006457 }
6458
6459 return commonCastTransforms(CI);
6460}
6461
6462
6463
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006464/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6465/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006466/// cases.
6467/// @brief Implement the transforms common to CastInst with integer operands
6468Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6469 if (Instruction *Result = commonCastTransforms(CI))
6470 return Result;
6471
6472 Value *Src = CI.getOperand(0);
6473 const Type *SrcTy = Src->getType();
6474 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006475 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6476 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006477
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006478 // See if we can simplify any instructions used by the LHS whose sole
6479 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006480 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6481 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006482 KnownZero, KnownOne))
6483 return &CI;
6484
6485 // If the source isn't an instruction or has more than one use then we
6486 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006487 Instruction *SrcI = dyn_cast<Instruction>(Src);
6488 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006489 return 0;
6490
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006491 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006492 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006493 if (!isa<BitCastInst>(CI) &&
6494 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6495 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006496 // If this cast is a truncate, evaluting in a different type always
6497 // eliminates the cast, so it is always a win. If this is a noop-cast
6498 // this just removes a noop cast which isn't pointful, but simplifies
6499 // the code. If this is a zero-extension, we need to do an AND to
6500 // maintain the clear top-part of the computation, so we require that
6501 // the input have eliminated at least one cast. If this is a sign
6502 // extension, we insert two new casts (to do the extension) so we
6503 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006504 bool DoXForm;
6505 switch (CI.getOpcode()) {
6506 default:
6507 // All the others use floating point so we shouldn't actually
6508 // get here because of the check above.
6509 assert(0 && "Unknown cast type");
6510 case Instruction::Trunc:
6511 DoXForm = true;
6512 break;
6513 case Instruction::ZExt:
6514 DoXForm = NumCastsRemoved >= 1;
6515 break;
6516 case Instruction::SExt:
6517 DoXForm = NumCastsRemoved >= 2;
6518 break;
6519 case Instruction::BitCast:
6520 DoXForm = false;
6521 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006522 }
6523
6524 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006525 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6526 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006527 assert(Res->getType() == DestTy);
6528 switch (CI.getOpcode()) {
6529 default: assert(0 && "Unknown cast type!");
6530 case Instruction::Trunc:
6531 case Instruction::BitCast:
6532 // Just replace this cast with the result.
6533 return ReplaceInstUsesWith(CI, Res);
6534 case Instruction::ZExt: {
6535 // We need to emit an AND to clear the high bits.
6536 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00006537 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6538 SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006539 return BinaryOperator::createAnd(Res, C);
6540 }
6541 case Instruction::SExt:
6542 // We need to emit a cast to truncate, then a cast to sext.
6543 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006544 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6545 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006546 }
6547 }
6548 }
6549
6550 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6551 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6552
6553 switch (SrcI->getOpcode()) {
6554 case Instruction::Add:
6555 case Instruction::Mul:
6556 case Instruction::And:
6557 case Instruction::Or:
6558 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00006559 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006560 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6561 // Don't insert two casts if they cannot be eliminated. We allow
6562 // two casts to be inserted if the sizes are the same. This could
6563 // only be converting signedness, which is a noop.
6564 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006565 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6566 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006567 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006568 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6569 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6570 return BinaryOperator::create(
6571 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006572 }
6573 }
6574
6575 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6576 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6577 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006578 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006579 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006580 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006581 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6582 }
6583 break;
6584 case Instruction::SDiv:
6585 case Instruction::UDiv:
6586 case Instruction::SRem:
6587 case Instruction::URem:
6588 // If we are just changing the sign, rewrite.
6589 if (DestBitSize == SrcBitSize) {
6590 // Don't insert two casts if they cannot be eliminated. We allow
6591 // two casts to be inserted if the sizes are the same. This could
6592 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006593 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6594 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006595 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6596 Op0, DestTy, SrcI);
6597 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6598 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006599 return BinaryOperator::create(
6600 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6601 }
6602 }
6603 break;
6604
6605 case Instruction::Shl:
6606 // Allow changing the sign of the source operand. Do not allow
6607 // changing the size of the shift, UNLESS the shift amount is a
6608 // constant. We must not change variable sized shifts to a smaller
6609 // size, because it is undefined to shift more bits out than exist
6610 // in the value.
6611 if (DestBitSize == SrcBitSize ||
6612 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006613 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6614 Instruction::BitCast : Instruction::Trunc);
6615 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006616 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006617 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006618 }
6619 break;
6620 case Instruction::AShr:
6621 // If this is a signed shr, and if all bits shifted in are about to be
6622 // truncated off, turn it into an unsigned shr to allow greater
6623 // simplifications.
6624 if (DestBitSize < SrcBitSize &&
6625 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006626 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006627 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6628 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006629 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006630 }
6631 }
6632 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006633 }
6634 return 0;
6635}
6636
Chris Lattner74ff60f2007-04-11 06:57:46 +00006637Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006638 if (Instruction *Result = commonIntCastTransforms(CI))
6639 return Result;
6640
6641 Value *Src = CI.getOperand(0);
6642 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006643 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6644 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006645
6646 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6647 switch (SrcI->getOpcode()) {
6648 default: break;
6649 case Instruction::LShr:
6650 // We can shrink lshr to something smaller if we know the bits shifted in
6651 // are already zeros.
6652 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006653 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00006654
6655 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006656 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006657 Value* SrcIOp0 = SrcI->getOperand(0);
6658 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006659 if (ShAmt >= DestBitWidth) // All zeros.
6660 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6661
6662 // Okay, we can shrink this. Truncate the input, then return a new
6663 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006664 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6665 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6666 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006667 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006668 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006669 } else { // This is a variable shr.
6670
6671 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6672 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6673 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006674 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006675 Value *One = ConstantInt::get(SrcI->getType(), 1);
6676
Reid Spencer2341c222007-02-02 02:16:23 +00006677 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006678 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006679 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006680 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6681 SrcI->getOperand(0),
6682 "tmp"), CI);
6683 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006684 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006685 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006686 }
6687 break;
6688 }
6689 }
6690
6691 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006692}
6693
Chris Lattner74ff60f2007-04-11 06:57:46 +00006694Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006695 // If one of the common conversion will work ..
6696 if (Instruction *Result = commonIntCastTransforms(CI))
6697 return Result;
6698
6699 Value *Src = CI.getOperand(0);
6700
6701 // If this is a cast of a cast
6702 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006703 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6704 // types and if the sizes are just right we can convert this into a logical
6705 // 'and' which will be much cheaper than the pair of casts.
6706 if (isa<TruncInst>(CSrc)) {
6707 // Get the sizes of the types involved
6708 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00006709 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6710 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6711 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006712 // If we're actually extending zero bits and the trunc is a no-op
6713 if (MidSize < DstSize && SrcSize == DstSize) {
6714 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006715 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006716 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006717 Instruction *And =
6718 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6719 // Unfortunately, if the type changed, we need to cast it back.
6720 if (And->getType() != CI.getType()) {
6721 And->setName(CSrc->getName()+".mask");
6722 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006723 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006724 }
6725 return And;
6726 }
6727 }
6728 }
6729
Chris Lattner7ddbff02007-04-11 05:45:39 +00006730 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6731 // If we are just checking for a icmp eq of a single bit and zext'ing it
6732 // to an integer, then shift the bit to the appropriate place and then
6733 // cast to integer to avoid the comparison.
6734 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00006735 const APInt &Op1CV = Op1C->getValue();
Chris Lattnerd0f79422007-04-11 06:53:04 +00006736
6737 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6738 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6739 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6740 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6741 Value *In = ICI->getOperand(0);
6742 Value *Sh = ConstantInt::get(In->getType(),
6743 In->getType()->getPrimitiveSizeInBits()-1);
6744 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattner28d921d2007-04-14 23:32:02 +00006745 In->getName()+".lobit"),
Chris Lattnerd0f79422007-04-11 06:53:04 +00006746 CI);
6747 if (In->getType() != CI.getType())
6748 In = CastInst::createIntegerCast(In, CI.getType(),
6749 false/*ZExt*/, "tmp", &CI);
6750
6751 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6752 Constant *One = ConstantInt::get(In->getType(), 1);
6753 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattner28d921d2007-04-14 23:32:02 +00006754 In->getName()+".not"),
Chris Lattnerd0f79422007-04-11 06:53:04 +00006755 CI);
6756 }
6757
6758 return ReplaceInstUsesWith(CI, In);
6759 }
6760
6761
6762
Chris Lattner20f23722007-04-11 06:12:58 +00006763 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6764 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6765 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6766 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6767 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6768 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6769 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6770 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner7ddbff02007-04-11 05:45:39 +00006771 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6772 // This only works for EQ and NE
6773 ICI->isEquality()) {
6774 // If Op1C some other power of two, convert:
6775 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6776 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6777 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6778 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6779
6780 APInt KnownZeroMask(~KnownZero);
6781 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6782 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6783 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6784 // (X&4) == 2 --> false
6785 // (X&4) != 2 --> true
6786 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6787 Res = ConstantExpr::getZExt(Res, CI.getType());
6788 return ReplaceInstUsesWith(CI, Res);
6789 }
6790
6791 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6792 Value *In = ICI->getOperand(0);
6793 if (ShiftAmt) {
6794 // Perform a logical shr by shiftamt.
6795 // Insert the shift to put the result in the low bit.
6796 In = InsertNewInstBefore(
6797 BinaryOperator::createLShr(In,
6798 ConstantInt::get(In->getType(), ShiftAmt),
6799 In->getName()+".lobit"), CI);
6800 }
6801
6802 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6803 Constant *One = ConstantInt::get(In->getType(), 1);
6804 In = BinaryOperator::createXor(In, One, "tmp");
6805 InsertNewInstBefore(cast<Instruction>(In), CI);
6806 }
6807
6808 if (CI.getType() == In->getType())
6809 return ReplaceInstUsesWith(CI, In);
6810 else
6811 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6812 }
6813 }
6814 }
6815 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006816 return 0;
6817}
6818
Chris Lattner74ff60f2007-04-11 06:57:46 +00006819Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00006820 if (Instruction *I = commonIntCastTransforms(CI))
6821 return I;
6822
Chris Lattner74ff60f2007-04-11 06:57:46 +00006823 Value *Src = CI.getOperand(0);
6824
6825 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6826 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6827 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6828 // If we are just checking for a icmp eq of a single bit and zext'ing it
6829 // to an integer, then shift the bit to the appropriate place and then
6830 // cast to integer to avoid the comparison.
6831 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6832 const APInt &Op1CV = Op1C->getValue();
6833
6834 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6835 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6836 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6837 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6838 Value *In = ICI->getOperand(0);
6839 Value *Sh = ConstantInt::get(In->getType(),
6840 In->getType()->getPrimitiveSizeInBits()-1);
6841 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattner28d921d2007-04-14 23:32:02 +00006842 In->getName()+".lobit"),
Chris Lattner74ff60f2007-04-11 06:57:46 +00006843 CI);
6844 if (In->getType() != CI.getType())
6845 In = CastInst::createIntegerCast(In, CI.getType(),
6846 true/*SExt*/, "tmp", &CI);
6847
6848 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6849 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6850 In->getName()+".not"), CI);
6851
6852 return ReplaceInstUsesWith(CI, In);
6853 }
6854 }
6855 }
6856
Chris Lattner20f23722007-04-11 06:12:58 +00006857 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006858}
6859
6860Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6861 return commonCastTransforms(CI);
6862}
6863
6864Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6865 return commonCastTransforms(CI);
6866}
6867
6868Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006869 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006870}
6871
6872Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006873 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006874}
6875
6876Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6877 return commonCastTransforms(CI);
6878}
6879
6880Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6881 return commonCastTransforms(CI);
6882}
6883
6884Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00006885 return commonPointerCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006886}
6887
6888Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6889 return commonCastTransforms(CI);
6890}
6891
Chris Lattner1db224d2007-04-27 17:44:50 +00006892Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006893 // If the operands are integer typed then apply the integer transforms,
6894 // otherwise just apply the common ones.
6895 Value *Src = CI.getOperand(0);
6896 const Type *SrcTy = Src->getType();
6897 const Type *DestTy = CI.getType();
6898
Chris Lattner03c49532007-01-15 02:27:26 +00006899 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006900 if (Instruction *Result = commonIntCastTransforms(CI))
6901 return Result;
Chris Lattner1db224d2007-04-27 17:44:50 +00006902 } else if (isa<PointerType>(SrcTy)) {
6903 if (Instruction *I = commonPointerCastTransforms(CI))
6904 return I;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006905 } else {
6906 if (Instruction *Result = commonCastTransforms(CI))
6907 return Result;
6908 }
6909
6910
6911 // Get rid of casts from one type to the same type. These are useless and can
6912 // be replaced by the operand.
6913 if (DestTy == Src->getType())
6914 return ReplaceInstUsesWith(CI, Src);
6915
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006916 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner1db224d2007-04-27 17:44:50 +00006917 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
6918 const Type *DstElTy = DstPTy->getElementType();
6919 const Type *SrcElTy = SrcPTy->getElementType();
6920
6921 // If we are casting a malloc or alloca to a pointer to a type of the same
6922 // size, rewrite the allocation instruction to allocate the "right" type.
6923 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6924 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6925 return V;
6926
6927 // If the source and destination are pointers, and this cast is equivalent to
6928 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6929 // This can enhance SROA and other transforms that want type-safe pointers.
6930 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6931 unsigned NumZeros = 0;
6932 while (SrcElTy != DstElTy &&
6933 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6934 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6935 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6936 ++NumZeros;
6937 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006938
Chris Lattner1db224d2007-04-27 17:44:50 +00006939 // If we found a path from the src to dest, create the getelementptr now.
6940 if (SrcElTy == DstElTy) {
6941 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6942 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006943 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006944 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006945
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006946 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6947 if (SVI->hasOneUse()) {
6948 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6949 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006950 if (isa<VectorType>(DestTy) &&
6951 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006952 SVI->getType()->getNumElements()) {
6953 CastInst *Tmp;
6954 // If either of the operands is a cast from CI.getType(), then
6955 // evaluating the shuffle in the casted destination's type will allow
6956 // us to eliminate at least one cast.
6957 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6958 Tmp->getOperand(0)->getType() == DestTy) ||
6959 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6960 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006961 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6962 SVI->getOperand(0), DestTy, &CI);
6963 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6964 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006965 // Return a new shuffle vector. Use the same element ID's, as we
6966 // know the vector types match #elts.
6967 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006968 }
6969 }
6970 }
6971 }
Chris Lattner260ab202002-04-18 17:39:14 +00006972 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006973}
6974
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006975/// GetSelectFoldableOperands - We want to turn code that looks like this:
6976/// %C = or %A, %B
6977/// %D = select %cond, %C, %A
6978/// into:
6979/// %C = select %cond, %B, 0
6980/// %D = or %A, %C
6981///
6982/// Assuming that the specified instruction is an operand to the select, return
6983/// a bitmask indicating which operands of this instruction are foldable if they
6984/// equal the other incoming value of the select.
6985///
6986static unsigned GetSelectFoldableOperands(Instruction *I) {
6987 switch (I->getOpcode()) {
6988 case Instruction::Add:
6989 case Instruction::Mul:
6990 case Instruction::And:
6991 case Instruction::Or:
6992 case Instruction::Xor:
6993 return 3; // Can fold through either operand.
6994 case Instruction::Sub: // Can only fold on the amount subtracted.
6995 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006996 case Instruction::LShr:
6997 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006998 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006999 default:
7000 return 0; // Cannot fold
7001 }
7002}
7003
7004/// GetSelectFoldableConstant - For the same transformation as the previous
7005/// function, return the identity constant that goes into the select.
7006static Constant *GetSelectFoldableConstant(Instruction *I) {
7007 switch (I->getOpcode()) {
7008 default: assert(0 && "This cannot happen!"); abort();
7009 case Instruction::Add:
7010 case Instruction::Sub:
7011 case Instruction::Or:
7012 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007013 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00007014 case Instruction::LShr:
7015 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00007016 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007017 case Instruction::And:
7018 return ConstantInt::getAllOnesValue(I->getType());
7019 case Instruction::Mul:
7020 return ConstantInt::get(I->getType(), 1);
7021 }
7022}
7023
Chris Lattner411336f2005-01-19 21:50:18 +00007024/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7025/// have the same opcode and only one use each. Try to simplify this.
7026Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7027 Instruction *FI) {
7028 if (TI->getNumOperands() == 1) {
7029 // If this is a non-volatile load or a cast from the same type,
7030 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007031 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00007032 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7033 return 0;
7034 } else {
7035 return 0; // unknown unary op.
7036 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007037
Chris Lattner411336f2005-01-19 21:50:18 +00007038 // Fold this by inserting a select from the input values.
7039 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7040 FI->getOperand(0), SI.getName()+".v");
7041 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007042 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7043 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00007044 }
7045
Reid Spencer2341c222007-02-02 02:16:23 +00007046 // Only handle binary operators here.
7047 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00007048 return 0;
7049
7050 // Figure out if the operations have any operands in common.
7051 Value *MatchOp, *OtherOpT, *OtherOpF;
7052 bool MatchIsOpZero;
7053 if (TI->getOperand(0) == FI->getOperand(0)) {
7054 MatchOp = TI->getOperand(0);
7055 OtherOpT = TI->getOperand(1);
7056 OtherOpF = FI->getOperand(1);
7057 MatchIsOpZero = true;
7058 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7059 MatchOp = TI->getOperand(1);
7060 OtherOpT = TI->getOperand(0);
7061 OtherOpF = FI->getOperand(0);
7062 MatchIsOpZero = false;
7063 } else if (!TI->isCommutative()) {
7064 return 0;
7065 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7066 MatchOp = TI->getOperand(0);
7067 OtherOpT = TI->getOperand(1);
7068 OtherOpF = FI->getOperand(0);
7069 MatchIsOpZero = true;
7070 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7071 MatchOp = TI->getOperand(1);
7072 OtherOpT = TI->getOperand(0);
7073 OtherOpF = FI->getOperand(1);
7074 MatchIsOpZero = true;
7075 } else {
7076 return 0;
7077 }
7078
7079 // If we reach here, they do have operations in common.
7080 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7081 OtherOpF, SI.getName()+".v");
7082 InsertNewInstBefore(NewSI, SI);
7083
7084 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7085 if (MatchIsOpZero)
7086 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7087 else
7088 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00007089 }
Reid Spencer2f34b982007-02-02 14:41:37 +00007090 assert(0 && "Shouldn't get here");
7091 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00007092}
7093
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007094Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00007095 Value *CondVal = SI.getCondition();
7096 Value *TrueVal = SI.getTrueValue();
7097 Value *FalseVal = SI.getFalseValue();
7098
7099 // select true, X, Y -> X
7100 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00007101 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00007102 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00007103
7104 // select C, X, X -> X
7105 if (TrueVal == FalseVal)
7106 return ReplaceInstUsesWith(SI, TrueVal);
7107
Chris Lattner81a7a232004-10-16 18:11:37 +00007108 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7109 return ReplaceInstUsesWith(SI, FalseVal);
7110 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7111 return ReplaceInstUsesWith(SI, TrueVal);
7112 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7113 if (isa<Constant>(TrueVal))
7114 return ReplaceInstUsesWith(SI, TrueVal);
7115 else
7116 return ReplaceInstUsesWith(SI, FalseVal);
7117 }
7118
Reid Spencer542964f2007-01-11 18:21:29 +00007119 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007120 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007121 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007122 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007123 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007124 } else {
7125 // Change: A = select B, false, C --> A = and !B, C
7126 Value *NotCond =
7127 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7128 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007129 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007130 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007131 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007132 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007133 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007134 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007135 } else {
7136 // Change: A = select B, C, true --> A = or !B, C
7137 Value *NotCond =
7138 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7139 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007140 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007141 }
7142 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00007143 }
Chris Lattner1c631e82004-04-08 04:43:23 +00007144
Chris Lattner183b3362004-04-09 19:05:30 +00007145 // Selecting between two integer constants?
7146 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7147 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00007148 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00007149 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007150 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00007151 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00007152 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00007153 Value *NotCond =
7154 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00007155 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007156 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00007157 }
Chris Lattner20f23722007-04-11 06:12:58 +00007158
7159 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner35167c32004-06-09 07:59:58 +00007160
Reid Spencer266e42b2006-12-23 06:05:41 +00007161 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007162
Reid Spencer266e42b2006-12-23 06:05:41 +00007163 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00007164 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00007165 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00007166 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007167 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007168 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00007169 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00007170 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00007171 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7172 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7173 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00007174 InsertNewInstBefore(SRA, SI);
7175
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007176 // Finally, convert to the type of the select RHS. We figure out
7177 // if this requires a SExt, Trunc or BitCast based on the sizes.
7178 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng56cda952007-04-02 08:20:41 +00007179 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7180 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007181 if (SRASize < SISize)
7182 opc = Instruction::SExt;
7183 else if (SRASize > SISize)
7184 opc = Instruction::Trunc;
7185 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007186 }
7187 }
7188
7189
7190 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00007191 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007192 // non-constant value, eliminate this whole mess. This corresponds to
7193 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00007194 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007195 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007196 cast<Constant>(IC->getOperand(1))->isNullValue())
7197 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7198 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007199 isa<ConstantInt>(ICA->getOperand(1)) &&
7200 (ICA->getOperand(1) == TrueValC ||
7201 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007202 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7203 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007204 // know whether we have a icmp_ne or icmp_eq and whether the
7205 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00007206 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00007207 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007208 Value *V = ICA;
7209 if (ShouldNotVal)
7210 V = InsertNewInstBefore(BinaryOperator::create(
7211 Instruction::Xor, V, ICA->getOperand(1)), SI);
7212 return ReplaceInstUsesWith(SI, V);
7213 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007214 }
Chris Lattner533bc492004-03-30 19:37:13 +00007215 }
Chris Lattner623fba12004-04-10 22:21:27 +00007216
7217 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007218 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7219 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007220 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007221 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007222 return ReplaceInstUsesWith(SI, FalseVal);
7223 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007224 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007225 return ReplaceInstUsesWith(SI, TrueVal);
7226 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7227
Reid Spencer266e42b2006-12-23 06:05:41 +00007228 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007229 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007230 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007231 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007232 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007233 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7234 return ReplaceInstUsesWith(SI, TrueVal);
7235 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7236 }
7237 }
7238
7239 // See if we are selecting two values based on a comparison of the two values.
7240 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7241 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7242 // Transform (X == Y) ? X : Y -> Y
7243 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7244 return ReplaceInstUsesWith(SI, FalseVal);
7245 // Transform (X != Y) ? X : Y -> X
7246 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7247 return ReplaceInstUsesWith(SI, TrueVal);
7248 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7249
7250 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7251 // Transform (X == Y) ? Y : X -> X
7252 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7253 return ReplaceInstUsesWith(SI, FalseVal);
7254 // Transform (X != Y) ? Y : X -> Y
7255 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007256 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007257 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7258 }
7259 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007260
Chris Lattnera04c9042005-01-13 22:52:24 +00007261 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7262 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7263 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007264 Instruction *AddOp = 0, *SubOp = 0;
7265
Chris Lattner411336f2005-01-19 21:50:18 +00007266 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7267 if (TI->getOpcode() == FI->getOpcode())
7268 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7269 return IV;
7270
7271 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7272 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007273 if (TI->getOpcode() == Instruction::Sub &&
7274 FI->getOpcode() == Instruction::Add) {
7275 AddOp = FI; SubOp = TI;
7276 } else if (FI->getOpcode() == Instruction::Sub &&
7277 TI->getOpcode() == Instruction::Add) {
7278 AddOp = TI; SubOp = FI;
7279 }
7280
7281 if (AddOp) {
7282 Value *OtherAddOp = 0;
7283 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7284 OtherAddOp = AddOp->getOperand(1);
7285 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7286 OtherAddOp = AddOp->getOperand(0);
7287 }
7288
7289 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007290 // So at this point we know we have (Y -> OtherAddOp):
7291 // select C, (add X, Y), (sub X, Z)
7292 Value *NegVal; // Compute -Z
7293 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7294 NegVal = ConstantExpr::getNeg(C);
7295 } else {
7296 NegVal = InsertNewInstBefore(
7297 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007298 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007299
7300 Value *NewTrueOp = OtherAddOp;
7301 Value *NewFalseOp = NegVal;
7302 if (AddOp != TI)
7303 std::swap(NewTrueOp, NewFalseOp);
7304 Instruction *NewSel =
7305 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7306
7307 NewSel = InsertNewInstBefore(NewSel, SI);
7308 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007309 }
7310 }
7311 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007312
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007313 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007314 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007315 // See the comment above GetSelectFoldableOperands for a description of the
7316 // transformation we are doing here.
7317 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7318 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7319 !isa<Constant>(FalseVal))
7320 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7321 unsigned OpToFold = 0;
7322 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7323 OpToFold = 1;
7324 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7325 OpToFold = 2;
7326 }
7327
7328 if (OpToFold) {
7329 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007330 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007331 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007332 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007333 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007334 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7335 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007336 else {
7337 assert(0 && "Unknown instruction!!");
7338 }
7339 }
7340 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007341
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007342 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7343 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7344 !isa<Constant>(TrueVal))
7345 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7346 unsigned OpToFold = 0;
7347 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7348 OpToFold = 1;
7349 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7350 OpToFold = 2;
7351 }
7352
7353 if (OpToFold) {
7354 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007355 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007356 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007357 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007358 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007359 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7360 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007361 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007362 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007363 }
7364 }
7365 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007366
7367 if (BinaryOperator::isNot(CondVal)) {
7368 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7369 SI.setOperand(1, FalseVal);
7370 SI.setOperand(2, TrueVal);
7371 return &SI;
7372 }
7373
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007374 return 0;
7375}
7376
Chris Lattner82f2ef22006-03-06 20:18:44 +00007377/// GetKnownAlignment - If the specified pointer has an alignment that we can
7378/// determine, return it, otherwise return 0.
7379static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7380 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7381 unsigned Align = GV->getAlignment();
7382 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007383 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007384 return Align;
7385 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7386 unsigned Align = AI->getAlignment();
7387 if (Align == 0 && TD) {
7388 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007389 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007390 else if (isa<MallocInst>(AI)) {
7391 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007392 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007393 Align =
7394 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007395 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007396 Align =
7397 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007398 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007399 }
7400 }
7401 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007402 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007403 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007404 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007405 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007406 if (isa<PointerType>(CI->getOperand(0)->getType()))
7407 return GetKnownAlignment(CI->getOperand(0), TD);
7408 return 0;
Chris Lattneracbf6a42007-04-28 00:57:34 +00007409 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner82f2ef22006-03-06 20:18:44 +00007410 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7411 if (BaseAlignment == 0) return 0;
7412
7413 // If all indexes are zero, it is just the alignment of the base pointer.
7414 bool AllZeroOperands = true;
7415 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7416 if (!isa<Constant>(GEPI->getOperand(i)) ||
7417 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7418 AllZeroOperands = false;
7419 break;
7420 }
7421 if (AllZeroOperands)
7422 return BaseAlignment;
7423
7424 // Otherwise, if the base alignment is >= the alignment we expect for the
7425 // base pointer type, then we know that the resultant pointer is aligned at
7426 // least as much as its type requires.
7427 if (!TD) return 0;
7428
7429 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007430 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007431 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007432 <= BaseAlignment) {
7433 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007434 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007435 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007436 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007437 return 0;
7438 }
7439 return 0;
7440}
7441
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007442
Chris Lattnerc66b2232006-01-13 20:11:04 +00007443/// visitCallInst - CallInst simplification. This mostly only handles folding
7444/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7445/// the heavy lifting.
7446///
Chris Lattner970c33a2003-06-19 17:00:31 +00007447Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007448 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7449 if (!II) return visitCallSite(&CI);
7450
Chris Lattner51ea1272004-02-28 05:22:00 +00007451 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7452 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007453 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007454 bool Changed = false;
7455
7456 // memmove/cpy/set of zero bytes is a noop.
7457 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7458 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7459
Chris Lattner00648e12004-10-12 04:52:52 +00007460 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007461 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007462 // Replace the instruction with just byte operations. We would
7463 // transform other cases to loads/stores, but we don't know if
7464 // alignment is sufficient.
7465 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007466 }
7467
Chris Lattner00648e12004-10-12 04:52:52 +00007468 // If we have a memmove and the source operation is a constant global,
7469 // then the source and dest pointers can't alias, so we can change this
7470 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007471 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007472 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7473 if (GVSrc->isConstant()) {
7474 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007475 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007476 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007477 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007478 Name = "llvm.memcpy.i32";
7479 else
7480 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007481 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007482 CI.getCalledFunction()->getFunctionType());
7483 CI.setOperand(0, MemCpy);
7484 Changed = true;
7485 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007486 }
Chris Lattner00648e12004-10-12 04:52:52 +00007487
Chris Lattner82f2ef22006-03-06 20:18:44 +00007488 // If we can determine a pointer alignment that is bigger than currently
7489 // set, update the alignment.
7490 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7491 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7492 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7493 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007494 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007495 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007496 Changed = true;
7497 }
7498 } else if (isa<MemSetInst>(MI)) {
7499 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007500 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007501 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007502 Changed = true;
7503 }
7504 }
7505
Chris Lattnerc66b2232006-01-13 20:11:04 +00007506 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007507 } else {
7508 switch (II->getIntrinsicID()) {
7509 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007510 case Intrinsic::ppc_altivec_lvx:
7511 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007512 case Intrinsic::x86_sse_loadu_ps:
7513 case Intrinsic::x86_sse2_loadu_pd:
7514 case Intrinsic::x86_sse2_loadu_dq:
7515 // Turn PPC lvx -> load if the pointer is known aligned.
7516 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007517 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007518 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007519 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007520 return new LoadInst(Ptr);
7521 }
7522 break;
7523 case Intrinsic::ppc_altivec_stvx:
7524 case Intrinsic::ppc_altivec_stvxl:
7525 // Turn stvx -> store if the pointer is known aligned.
7526 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007527 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007528 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7529 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007530 return new StoreInst(II->getOperand(1), Ptr);
7531 }
7532 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007533 case Intrinsic::x86_sse_storeu_ps:
7534 case Intrinsic::x86_sse2_storeu_pd:
7535 case Intrinsic::x86_sse2_storeu_dq:
7536 case Intrinsic::x86_sse2_storel_dq:
7537 // Turn X86 storeu -> store if the pointer is known aligned.
7538 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7539 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007540 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7541 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007542 return new StoreInst(II->getOperand(2), Ptr);
7543 }
7544 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007545
7546 case Intrinsic::x86_sse_cvttss2si: {
7547 // These intrinsics only demands the 0th element of its input vector. If
7548 // we can simplify the input based on that, do so now.
7549 uint64_t UndefElts;
7550 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7551 UndefElts)) {
7552 II->setOperand(1, V);
7553 return II;
7554 }
7555 break;
7556 }
7557
Chris Lattnere79d2492006-04-06 19:19:17 +00007558 case Intrinsic::ppc_altivec_vperm:
7559 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007560 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007561 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7562
7563 // Check that all of the elements are integer constants or undefs.
7564 bool AllEltsOk = true;
7565 for (unsigned i = 0; i != 16; ++i) {
7566 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7567 !isa<UndefValue>(Mask->getOperand(i))) {
7568 AllEltsOk = false;
7569 break;
7570 }
7571 }
7572
7573 if (AllEltsOk) {
7574 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007575 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7576 II->getOperand(1), Mask->getType(), CI);
7577 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7578 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007579 Value *Result = UndefValue::get(Op0->getType());
7580
7581 // Only extract each element once.
7582 Value *ExtractedElts[32];
7583 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7584
7585 for (unsigned i = 0; i != 16; ++i) {
7586 if (isa<UndefValue>(Mask->getOperand(i)))
7587 continue;
Chris Lattner28d921d2007-04-14 23:32:02 +00007588 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007589 Idx &= 31; // Match the hardware behavior.
7590
7591 if (ExtractedElts[Idx] == 0) {
7592 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007593 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007594 InsertNewInstBefore(Elt, CI);
7595 ExtractedElts[Idx] = Elt;
7596 }
7597
7598 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007599 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007600 InsertNewInstBefore(cast<Instruction>(Result), CI);
7601 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007602 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007603 }
7604 }
7605 break;
7606
Chris Lattner503221f2006-01-13 21:28:09 +00007607 case Intrinsic::stackrestore: {
7608 // If the save is right next to the restore, remove the restore. This can
7609 // happen when variable allocas are DCE'd.
7610 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7611 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7612 BasicBlock::iterator BI = SS;
7613 if (&*++BI == II)
7614 return EraseInstFromFunction(CI);
7615 }
7616 }
7617
7618 // If the stack restore is in a return/unwind block and if there are no
7619 // allocas or calls between the restore and the return, nuke the restore.
7620 TerminatorInst *TI = II->getParent()->getTerminator();
7621 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7622 BasicBlock::iterator BI = II;
7623 bool CannotRemove = false;
7624 for (++BI; &*BI != TI; ++BI) {
7625 if (isa<AllocaInst>(BI) ||
7626 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7627 CannotRemove = true;
7628 break;
7629 }
7630 }
7631 if (!CannotRemove)
7632 return EraseInstFromFunction(CI);
7633 }
7634 break;
7635 }
7636 }
Chris Lattner00648e12004-10-12 04:52:52 +00007637 }
7638
Chris Lattnerc66b2232006-01-13 20:11:04 +00007639 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007640}
7641
7642// InvokeInst simplification
7643//
7644Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007645 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007646}
7647
Chris Lattneraec3d942003-10-07 22:32:43 +00007648// visitCallSite - Improvements for call and invoke instructions.
7649//
7650Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007651 bool Changed = false;
7652
7653 // If the callee is a constexpr cast of a function, attempt to move the cast
7654 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007655 if (transformConstExprCastCall(CS)) return 0;
7656
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007657 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007658
Chris Lattner61d9d812005-05-13 07:09:09 +00007659 if (Function *CalleeF = dyn_cast<Function>(Callee))
7660 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7661 Instruction *OldCall = CS.getInstruction();
7662 // If the call and callee calling conventions don't match, this call must
7663 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007664 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007665 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007666 if (!OldCall->use_empty())
7667 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7668 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7669 return EraseInstFromFunction(*OldCall);
7670 return 0;
7671 }
7672
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007673 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7674 // This instruction is not reachable, just remove it. We insert a store to
7675 // undef so that we know that this code is not reachable, despite the fact
7676 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007677 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007678 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007679 CS.getInstruction());
7680
7681 if (!CS.getInstruction()->use_empty())
7682 CS.getInstruction()->
7683 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7684
7685 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7686 // Don't break the CFG, insert a dummy cond branch.
7687 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007688 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007689 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007690 return EraseInstFromFunction(*CS.getInstruction());
7691 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007692
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007693 const PointerType *PTy = cast<PointerType>(Callee->getType());
7694 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7695 if (FTy->isVarArg()) {
7696 // See if we can optimize any arguments passed through the varargs area of
7697 // the call.
7698 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7699 E = CS.arg_end(); I != E; ++I)
7700 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7701 // If this cast does not effect the value passed through the varargs
7702 // area, we can eliminate the use of the cast.
7703 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007704 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007705 *I = Op;
7706 Changed = true;
7707 }
7708 }
7709 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007710
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007711 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007712}
7713
Chris Lattner970c33a2003-06-19 17:00:31 +00007714// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7715// attempt to move the cast to the arguments of the call/invoke.
7716//
7717bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7718 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7719 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007720 if (CE->getOpcode() != Instruction::BitCast ||
7721 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007722 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007723 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007724 Instruction *Caller = CS.getInstruction();
7725
7726 // Okay, this is a cast from a function to a different type. Unless doing so
7727 // would cause a type conversion of one of our arguments, change this call to
7728 // be a direct call with arguments casted to the appropriate types.
7729 //
7730 const FunctionType *FT = Callee->getFunctionType();
7731 const Type *OldRetTy = Caller->getType();
7732
Chris Lattner1f7942f2004-01-14 06:06:08 +00007733 // Check to see if we are changing the return type...
7734 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007735 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007736 // Conversion is ok if changing from pointer to int of same size.
7737 !(isa<PointerType>(FT->getReturnType()) &&
7738 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007739 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007740
7741 // If the callsite is an invoke instruction, and the return value is used by
7742 // a PHI node in a successor, we cannot change the return type of the call
7743 // because there is no place to put the cast instruction (without breaking
7744 // the critical edge). Bail out in this case.
7745 if (!Caller->use_empty())
7746 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7747 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7748 UI != E; ++UI)
7749 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7750 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007751 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007752 return false;
7753 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007754
7755 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7756 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007757
Chris Lattner970c33a2003-06-19 17:00:31 +00007758 CallSite::arg_iterator AI = CS.arg_begin();
7759 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7760 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007761 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007762 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Dale Johannesen7c2001d2007-04-04 19:16:42 +00007763 //Some conversions are safe even if we do not have a body.
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007764 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007765 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007766 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007767 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007768 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7769 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007770 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007771 if (Callee->isDeclaration() && !isConvertible) return false;
Dale Johannesen7c2001d2007-04-04 19:16:42 +00007772
7773 // Most other conversions can be done if we have a body, even if these
7774 // lose information, e.g. int->short.
7775 // Some conversions cannot be done at all, e.g. float to pointer.
7776 // Logic here parallels CastInst::getCastOpcode (the design there
7777 // requires legality checks like this be done before calling it).
7778 if (ParamTy->isInteger()) {
7779 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7780 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7781 return false;
7782 }
7783 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7784 !isa<PointerType>(ActTy))
7785 return false;
7786 } else if (ParamTy->isFloatingPoint()) {
7787 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7788 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7789 return false;
7790 }
7791 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7792 return false;
7793 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7794 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7795 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7796 return false;
7797 }
7798 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7799 return false;
7800 } else if (isa<PointerType>(ParamTy)) {
7801 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7802 return false;
7803 } else {
7804 return false;
7805 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007806 }
7807
7808 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007809 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007810 return false; // Do not delete arguments unless we have a function body...
7811
7812 // Okay, we decided that this is a safe thing to do: go ahead and start
7813 // inserting cast instructions as necessary...
7814 std::vector<Value*> Args;
7815 Args.reserve(NumActualArgs);
7816
7817 AI = CS.arg_begin();
7818 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7819 const Type *ParamTy = FT->getParamType(i);
7820 if ((*AI)->getType() == ParamTy) {
7821 Args.push_back(*AI);
7822 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007823 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007824 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007825 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007826 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007827 }
7828 }
7829
7830 // If the function takes more arguments than the call was taking, add them
7831 // now...
7832 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7833 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7834
7835 // If we are removing arguments to the function, emit an obnoxious warning...
7836 if (FT->getNumParams() < NumActualArgs)
7837 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007838 cerr << "WARNING: While resolving call to function '"
7839 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007840 } else {
7841 // Add all of the arguments in their promoted form to the arg list...
7842 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7843 const Type *PTy = getPromotedType((*AI)->getType());
7844 if (PTy != (*AI)->getType()) {
7845 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007846 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7847 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007848 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007849 InsertNewInstBefore(Cast, *Caller);
7850 Args.push_back(Cast);
7851 } else {
7852 Args.push_back(*AI);
7853 }
7854 }
7855 }
7856
7857 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007858 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007859
7860 Instruction *NC;
7861 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007862 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007863 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007864 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007865 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007866 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007867 if (cast<CallInst>(Caller)->isTailCall())
7868 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007869 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007870 }
7871
Chris Lattner6e0123b2007-02-11 01:23:03 +00007872 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007873 Value *NV = NC;
7874 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7875 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007876 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007877 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7878 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007879 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007880
7881 // If this is an invoke instruction, we should insert it after the first
7882 // non-phi, instruction in the normal successor block.
7883 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7884 BasicBlock::iterator I = II->getNormalDest()->begin();
7885 while (isa<PHINode>(I)) ++I;
7886 InsertNewInstBefore(NC, *I);
7887 } else {
7888 // Otherwise, it's a call, just insert cast right after the call instr
7889 InsertNewInstBefore(NC, *Caller);
7890 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007891 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007892 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007893 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007894 }
7895 }
7896
7897 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7898 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007899 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007900 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007901 return true;
7902}
7903
Chris Lattnercadac0c2006-11-01 04:51:18 +00007904/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7905/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7906/// and a single binop.
7907Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7908 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007909 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7910 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007911 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007912 Value *LHSVal = FirstInst->getOperand(0);
7913 Value *RHSVal = FirstInst->getOperand(1);
7914
7915 const Type *LHSType = LHSVal->getType();
7916 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007917
7918 // Scan to see if all operands are the same opcode, all have one use, and all
7919 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007920 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007921 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007922 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007923 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007924 // types or GEP's with different index types.
7925 I->getOperand(0)->getType() != LHSType ||
7926 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007927 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007928
7929 // If they are CmpInst instructions, check their predicates
7930 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7931 if (cast<CmpInst>(I)->getPredicate() !=
7932 cast<CmpInst>(FirstInst)->getPredicate())
7933 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007934
7935 // Keep track of which operand needs a phi node.
7936 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7937 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007938 }
7939
Chris Lattner4f218d52006-11-08 19:42:28 +00007940 // Otherwise, this is safe to transform, determine if it is profitable.
7941
7942 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7943 // Indexes are often folded into load/store instructions, so we don't want to
7944 // hide them behind a phi.
7945 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7946 return 0;
7947
Chris Lattnercadac0c2006-11-01 04:51:18 +00007948 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007949 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007950 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007951 if (LHSVal == 0) {
7952 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7953 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7954 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007955 InsertNewInstBefore(NewLHS, PN);
7956 LHSVal = NewLHS;
7957 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007958
7959 if (RHSVal == 0) {
7960 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7961 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7962 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007963 InsertNewInstBefore(NewRHS, PN);
7964 RHSVal = NewRHS;
7965 }
7966
Chris Lattnercd62f112006-11-08 19:29:23 +00007967 // Add all operands to the new PHIs.
7968 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7969 if (NewLHS) {
7970 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7971 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7972 }
7973 if (NewRHS) {
7974 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7975 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7976 }
7977 }
7978
Chris Lattnercadac0c2006-11-01 04:51:18 +00007979 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007980 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007981 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7982 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7983 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007984 else {
7985 assert(isa<GetElementPtrInst>(FirstInst));
7986 return new GetElementPtrInst(LHSVal, RHSVal);
7987 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007988}
7989
Chris Lattner14f82c72006-11-01 07:13:54 +00007990/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7991/// of the block that defines it. This means that it must be obvious the value
7992/// of the load is not changed from the point of the load to the end of the
7993/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007994///
7995/// Finally, it is safe, but not profitable, to sink a load targetting a
7996/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7997/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007998static bool isSafeToSinkLoad(LoadInst *L) {
7999 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8000
8001 for (++BBI; BBI != E; ++BBI)
8002 if (BBI->mayWriteToMemory())
8003 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00008004
8005 // Check for non-address taken alloca. If not address-taken already, it isn't
8006 // profitable to do this xform.
8007 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8008 bool isAddressTaken = false;
8009 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8010 UI != E; ++UI) {
8011 if (isa<LoadInst>(UI)) continue;
8012 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8013 // If storing TO the alloca, then the address isn't taken.
8014 if (SI->getOperand(1) == AI) continue;
8015 }
8016 isAddressTaken = true;
8017 break;
8018 }
8019
8020 if (!isAddressTaken)
8021 return false;
8022 }
8023
Chris Lattner14f82c72006-11-01 07:13:54 +00008024 return true;
8025}
8026
Chris Lattner970c33a2003-06-19 17:00:31 +00008027
Chris Lattner7515cab2004-11-14 19:13:23 +00008028// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8029// operator and they all are only used by the PHI, PHI together their
8030// inputs, and do the operation once, to the result of the PHI.
8031Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8032 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8033
8034 // Scan the instruction, looking for input operations that can be folded away.
8035 // If all input operands to the phi are the same instruction (e.g. a cast from
8036 // the same type or "+42") we can pull the operation through the PHI, reducing
8037 // code size and simplifying code.
8038 Constant *ConstantOp = 0;
8039 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00008040 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00008041 if (isa<CastInst>(FirstInst)) {
8042 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00008043 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008044 // Can fold binop, compare or shift here if the RHS is a constant,
8045 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00008046 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008047 if (ConstantOp == 0)
8048 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00008049 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8050 isVolatile = LI->isVolatile();
8051 // We can't sink the load if the loaded value could be modified between the
8052 // load and the PHI.
8053 if (LI->getParent() != PN.getIncomingBlock(0) ||
8054 !isSafeToSinkLoad(LI))
8055 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00008056 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00008057 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00008058 return FoldPHIArgBinOpIntoPHI(PN);
8059 // Can't handle general GEPs yet.
8060 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008061 } else {
8062 return 0; // Cannot fold this operation.
8063 }
8064
8065 // Check to see if all arguments are the same operation.
8066 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8067 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8068 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00008069 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00008070 return 0;
8071 if (CastSrcTy) {
8072 if (I->getOperand(0)->getType() != CastSrcTy)
8073 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00008074 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008075 // We can't sink the load if the loaded value could be modified between
8076 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00008077 if (LI->isVolatile() != isVolatile ||
8078 LI->getParent() != PN.getIncomingBlock(i) ||
8079 !isSafeToSinkLoad(LI))
8080 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008081 } else if (I->getOperand(1) != ConstantOp) {
8082 return 0;
8083 }
8084 }
8085
8086 // Okay, they are all the same operation. Create a new PHI node of the
8087 // correct type, and PHI together all of the LHS's of the instructions.
8088 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8089 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00008090 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00008091
8092 Value *InVal = FirstInst->getOperand(0);
8093 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00008094
8095 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00008096 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8097 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8098 if (NewInVal != InVal)
8099 InVal = 0;
8100 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8101 }
8102
8103 Value *PhiVal;
8104 if (InVal) {
8105 // The new PHI unions all of the same values together. This is really
8106 // common, so we handle it intelligently here for compile-time speed.
8107 PhiVal = InVal;
8108 delete NewPN;
8109 } else {
8110 InsertNewInstBefore(NewPN, PN);
8111 PhiVal = NewPN;
8112 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008113
Chris Lattner7515cab2004-11-14 19:13:23 +00008114 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008115 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8116 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00008117 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00008118 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00008119 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00008120 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00008121 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8122 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8123 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00008124 else
Reid Spencer2341c222007-02-02 02:16:23 +00008125 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00008126 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008127}
Chris Lattner48a44f72002-05-02 17:06:02 +00008128
Chris Lattner71536432005-01-17 05:10:15 +00008129/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8130/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00008131static bool DeadPHICycle(PHINode *PN,
8132 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00008133 if (PN->use_empty()) return true;
8134 if (!PN->hasOneUse()) return false;
8135
8136 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00008137 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00008138 return true;
8139
8140 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8141 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008142
Chris Lattner71536432005-01-17 05:10:15 +00008143 return false;
8144}
8145
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008146// PHINode simplification
8147//
Chris Lattner113f4f42002-06-25 16:13:24 +00008148Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00008149 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00008150 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00008151
Owen Andersonae8aa642006-07-10 22:03:18 +00008152 if (Value *V = PN.hasConstantValue())
8153 return ReplaceInstUsesWith(PN, V);
8154
Owen Andersonae8aa642006-07-10 22:03:18 +00008155 // If all PHI operands are the same operation, pull them through the PHI,
8156 // reducing code size.
8157 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8158 PN.getIncomingValue(0)->hasOneUse())
8159 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8160 return Result;
8161
8162 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8163 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8164 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008165 if (PN.hasOneUse()) {
8166 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8167 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00008168 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00008169 PotentiallyDeadPHIs.insert(&PN);
8170 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8171 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8172 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008173
8174 // If this phi has a single use, and if that use just computes a value for
8175 // the next iteration of a loop, delete the phi. This occurs with unused
8176 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8177 // common case here is good because the only other things that catch this
8178 // are induction variable analysis (sometimes) and ADCE, which is only run
8179 // late.
8180 if (PHIUser->hasOneUse() &&
8181 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8182 PHIUser->use_back() == &PN) {
8183 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8184 }
8185 }
Owen Andersonae8aa642006-07-10 22:03:18 +00008186
Chris Lattner91daeb52003-12-19 05:58:40 +00008187 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008188}
8189
Reid Spencer13bc5d72006-12-12 09:18:51 +00008190static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8191 Instruction *InsertPoint,
8192 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00008193 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8194 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008195 // We must cast correctly to the pointer type. Ensure that we
8196 // sign extend the integer value if it is smaller as this is
8197 // used for address computation.
8198 Instruction::CastOps opcode =
8199 (VTySize < PtrSize ? Instruction::SExt :
8200 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8201 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00008202}
8203
Chris Lattner48a44f72002-05-02 17:06:02 +00008204
Chris Lattner113f4f42002-06-25 16:13:24 +00008205Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008206 Value *PtrOp = GEP.getOperand(0);
Chris Lattneracbf6a42007-04-28 00:57:34 +00008207 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00008208 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008209 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00008210 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008211
Chris Lattner81a7a232004-10-16 18:11:37 +00008212 if (isa<UndefValue>(GEP.getOperand(0)))
8213 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8214
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008215 bool HasZeroPointerIndex = false;
8216 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8217 HasZeroPointerIndex = C->isNullValue();
8218
8219 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008220 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008221
Chris Lattner69193f92004-04-05 01:30:19 +00008222 // Eliminate unneeded casts for indices.
8223 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008224
Chris Lattner2b2412d2004-04-07 18:38:20 +00008225 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008226 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00008227 if (isa<SequentialType>(*GTI)) {
8228 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008229 if (CI->getOpcode() == Instruction::ZExt ||
8230 CI->getOpcode() == Instruction::SExt) {
8231 const Type *SrcTy = CI->getOperand(0)->getType();
8232 // We can eliminate a cast from i32 to i64 iff the target
8233 // is a 32-bit pointer target.
8234 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8235 MadeChange = true;
8236 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008237 }
8238 }
8239 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008240 // If we are using a wider index than needed for this platform, shrink it
8241 // to what we need. If the incoming value needs a cast instruction,
8242 // insert it. This explicit cast can make subsequent optimizations more
8243 // obvious.
8244 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008245 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008246 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008247 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008248 MadeChange = true;
8249 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008250 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8251 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008252 GEP.setOperand(i, Op);
8253 MadeChange = true;
8254 }
Chris Lattner69193f92004-04-05 01:30:19 +00008255 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008256 }
Chris Lattner69193f92004-04-05 01:30:19 +00008257 if (MadeChange) return &GEP;
8258
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008259 // If this GEP instruction doesn't move the pointer, and if the input operand
8260 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8261 // real input to the dest type.
Chris Lattneracbf6a42007-04-28 00:57:34 +00008262 if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
Chris Lattner9bf53ff2007-03-25 20:43:09 +00008263 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8264 GEP.getType());
8265
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008266 // Combine Indices - If the source pointer to this getelementptr instruction
8267 // is a getelementptr instruction, combine the indices of the two
8268 // getelementptr instructions into a single instruction.
8269 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008270 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008271 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008272 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008273
8274 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008275 // Note that if our source is a gep chain itself that we wait for that
8276 // chain to be resolved before we perform this transformation. This
8277 // avoids us creating a TON of code in some cases.
8278 //
8279 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8280 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8281 return 0; // Wait until our source is folded to completion.
8282
Chris Lattneraf6094f2007-02-15 22:48:32 +00008283 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008284
8285 // Find out whether the last index in the source GEP is a sequential idx.
8286 bool EndsWithSequential = false;
8287 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8288 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008289 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008290
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008291 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008292 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008293 // Replace: gep (gep %P, long B), long A, ...
8294 // With: T = long A+B; gep %P, T, ...
8295 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008296 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008297 if (SO1 == Constant::getNullValue(SO1->getType())) {
8298 Sum = GO1;
8299 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8300 Sum = SO1;
8301 } else {
8302 // If they aren't the same type, convert both to an integer of the
8303 // target's pointer size.
8304 if (SO1->getType() != GO1->getType()) {
8305 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008306 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008307 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008308 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008309 } else {
8310 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008311 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008312 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008313 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008314
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008315 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008316 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008317 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008318 } else {
8319 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008320 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8321 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008322 }
8323 }
8324 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008325 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8326 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8327 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008328 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8329 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008330 }
Chris Lattner69193f92004-04-05 01:30:19 +00008331 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008332
8333 // Recycle the GEP we already have if possible.
8334 if (SrcGEPOperands.size() == 2) {
8335 GEP.setOperand(0, SrcGEPOperands[0]);
8336 GEP.setOperand(1, Sum);
8337 return &GEP;
8338 } else {
8339 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8340 SrcGEPOperands.end()-1);
8341 Indices.push_back(Sum);
8342 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8343 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008344 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008345 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008346 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008347 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008348 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8349 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008350 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8351 }
8352
8353 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008354 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8355 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008356
Chris Lattner5f667a62004-05-07 22:09:22 +00008357 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008358 // GEP of global variable. If all of the indices for this GEP are
8359 // constants, we can promote this to a constexpr instead of an instruction.
8360
8361 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008362 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008363 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8364 for (; I != E && isa<Constant>(*I); ++I)
8365 Indices.push_back(cast<Constant>(*I));
8366
8367 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008368 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8369 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008370
8371 // Replace all uses of the GEP with the new constexpr...
8372 return ReplaceInstUsesWith(GEP, CE);
8373 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008374 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008375 if (!isa<PointerType>(X->getType())) {
8376 // Not interesting. Source pointer must be a cast from pointer.
8377 } else if (HasZeroPointerIndex) {
8378 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8379 // into : GEP [10 x ubyte]* X, long 0, ...
8380 //
8381 // This occurs when the program declares an array extern like "int X[];"
8382 //
8383 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8384 const PointerType *XTy = cast<PointerType>(X->getType());
8385 if (const ArrayType *XATy =
8386 dyn_cast<ArrayType>(XTy->getElementType()))
8387 if (const ArrayType *CATy =
8388 dyn_cast<ArrayType>(CPTy->getElementType()))
8389 if (CATy->getElementType() == XATy->getElementType()) {
8390 // At this point, we know that the cast source type is a pointer
8391 // to an array of the same type as the destination pointer
8392 // array. Because the array type is never stepped over (there
8393 // is a leading zero) we can fold the cast into this GEP.
8394 GEP.setOperand(0, X);
8395 return &GEP;
8396 }
8397 } else if (GEP.getNumOperands() == 2) {
8398 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008399 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8400 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008401 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8402 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8403 if (isa<ArrayType>(SrcElTy) &&
8404 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8405 TD->getTypeSize(ResElTy)) {
8406 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008407 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008408 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008409 // V and GEP are both pointer types --> BitCast
8410 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008411 }
Chris Lattner2a893292005-09-13 18:36:04 +00008412
8413 // Transform things like:
8414 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8415 // (where tmp = 8*tmp2) into:
8416 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8417
8418 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008419 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008420 uint64_t ArrayEltSize =
8421 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8422
8423 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8424 // allow either a mul, shift, or constant here.
8425 Value *NewIdx = 0;
8426 ConstantInt *Scale = 0;
8427 if (ArrayEltSize == 1) {
8428 NewIdx = GEP.getOperand(1);
8429 Scale = ConstantInt::get(NewIdx->getType(), 1);
8430 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008431 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008432 Scale = CI;
8433 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8434 if (Inst->getOpcode() == Instruction::Shl &&
8435 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00008436 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8437 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8438 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +00008439 NewIdx = Inst->getOperand(0);
8440 } else if (Inst->getOpcode() == Instruction::Mul &&
8441 isa<ConstantInt>(Inst->getOperand(1))) {
8442 Scale = cast<ConstantInt>(Inst->getOperand(1));
8443 NewIdx = Inst->getOperand(0);
8444 }
8445 }
8446
8447 // If the index will be to exactly the right offset with the scale taken
8448 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008449 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008450 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008451 Scale = ConstantInt::get(Scale->getType(),
8452 Scale->getZExtValue() / ArrayEltSize);
8453 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008454 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8455 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008456 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8457 NewIdx = InsertNewInstBefore(Sc, GEP);
8458 }
8459
8460 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008461 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008462 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008463 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008464 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8465 // The NewGEP must be pointer typed, so must the old one -> BitCast
8466 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008467 }
8468 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008469 }
Chris Lattnerca081252001-12-14 16:52:21 +00008470 }
8471
Chris Lattnerca081252001-12-14 16:52:21 +00008472 return 0;
8473}
8474
Chris Lattner1085bdf2002-11-04 16:18:53 +00008475Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8476 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8477 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008478 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8479 const Type *NewTy =
8480 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008481 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008482
8483 // Create and insert the replacement instruction...
8484 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008485 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008486 else {
8487 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008488 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008489 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008490
8491 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008492
Chris Lattner1085bdf2002-11-04 16:18:53 +00008493 // Scan to the end of the allocation instructions, to skip over a block of
8494 // allocas if possible...
8495 //
8496 BasicBlock::iterator It = New;
8497 while (isa<AllocationInst>(*It)) ++It;
8498
8499 // Now that I is pointing to the first non-allocation-inst in the block,
8500 // insert our getelementptr instruction...
8501 //
Reid Spencerc635f472006-12-31 05:48:39 +00008502 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008503 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8504 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008505
8506 // Now make everything use the getelementptr instead of the original
8507 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008508 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008509 } else if (isa<UndefValue>(AI.getArraySize())) {
8510 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008511 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008512
8513 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8514 // Note that we only do this for alloca's, because malloc should allocate and
8515 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008516 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008517 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008518 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8519
Chris Lattner1085bdf2002-11-04 16:18:53 +00008520 return 0;
8521}
8522
Chris Lattner8427bff2003-12-07 01:24:23 +00008523Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8524 Value *Op = FI.getOperand(0);
8525
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008526 // free undef -> unreachable.
8527 if (isa<UndefValue>(Op)) {
8528 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008529 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008530 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008531 return EraseInstFromFunction(FI);
8532 }
Chris Lattnerefb33d22007-04-14 00:20:02 +00008533
Chris Lattnerf3a36602004-02-28 04:57:37 +00008534 // If we have 'free null' delete the instruction. This can happen in stl code
8535 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008536 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008537 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +00008538
8539 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8540 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8541 FI.setOperand(0, CI->getOperand(0));
8542 return &FI;
8543 }
8544
8545 // Change free (gep X, 0,0,0,0) into free(X)
8546 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8547 if (GEPI->hasAllZeroIndices()) {
8548 AddToWorkList(GEPI);
8549 FI.setOperand(0, GEPI->getOperand(0));
8550 return &FI;
8551 }
8552 }
8553
8554 // Change free(malloc) into nothing, if the malloc has a single use.
8555 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8556 if (MI->hasOneUse()) {
8557 EraseInstFromFunction(FI);
8558 return EraseInstFromFunction(*MI);
8559 }
Chris Lattnerf3a36602004-02-28 04:57:37 +00008560
Chris Lattner8427bff2003-12-07 01:24:23 +00008561 return 0;
8562}
8563
8564
Chris Lattner72684fe2005-01-31 05:51:45 +00008565/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008566static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8567 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008568 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008569
8570 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008571 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008572 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008573
Reid Spencer31a4ef42007-01-22 05:51:25 +00008574 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008575 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008576 // If the source is an array, the code below will not succeed. Check to
8577 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8578 // constants.
8579 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8580 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8581 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008582 Value *Idxs[2];
8583 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8584 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008585 SrcTy = cast<PointerType>(CastOp->getType());
8586 SrcPTy = SrcTy->getElementType();
8587 }
8588
Reid Spencer31a4ef42007-01-22 05:51:25 +00008589 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008590 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008591 // Do not allow turning this into a load of an integer, which is then
8592 // casted to a pointer, this pessimizes pointer analysis a lot.
8593 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008594 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8595 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008596
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008597 // Okay, we are casting from one integer or pointer type to another of
8598 // the same size. Instead of casting the pointer before the load, cast
8599 // the result of the loaded value.
8600 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8601 CI->getName(),
8602 LI.isVolatile()),LI);
8603 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008604 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008605 }
Chris Lattner35e24772004-07-13 01:49:43 +00008606 }
8607 }
8608 return 0;
8609}
8610
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008611/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008612/// from this value cannot trap. If it is not obviously safe to load from the
8613/// specified pointer, we do a quick local scan of the basic block containing
8614/// ScanFrom, to determine if the address is already accessed.
8615static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8616 // If it is an alloca or global variable, it is always safe to load from.
8617 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8618
8619 // Otherwise, be a little bit agressive by scanning the local block where we
8620 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008621 // from/to. If so, the previous load or store would have already trapped,
8622 // so there is no harm doing an extra load (also, CSE will later eliminate
8623 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008624 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8625
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008626 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008627 --BBI;
8628
8629 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8630 if (LI->getOperand(0) == V) return true;
8631 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8632 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008633
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008634 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008635 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008636}
8637
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008638Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8639 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008640
Chris Lattnera9d84e32005-05-01 04:24:53 +00008641 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008642 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008643 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8644 return Res;
8645
8646 // None of the following transforms are legal for volatile loads.
8647 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008648
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008649 if (&LI.getParent()->front() != &LI) {
8650 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008651 // If the instruction immediately before this is a store to the same
8652 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008653 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8654 if (SI->getOperand(1) == LI.getOperand(0))
8655 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008656 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8657 if (LIB->getOperand(0) == LI.getOperand(0))
8658 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008659 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008660
8661 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
Chris Lattneracbf6a42007-04-28 00:57:34 +00008662 if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008663 // Insert a new store to null instruction before the load to indicate
8664 // that this code is not reachable. We do this instead of inserting
8665 // an unreachable instruction directly because we cannot modify the
8666 // CFG.
8667 new StoreInst(UndefValue::get(LI.getType()),
8668 Constant::getNullValue(Op->getType()), &LI);
8669 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8670 }
8671
Chris Lattner81a7a232004-10-16 18:11:37 +00008672 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008673 // load null/undef -> undef
8674 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008675 // Insert a new store to null instruction before the load to indicate that
8676 // this code is not reachable. We do this instead of inserting an
8677 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008678 new StoreInst(UndefValue::get(LI.getType()),
8679 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008680 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008681 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008682
Chris Lattner81a7a232004-10-16 18:11:37 +00008683 // Instcombine load (constant global) into the value loaded.
8684 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008685 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008686 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008687
Chris Lattner81a7a232004-10-16 18:11:37 +00008688 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8689 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8690 if (CE->getOpcode() == Instruction::GetElementPtr) {
8691 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008692 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008693 if (Constant *V =
8694 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008695 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008696 if (CE->getOperand(0)->isNullValue()) {
8697 // Insert a new store to null instruction before the load to indicate
8698 // that this code is not reachable. We do this instead of inserting
8699 // an unreachable instruction directly because we cannot modify the
8700 // CFG.
8701 new StoreInst(UndefValue::get(LI.getType()),
8702 Constant::getNullValue(Op->getType()), &LI);
8703 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8704 }
8705
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008706 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008707 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8708 return Res;
8709 }
8710 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008711
Chris Lattnera9d84e32005-05-01 04:24:53 +00008712 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008713 // Change select and PHI nodes to select values instead of addresses: this
8714 // helps alias analysis out a lot, allows many others simplifications, and
8715 // exposes redundancy in the code.
8716 //
8717 // Note that we cannot do the transformation unless we know that the
8718 // introduced loads cannot trap! Something like this is valid as long as
8719 // the condition is always false: load (select bool %C, int* null, int* %G),
8720 // but it would not be valid if we transformed it to load from null
8721 // unconditionally.
8722 //
8723 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8724 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008725 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8726 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008727 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008728 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008729 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008730 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008731 return new SelectInst(SI->getCondition(), V1, V2);
8732 }
8733
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008734 // load (select (cond, null, P)) -> load P
8735 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8736 if (C->isNullValue()) {
8737 LI.setOperand(0, SI->getOperand(2));
8738 return &LI;
8739 }
8740
8741 // load (select (cond, P, null)) -> load P
8742 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8743 if (C->isNullValue()) {
8744 LI.setOperand(0, SI->getOperand(1));
8745 return &LI;
8746 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008747 }
8748 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008749 return 0;
8750}
8751
Reid Spencere928a152007-01-19 21:20:31 +00008752/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008753/// when possible.
8754static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8755 User *CI = cast<User>(SI.getOperand(1));
8756 Value *CastOp = CI->getOperand(0);
8757
8758 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8759 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8760 const Type *SrcPTy = SrcTy->getElementType();
8761
Reid Spencer31a4ef42007-01-22 05:51:25 +00008762 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008763 // If the source is an array, the code below will not succeed. Check to
8764 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8765 // constants.
8766 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8767 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8768 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008769 Value* Idxs[2];
8770 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8771 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008772 SrcTy = cast<PointerType>(CastOp->getType());
8773 SrcPTy = SrcTy->getElementType();
8774 }
8775
Reid Spencer9a4bed02007-01-20 23:35:48 +00008776 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8777 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8778 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008779
8780 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008781 // the same size. Instead of casting the pointer before
8782 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008783 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008784 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008785 Instruction::CastOps opcode = Instruction::BitCast;
8786 const Type* CastSrcTy = SIOp0->getType();
8787 const Type* CastDstTy = SrcPTy;
8788 if (isa<PointerType>(CastDstTy)) {
8789 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008790 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008791 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008792 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008793 opcode = Instruction::PtrToInt;
8794 }
8795 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008796 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008797 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008798 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008799 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8800 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008801 return new StoreInst(NewCast, CastOp);
8802 }
8803 }
8804 }
8805 return 0;
8806}
8807
Chris Lattner31f486c2005-01-31 05:36:43 +00008808Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8809 Value *Val = SI.getOperand(0);
8810 Value *Ptr = SI.getOperand(1);
8811
8812 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008813 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008814 ++NumCombined;
8815 return 0;
8816 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008817
8818 // If the RHS is an alloca with a single use, zapify the store, making the
8819 // alloca dead.
8820 if (Ptr->hasOneUse()) {
8821 if (isa<AllocaInst>(Ptr)) {
8822 EraseInstFromFunction(SI);
8823 ++NumCombined;
8824 return 0;
8825 }
8826
8827 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8828 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8829 GEP->getOperand(0)->hasOneUse()) {
8830 EraseInstFromFunction(SI);
8831 ++NumCombined;
8832 return 0;
8833 }
8834 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008835
Chris Lattner5997cf92006-02-08 03:25:32 +00008836 // Do really simple DSE, to catch cases where there are several consequtive
8837 // stores to the same location, separated by a few arithmetic operations. This
8838 // situation often occurs with bitfield accesses.
8839 BasicBlock::iterator BBI = &SI;
8840 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8841 --ScanInsts) {
8842 --BBI;
8843
8844 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8845 // Prev store isn't volatile, and stores to the same location?
8846 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8847 ++NumDeadStore;
8848 ++BBI;
8849 EraseInstFromFunction(*PrevSI);
8850 continue;
8851 }
8852 break;
8853 }
8854
Chris Lattnerdab43b22006-05-26 19:19:20 +00008855 // If this is a load, we have to stop. However, if the loaded value is from
8856 // the pointer we're loading and is producing the pointer we're storing,
8857 // then *this* store is dead (X = load P; store X -> P).
8858 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8859 if (LI == Val && LI->getOperand(0) == Ptr) {
8860 EraseInstFromFunction(SI);
8861 ++NumCombined;
8862 return 0;
8863 }
8864 // Otherwise, this is a load from some other location. Stores before it
8865 // may not be dead.
8866 break;
8867 }
8868
Chris Lattner5997cf92006-02-08 03:25:32 +00008869 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008870 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008871 break;
8872 }
8873
8874
8875 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008876
8877 // store X, null -> turns into 'unreachable' in SimplifyCFG
8878 if (isa<ConstantPointerNull>(Ptr)) {
8879 if (!isa<UndefValue>(Val)) {
8880 SI.setOperand(0, UndefValue::get(Val->getType()));
8881 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008882 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008883 ++NumCombined;
8884 }
8885 return 0; // Do not modify these!
8886 }
8887
8888 // store undef, Ptr -> noop
8889 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008890 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008891 ++NumCombined;
8892 return 0;
8893 }
8894
Chris Lattner72684fe2005-01-31 05:51:45 +00008895 // If the pointer destination is a cast, see if we can fold the cast into the
8896 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008897 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008898 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8899 return Res;
8900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008901 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008902 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8903 return Res;
8904
Chris Lattner219175c2005-09-12 23:23:25 +00008905
8906 // If this store is the last instruction in the basic block, and if the block
8907 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008908 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008909 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner14a251b2007-04-15 00:07:55 +00008910 if (BI->isUnconditional())
8911 if (SimplifyStoreAtEndOfBlock(SI))
8912 return 0; // xform done!
Chris Lattner219175c2005-09-12 23:23:25 +00008913
Chris Lattner31f486c2005-01-31 05:36:43 +00008914 return 0;
8915}
8916
Chris Lattner14a251b2007-04-15 00:07:55 +00008917/// SimplifyStoreAtEndOfBlock - Turn things like:
8918/// if () { *P = v1; } else { *P = v2 }
8919/// into a phi node with a store in the successor.
8920///
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008921/// Simplify things like:
8922/// *P = v1; if () { *P = v2; }
8923/// into a phi node with a store in the successor.
8924///
Chris Lattner14a251b2007-04-15 00:07:55 +00008925bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
8926 BasicBlock *StoreBB = SI.getParent();
8927
8928 // Check to see if the successor block has exactly two incoming edges. If
8929 // so, see if the other predecessor contains a store to the same location.
8930 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008931 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner14a251b2007-04-15 00:07:55 +00008932
8933 // Determine whether Dest has exactly two predecessors and, if so, compute
8934 // the other predecessor.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008935 pred_iterator PI = pred_begin(DestBB);
8936 BasicBlock *OtherBB = 0;
Chris Lattner14a251b2007-04-15 00:07:55 +00008937 if (*PI != StoreBB)
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008938 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +00008939 ++PI;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008940 if (PI == pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +00008941 return false;
8942
8943 if (*PI != StoreBB) {
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008944 if (OtherBB)
Chris Lattner14a251b2007-04-15 00:07:55 +00008945 return false;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008946 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +00008947 }
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008948 if (++PI != pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +00008949 return false;
8950
8951
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008952 // Verify that the other block ends in a branch and is not otherwise empty.
8953 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner14a251b2007-04-15 00:07:55 +00008954 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008955 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner14a251b2007-04-15 00:07:55 +00008956 return false;
8957
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00008958 // If the other block ends in an unconditional branch, check for the 'if then
8959 // else' case. there is an instruction before the branch.
8960 StoreInst *OtherStore = 0;
8961 if (OtherBr->isUnconditional()) {
8962 // If this isn't a store, or isn't a store to the same location, bail out.
8963 --BBI;
8964 OtherStore = dyn_cast<StoreInst>(BBI);
8965 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
8966 return false;
8967 } else {
8968 // Otherwise, the other block ended with a conditional branch. If one of the
8969 // destinations is StoreBB, then we have the if/then case.
8970 if (OtherBr->getSuccessor(0) != StoreBB &&
8971 OtherBr->getSuccessor(1) != StoreBB)
8972 return false;
8973
8974 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
8975 // if/then triangle. See if there is a store to the same ptr as SI that lives
8976 // in OtherBB.
8977 for (;; --BBI) {
8978 // Check to see if we find the matching store.
8979 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
8980 if (OtherStore->getOperand(1) != SI.getOperand(1))
8981 return false;
8982 break;
8983 }
8984 // If we find something that may be using the stored value, or if we run out
8985 // of instructions, we can't do the xform.
8986 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
8987 BBI == OtherBB->begin())
8988 return false;
8989 }
8990
8991 // In order to eliminate the store in OtherBr, we have to
8992 // make sure nothing reads the stored value in StoreBB.
8993 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
8994 // FIXME: This should really be AA driven.
8995 if (isa<LoadInst>(I) || I->mayWriteToMemory())
8996 return false;
8997 }
8998 }
Chris Lattner14a251b2007-04-15 00:07:55 +00008999
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00009000 // Insert a PHI node now if we need it.
Chris Lattner14a251b2007-04-15 00:07:55 +00009001 Value *MergedVal = OtherStore->getOperand(0);
9002 if (MergedVal != SI.getOperand(0)) {
9003 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9004 PN->reserveOperandSpace(2);
9005 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00009006 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9007 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner14a251b2007-04-15 00:07:55 +00009008 }
9009
9010 // Advance to a place where it is safe to insert the new store and
9011 // insert it.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +00009012 BBI = DestBB->begin();
Chris Lattner14a251b2007-04-15 00:07:55 +00009013 while (isa<PHINode>(BBI)) ++BBI;
9014 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9015 OtherStore->isVolatile()), *BBI);
9016
9017 // Nuke the old stores.
9018 EraseInstFromFunction(SI);
9019 EraseInstFromFunction(*OtherStore);
9020 ++NumCombined;
9021 return true;
9022}
9023
Chris Lattner31f486c2005-01-31 05:36:43 +00009024
Chris Lattner9eef8a72003-06-04 04:46:00 +00009025Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9026 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00009027 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00009028 BasicBlock *TrueDest;
9029 BasicBlock *FalseDest;
9030 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9031 !isa<Constant>(X)) {
9032 // Swap Destinations and condition...
9033 BI.setCondition(X);
9034 BI.setSuccessor(0, FalseDest);
9035 BI.setSuccessor(1, TrueDest);
9036 return &BI;
9037 }
9038
Reid Spencer266e42b2006-12-23 06:05:41 +00009039 // Cannonicalize fcmp_one -> fcmp_oeq
9040 FCmpInst::Predicate FPred; Value *Y;
9041 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9042 TrueDest, FalseDest)))
9043 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9044 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9045 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009046 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009047 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9048 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00009049 // Swap Destinations and condition...
9050 BI.setCondition(NewSCC);
9051 BI.setSuccessor(0, FalseDest);
9052 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009053 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009054 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009055 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00009056 return &BI;
9057 }
9058
9059 // Cannonicalize icmp_ne -> icmp_eq
9060 ICmpInst::Predicate IPred;
9061 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9062 TrueDest, FalseDest)))
9063 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9064 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9065 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9066 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009067 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009068 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9069 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00009070 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00009071 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009072 BI.setSuccessor(0, FalseDest);
9073 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009074 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009075 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009076 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009077 return &BI;
9078 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009079
Chris Lattner9eef8a72003-06-04 04:46:00 +00009080 return 0;
9081}
Chris Lattner1085bdf2002-11-04 16:18:53 +00009082
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009083Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9084 Value *Cond = SI.getCondition();
9085 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9086 if (I->getOpcode() == Instruction::Add)
9087 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9088 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9089 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00009090 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009091 AddRHS));
9092 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009093 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009094 return &SI;
9095 }
9096 }
9097 return 0;
9098}
9099
Chris Lattner6bc98652006-03-05 00:22:33 +00009100/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9101/// is to leave as a vector operation.
9102static bool CheapToScalarize(Value *V, bool isConstant) {
9103 if (isa<ConstantAggregateZero>(V))
9104 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009105 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009106 if (isConstant) return true;
9107 // If all elts are the same, we can extract.
9108 Constant *Op0 = C->getOperand(0);
9109 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9110 if (C->getOperand(i) != Op0)
9111 return false;
9112 return true;
9113 }
9114 Instruction *I = dyn_cast<Instruction>(V);
9115 if (!I) return false;
9116
9117 // Insert element gets simplified to the inserted element or is deleted if
9118 // this is constant idx extract element and its a constant idx insertelt.
9119 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9120 isa<ConstantInt>(I->getOperand(2)))
9121 return true;
9122 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9123 return true;
9124 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9125 if (BO->hasOneUse() &&
9126 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9127 CheapToScalarize(BO->getOperand(1), isConstant)))
9128 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00009129 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9130 if (CI->hasOneUse() &&
9131 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9132 CheapToScalarize(CI->getOperand(1), isConstant)))
9133 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00009134
9135 return false;
9136}
9137
Chris Lattner945e4372007-02-14 05:52:17 +00009138/// Read and decode a shufflevector mask.
9139///
9140/// It turns undef elements into values that are larger than the number of
9141/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00009142static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9143 unsigned NElts = SVI->getType()->getNumElements();
9144 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9145 return std::vector<unsigned>(NElts, 0);
9146 if (isa<UndefValue>(SVI->getOperand(2)))
9147 return std::vector<unsigned>(NElts, 2*NElts);
9148
9149 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009150 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00009151 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9152 if (isa<UndefValue>(CP->getOperand(i)))
9153 Result.push_back(NElts*2); // undef -> 8
9154 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00009155 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00009156 return Result;
9157}
9158
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009159/// FindScalarElement - Given a vector and an element number, see if the scalar
9160/// value is already around as a register, for example if it were inserted then
9161/// extracted from the vector.
9162static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009163 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9164 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00009165 unsigned Width = PTy->getNumElements();
9166 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009167 return UndefValue::get(PTy->getElementType());
9168
9169 if (isa<UndefValue>(V))
9170 return UndefValue::get(PTy->getElementType());
9171 else if (isa<ConstantAggregateZero>(V))
9172 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00009173 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009174 return CP->getOperand(EltNo);
9175 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9176 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009177 if (!isa<ConstantInt>(III->getOperand(2)))
9178 return 0;
9179 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009180
9181 // If this is an insert to the element we are looking for, return the
9182 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009183 if (EltNo == IIElt)
9184 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009185
9186 // Otherwise, the insertelement doesn't modify the value, recurse on its
9187 // vector input.
9188 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00009189 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00009190 unsigned InEl = getShuffleMask(SVI)[EltNo];
9191 if (InEl < Width)
9192 return FindScalarElement(SVI->getOperand(0), InEl);
9193 else if (InEl < Width*2)
9194 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9195 else
9196 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009197 }
9198
9199 // Otherwise, we don't know.
9200 return 0;
9201}
9202
Robert Bocchinoa8352962006-01-13 22:48:06 +00009203Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009204
Chris Lattner92346c32006-03-31 18:25:14 +00009205 // If packed val is undef, replace extract with scalar undef.
9206 if (isa<UndefValue>(EI.getOperand(0)))
9207 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9208
9209 // If packed val is constant 0, replace extract with scalar 0.
9210 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9211 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9212
Reid Spencerd84d35b2007-02-15 02:26:10 +00009213 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009214 // If packed val is constant with uniform operands, replace EI
9215 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00009216 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009217 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00009218 if (C->getOperand(i) != op0) {
9219 op0 = 0;
9220 break;
9221 }
9222 if (op0)
9223 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009224 }
Chris Lattner6bc98652006-03-05 00:22:33 +00009225
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009226 // If extracting a specified index from the vector, see if we can recursively
9227 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009228 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +00009229 unsigned IndexVal = IdxC->getZExtValue();
9230 unsigned VectorWidth =
9231 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9232
9233 // If this is extracting an invalid index, turn this into undef, to avoid
9234 // crashing the code below.
9235 if (IndexVal >= VectorWidth)
9236 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9237
Chris Lattner2deeaea2006-10-05 06:55:50 +00009238 // This instruction only demands the single element from the input vector.
9239 // If the input vector has a single use, simplify it based on this use
9240 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +00009241 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00009242 uint64_t UndefElts;
9243 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00009244 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00009245 UndefElts)) {
9246 EI.setOperand(0, V);
9247 return &EI;
9248 }
9249 }
9250
Reid Spencere0fc4df2006-10-20 07:07:24 +00009251 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009252 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +00009253
9254 // If the this extractelement is directly using a bitcast from a vector of
9255 // the same number of elements, see if we can find the source element from
9256 // it. In this case, we will end up needing to bitcast the scalars.
9257 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9258 if (const VectorType *VT =
9259 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9260 if (VT->getNumElements() == VectorWidth)
9261 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9262 return new BitCastInst(Elt, EI.getType());
9263 }
Chris Lattner2d37f922006-04-10 23:06:36 +00009264 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009265
Chris Lattner83f65782006-05-25 22:53:38 +00009266 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009267 if (I->hasOneUse()) {
9268 // Push extractelement into predecessor operation if legal and
9269 // profitable to do so
9270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009271 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9272 if (CheapToScalarize(BO, isConstantElt)) {
9273 ExtractElementInst *newEI0 =
9274 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9275 EI.getName()+".lhs");
9276 ExtractElementInst *newEI1 =
9277 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9278 EI.getName()+".rhs");
9279 InsertNewInstBefore(newEI0, EI);
9280 InsertNewInstBefore(newEI1, EI);
9281 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9282 }
Reid Spencerde46e482006-11-02 20:25:50 +00009283 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009284 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00009285 PointerType::get(EI.getType()), EI);
9286 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00009287 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00009288 InsertNewInstBefore(GEP, EI);
9289 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00009290 }
9291 }
9292 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9293 // Extracting the inserted element?
9294 if (IE->getOperand(2) == EI.getOperand(1))
9295 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9296 // If the inserted and extracted elements are constants, they must not
9297 // be the same value, extract from the pre-inserted value instead.
9298 if (isa<Constant>(IE->getOperand(2)) &&
9299 isa<Constant>(EI.getOperand(1))) {
9300 AddUsesToWorkList(EI);
9301 EI.setOperand(0, IE->getOperand(0));
9302 return &EI;
9303 }
9304 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9305 // If this is extracting an element from a shufflevector, figure out where
9306 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009307 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9308 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00009309 Value *Src;
9310 if (SrcIdx < SVI->getType()->getNumElements())
9311 Src = SVI->getOperand(0);
9312 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9313 SrcIdx -= SVI->getType()->getNumElements();
9314 Src = SVI->getOperand(1);
9315 } else {
9316 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009317 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009318 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009319 }
9320 }
Chris Lattner83f65782006-05-25 22:53:38 +00009321 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009322 return 0;
9323}
9324
Chris Lattner90951862006-04-16 00:51:47 +00009325/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9326/// elements from either LHS or RHS, return the shuffle mask and true.
9327/// Otherwise, return false.
9328static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9329 std::vector<Constant*> &Mask) {
9330 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9331 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009332 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009333
9334 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009335 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009336 return true;
9337 } else if (V == LHS) {
9338 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009339 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009340 return true;
9341 } else if (V == RHS) {
9342 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009343 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009344 return true;
9345 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9346 // If this is an insert of an extract from some other vector, include it.
9347 Value *VecOp = IEI->getOperand(0);
9348 Value *ScalarOp = IEI->getOperand(1);
9349 Value *IdxOp = IEI->getOperand(2);
9350
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009351 if (!isa<ConstantInt>(IdxOp))
9352 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009353 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009354
9355 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9356 // Okay, we can handle this if the vector we are insertinting into is
9357 // transitively ok.
9358 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9359 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009360 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009361 return true;
9362 }
9363 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9364 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009365 EI->getOperand(0)->getType() == V->getType()) {
9366 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009367 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009368
9369 // This must be extracting from either LHS or RHS.
9370 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9371 // Okay, we can handle this if the vector we are insertinting into is
9372 // transitively ok.
9373 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9374 // If so, update the mask to reflect the inserted value.
9375 if (EI->getOperand(0) == LHS) {
9376 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009377 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009378 } else {
9379 assert(EI->getOperand(0) == RHS);
9380 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009381 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009382
9383 }
9384 return true;
9385 }
9386 }
9387 }
9388 }
9389 }
9390 // TODO: Handle shufflevector here!
9391
9392 return false;
9393}
9394
9395/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9396/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9397/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009398static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009399 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009400 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009401 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009402 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009403 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009404
9405 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009406 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009407 return V;
9408 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009409 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009410 return V;
9411 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9412 // If this is an insert of an extract from some other vector, include it.
9413 Value *VecOp = IEI->getOperand(0);
9414 Value *ScalarOp = IEI->getOperand(1);
9415 Value *IdxOp = IEI->getOperand(2);
9416
9417 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9418 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9419 EI->getOperand(0)->getType() == V->getType()) {
9420 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009421 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9422 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009423
9424 // Either the extracted from or inserted into vector must be RHSVec,
9425 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009426 if (EI->getOperand(0) == RHS || RHS == 0) {
9427 RHS = EI->getOperand(0);
9428 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009429 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009430 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009431 return V;
9432 }
9433
Chris Lattner90951862006-04-16 00:51:47 +00009434 if (VecOp == RHS) {
9435 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009436 // Everything but the extracted element is replaced with the RHS.
9437 for (unsigned i = 0; i != NumElts; ++i) {
9438 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009439 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009440 }
9441 return V;
9442 }
Chris Lattner90951862006-04-16 00:51:47 +00009443
9444 // If this insertelement is a chain that comes from exactly these two
9445 // vectors, return the vector and the effective shuffle.
9446 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9447 return EI->getOperand(0);
9448
Chris Lattner39fac442006-04-15 01:39:45 +00009449 }
9450 }
9451 }
Chris Lattner90951862006-04-16 00:51:47 +00009452 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009453
9454 // Otherwise, can't do anything fancy. Return an identity vector.
9455 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009456 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009457 return V;
9458}
9459
9460Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9461 Value *VecOp = IE.getOperand(0);
9462 Value *ScalarOp = IE.getOperand(1);
9463 Value *IdxOp = IE.getOperand(2);
9464
Chris Lattner4ca9cbb2007-04-09 01:11:16 +00009465 // Inserting an undef or into an undefined place, remove this.
9466 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9467 ReplaceInstUsesWith(IE, VecOp);
9468
Chris Lattner39fac442006-04-15 01:39:45 +00009469 // If the inserted element was extracted from some other vector, and if the
9470 // indexes are constant, try to turn this into a shufflevector operation.
9471 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9472 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9473 EI->getOperand(0)->getType() == IE.getType()) {
9474 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattner28d921d2007-04-14 23:32:02 +00009475 unsigned ExtractedIdx =
9476 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009477 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009478
9479 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9480 return ReplaceInstUsesWith(IE, VecOp);
9481
9482 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9483 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9484
9485 // If we are extracting a value from a vector, then inserting it right
9486 // back into the same place, just use the input vector.
9487 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9488 return ReplaceInstUsesWith(IE, VecOp);
9489
9490 // We could theoretically do this for ANY input. However, doing so could
9491 // turn chains of insertelement instructions into a chain of shufflevector
9492 // instructions, and right now we do not merge shufflevectors. As such,
9493 // only do this in a situation where it is clear that there is benefit.
9494 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9495 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9496 // the values of VecOp, except then one read from EIOp0.
9497 // Build a new shuffle mask.
9498 std::vector<Constant*> Mask;
9499 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009500 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009501 else {
9502 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009503 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009504 NumVectorElts));
9505 }
Reid Spencerc635f472006-12-31 05:48:39 +00009506 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009507 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009508 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009509 }
9510
9511 // If this insertelement isn't used by some other insertelement, turn it
9512 // (and any insertelements it points to), into one big shuffle.
9513 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9514 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009515 Value *RHS = 0;
9516 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9517 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9518 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009519 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009520 }
9521 }
9522 }
9523
9524 return 0;
9525}
9526
9527
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009528Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9529 Value *LHS = SVI.getOperand(0);
9530 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009531 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009532
9533 bool MadeChange = false;
9534
Chris Lattner2deeaea2006-10-05 06:55:50 +00009535 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009536 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009537 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9538
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009539 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009540 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009541 if (isa<UndefValue>(SVI.getOperand(1))) {
9542 // Scan to see if there are any references to the RHS. If so, replace them
9543 // with undef element refs and set MadeChange to true.
9544 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9545 if (Mask[i] >= e && Mask[i] != 2*e) {
9546 Mask[i] = 2*e;
9547 MadeChange = true;
9548 }
9549 }
9550
9551 if (MadeChange) {
9552 // Remap any references to RHS to use LHS.
9553 std::vector<Constant*> Elts;
9554 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9555 if (Mask[i] == 2*e)
9556 Elts.push_back(UndefValue::get(Type::Int32Ty));
9557 else
9558 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9559 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009560 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009561 }
9562 }
Chris Lattner39fac442006-04-15 01:39:45 +00009563
Chris Lattner12249be2006-05-25 23:48:38 +00009564 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9565 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9566 if (LHS == RHS || isa<UndefValue>(LHS)) {
9567 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009568 // shuffle(undef,undef,mask) -> undef.
9569 return ReplaceInstUsesWith(SVI, LHS);
9570 }
9571
Chris Lattner12249be2006-05-25 23:48:38 +00009572 // Remap any references to RHS to use LHS.
9573 std::vector<Constant*> Elts;
9574 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009575 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009576 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009577 else {
9578 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9579 (Mask[i] < e && isa<UndefValue>(LHS)))
9580 Mask[i] = 2*e; // Turn into undef.
9581 else
9582 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009583 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009584 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009585 }
Chris Lattner12249be2006-05-25 23:48:38 +00009586 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009587 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009588 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009589 LHS = SVI.getOperand(0);
9590 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009591 MadeChange = true;
9592 }
9593
Chris Lattner0e477162006-05-26 00:29:06 +00009594 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009595 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009596
Chris Lattner12249be2006-05-25 23:48:38 +00009597 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9598 if (Mask[i] >= e*2) continue; // Ignore undef values.
9599 // Is this an identity shuffle of the LHS value?
9600 isLHSID &= (Mask[i] == i);
9601
9602 // Is this an identity shuffle of the RHS value?
9603 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009604 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009605
Chris Lattner12249be2006-05-25 23:48:38 +00009606 // Eliminate identity shuffles.
9607 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9608 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009609
Chris Lattner0e477162006-05-26 00:29:06 +00009610 // If the LHS is a shufflevector itself, see if we can combine it with this
9611 // one without producing an unusual shuffle. Here we are really conservative:
9612 // we are absolutely afraid of producing a shuffle mask not in the input
9613 // program, because the code gen may not be smart enough to turn a merged
9614 // shuffle into two specific shuffles: it may produce worse code. As such,
9615 // we only merge two shuffles if the result is one of the two input shuffle
9616 // masks. In this case, merging the shuffles just removes one instruction,
9617 // which we know is safe. This is good for things like turning:
9618 // (splat(splat)) -> splat.
9619 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9620 if (isa<UndefValue>(RHS)) {
9621 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9622
9623 std::vector<unsigned> NewMask;
9624 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9625 if (Mask[i] >= 2*e)
9626 NewMask.push_back(2*e);
9627 else
9628 NewMask.push_back(LHSMask[Mask[i]]);
9629
9630 // If the result mask is equal to the src shuffle or this shuffle mask, do
9631 // the replacement.
9632 if (NewMask == LHSMask || NewMask == Mask) {
9633 std::vector<Constant*> Elts;
9634 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9635 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009636 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009637 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009638 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009639 }
9640 }
9641 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9642 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009643 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009644 }
9645 }
9646 }
Chris Lattner4284f642007-01-30 22:32:46 +00009647
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009648 return MadeChange ? &SVI : 0;
9649}
9650
9651
Robert Bocchinoa8352962006-01-13 22:48:06 +00009652
Chris Lattner39c98bb2004-12-08 23:43:58 +00009653
9654/// TryToSinkInstruction - Try to move the specified instruction from its
9655/// current block into the beginning of DestBlock, which can only happen if it's
9656/// safe to move the instruction past all of the instructions between it and the
9657/// end of its block.
9658static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9659 assert(I->hasOneUse() && "Invariants didn't hold!");
9660
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009661 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9662 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009663
Chris Lattner39c98bb2004-12-08 23:43:58 +00009664 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009665 if (isa<AllocaInst>(I) && I->getParent() ==
9666 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009667 return false;
9668
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009669 // We can only sink load instructions if there is nothing between the load and
9670 // the end of block that could change the value.
9671 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009672 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9673 Scan != E; ++Scan)
9674 if (Scan->mayWriteToMemory())
9675 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009676 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009677
9678 BasicBlock::iterator InsertPos = DestBlock->begin();
9679 while (isa<PHINode>(InsertPos)) ++InsertPos;
9680
Chris Lattner9f269e42005-08-08 19:11:57 +00009681 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009682 ++NumSunkInst;
9683 return true;
9684}
9685
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009686
9687/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9688/// all reachable code to the worklist.
9689///
9690/// This has a couple of tricks to make the code faster and more powerful. In
9691/// particular, we constant fold and DCE instructions as we go, to avoid adding
9692/// them to the worklist (this significantly speeds up instcombine on code where
9693/// many instructions are dead or constant). Additionally, if we find a branch
9694/// whose condition is a known constant, we only visit the reachable successors.
9695///
9696static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009697 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009698 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009699 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009700 std::vector<BasicBlock*> Worklist;
9701 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009702
Chris Lattner12b89cc2007-03-23 19:17:18 +00009703 while (!Worklist.empty()) {
9704 BB = Worklist.back();
9705 Worklist.pop_back();
9706
9707 // We have now visited this block! If we've already been here, ignore it.
9708 if (!Visited.insert(BB)) continue;
9709
9710 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9711 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009712
Chris Lattner12b89cc2007-03-23 19:17:18 +00009713 // DCE instruction if trivially dead.
9714 if (isInstructionTriviallyDead(Inst)) {
9715 ++NumDeadInst;
9716 DOUT << "IC: DCE: " << *Inst;
9717 Inst->eraseFromParent();
9718 continue;
9719 }
9720
9721 // ConstantProp instruction if trivially constant.
9722 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9723 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9724 Inst->replaceAllUsesWith(C);
9725 ++NumConstProp;
9726 Inst->eraseFromParent();
9727 continue;
9728 }
9729
9730 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009731 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009732
9733 // Recursively visit successors. If this is a branch or switch on a
9734 // constant, only visit the reachable successor.
9735 TerminatorInst *TI = BB->getTerminator();
9736 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9737 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9738 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9739 Worklist.push_back(BI->getSuccessor(!CondVal));
9740 continue;
9741 }
9742 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9743 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9744 // See if this is an explicit destination.
9745 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9746 if (SI->getCaseValue(i) == Cond) {
9747 Worklist.push_back(SI->getSuccessor(i));
9748 continue;
9749 }
9750
9751 // Otherwise it is the default destination.
9752 Worklist.push_back(SI->getSuccessor(0));
9753 continue;
9754 }
9755 }
9756
9757 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9758 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009759 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009760}
9761
Chris Lattner960a5432007-03-03 02:04:50 +00009762bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009763 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009764 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009765
9766 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9767 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009768
Chris Lattner4ed40f72005-07-07 20:40:38 +00009769 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009770 // Do a depth-first traversal of the function, populate the worklist with
9771 // the reachable instructions. Ignore blocks that are not reachable. Keep
9772 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009773 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009774 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009775
Chris Lattner4ed40f72005-07-07 20:40:38 +00009776 // Do a quick scan over the function. If we find any blocks that are
9777 // unreachable, remove any instructions inside of them. This prevents
9778 // the instcombine code from having to deal with some bad special cases.
9779 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9780 if (!Visited.count(BB)) {
9781 Instruction *Term = BB->getTerminator();
9782 while (Term != BB->begin()) { // Remove instrs bottom-up
9783 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009784
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009785 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009786 ++NumDeadInst;
9787
9788 if (!I->use_empty())
9789 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9790 I->eraseFromParent();
9791 }
9792 }
9793 }
Chris Lattnerca081252001-12-14 16:52:21 +00009794
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009795 while (!Worklist.empty()) {
9796 Instruction *I = RemoveOneFromWorkList();
9797 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009798
Chris Lattner1443bc52006-05-11 17:11:52 +00009799 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009800 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009801 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009802 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009803 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009804 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009805
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009806 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009807
9808 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009809 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009810 continue;
9811 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009812
Chris Lattner1443bc52006-05-11 17:11:52 +00009813 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009814 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009815 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009816
Chris Lattner1443bc52006-05-11 17:11:52 +00009817 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009818 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009819 ReplaceInstUsesWith(*I, C);
9820
Chris Lattner99f48c62002-09-02 04:59:56 +00009821 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009822 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009823 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009824 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009825 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009826
Chris Lattner39c98bb2004-12-08 23:43:58 +00009827 // See if we can trivially sink this instruction to a successor basic block.
9828 if (I->hasOneUse()) {
9829 BasicBlock *BB = I->getParent();
9830 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9831 if (UserParent != BB) {
9832 bool UserIsSuccessor = false;
9833 // See if the user is one of our successors.
9834 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9835 if (*SI == UserParent) {
9836 UserIsSuccessor = true;
9837 break;
9838 }
9839
9840 // If the user is one of our immediate successors, and if that successor
9841 // only has us as a predecessors (we'd have to split the critical edge
9842 // otherwise), we can keep going.
9843 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9844 next(pred_begin(UserParent)) == pred_end(UserParent))
9845 // Okay, the CFG is simple enough, try to sink this instruction.
9846 Changed |= TryToSinkInstruction(I, UserParent);
9847 }
9848 }
9849
Chris Lattnerca081252001-12-14 16:52:21 +00009850 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009851#ifndef NDEBUG
9852 std::string OrigI;
9853#endif
9854 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009855 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009856 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009857 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009858 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009859 DOUT << "IC: Old = " << *I
9860 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009861
Chris Lattner396dbfe2004-06-09 05:08:07 +00009862 // Everything uses the new instruction now.
9863 I->replaceAllUsesWith(Result);
9864
9865 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009866 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009867 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009868
Chris Lattner6e0123b2007-02-11 01:23:03 +00009869 // Move the name to the new instruction first.
9870 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009871
9872 // Insert the new instruction into the basic block...
9873 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009874 BasicBlock::iterator InsertPos = I;
9875
9876 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9877 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9878 ++InsertPos;
9879
9880 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009881
Chris Lattner63d75af2004-05-01 23:27:23 +00009882 // Make sure that we reprocess all operands now that we reduced their
9883 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009884 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009885
Chris Lattner396dbfe2004-06-09 05:08:07 +00009886 // Instructions can end up on the worklist more than once. Make sure
9887 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009888 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009889
9890 // Erase the old instruction.
9891 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009892 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009893#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009894 DOUT << "IC: Mod = " << OrigI
9895 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009896#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009897
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009898 // If the instruction was modified, it's possible that it is now dead.
9899 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009900 if (isInstructionTriviallyDead(I)) {
9901 // Make sure we process all operands now that we are reducing their
9902 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009903 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009904
Chris Lattner63d75af2004-05-01 23:27:23 +00009905 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009906 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009907 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009908 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009909 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009910 AddToWorkList(I);
9911 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009912 }
Chris Lattner053c0932002-05-14 15:24:07 +00009913 }
Chris Lattner260ab202002-04-18 17:39:14 +00009914 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009915 }
9916 }
9917
Chris Lattner960a5432007-03-03 02:04:50 +00009918 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009919 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009920}
9921
Chris Lattner960a5432007-03-03 02:04:50 +00009922
9923bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009924 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9925
Chris Lattner960a5432007-03-03 02:04:50 +00009926 bool EverMadeChange = false;
9927
9928 // Iterate while there is work to do.
9929 unsigned Iteration = 0;
9930 while (DoOneIteration(F, Iteration++))
9931 EverMadeChange = true;
9932 return EverMadeChange;
9933}
9934
Brian Gaeke38b79e82004-07-27 17:43:21 +00009935FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009936 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009937}
Brian Gaeke960707c2003-11-11 22:41:34 +00009938