blob: 219f18209b98e0dc13cdd37124e6902df9343a34 [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 Spencer3f4e6e82007-02-04 00:40:42 +000059#include <set>
Chris Lattner8427bff2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000062
Chris Lattner79a42ac2006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000068
Chris Lattner79a42ac2006-12-19 21:40:18 +000069namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattner260ab202002-04-18 17:39:14 +0000103
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000104
Chris Lattner51ea1272004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000113 }
114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000122 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000142
Chris Lattner260ab202002-04-18 17:39:14 +0000143 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000147
Chris Lattnerf12cc842002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000152 }
153
Chris Lattner69193f92004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattner260ab202002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000186
Reid Spencer266e42b2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224
Chris Lattner970c33a2003-06-19 17:00:31 +0000225 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner69193f92004-04-05 01:30:19 +0000229 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner623826c2004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000239 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 }
241
Chris Lattner7e794272004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000248
Chris Lattnere79d2492006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000251
Reid Spencer13bc5d72006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000274 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000275
Chris Lattner2590e512006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner51ea1272004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattner3ac7c262003-08-13 20:16:26 +0000305 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencer266e42b2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000317
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Reid Spencer959a21d2007-03-23 21:24:59 +0000322 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
323 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000324 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
325 APInt& KnownZero, APInt& KnownOne,
326 unsigned Depth = 0);
327
Chris Lattner2deeaea2006-10-05 06:55:50 +0000328 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
329 uint64_t &UndefElts, unsigned Depth = 0);
330
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000331 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
332 // PHI node as operand #0, see if we can fold the instruction into the PHI
333 // (which is only possible if all operands to the PHI are constants).
334 Instruction *FoldOpIntoPhi(Instruction &I);
335
Chris Lattner7515cab2004-11-14 19:13:23 +0000336 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
337 // operator and they all are only used by the PHI, PHI together their
338 // inputs, and do the operation once, to the result of the PHI.
339 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000340 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
341
342
Zhou Sheng75b871f2007-01-11 12:24:14 +0000343 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
344 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000345
Zhou Sheng75b871f2007-01-11 12:24:14 +0000346 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000347 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000348 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000349 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000350 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000351 Instruction *MatchBSwap(BinaryOperator &I);
352
Reid Spencer74a528b2006-12-13 18:21:21 +0000353 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000354 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000355
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000356 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000357}
358
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000360// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000361static unsigned getComplexity(Value *V) {
362 if (isa<Instruction>(V)) {
363 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000364 return 3;
365 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000366 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000367 if (isa<Argument>(V)) return 3;
368 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000369}
Chris Lattner260ab202002-04-18 17:39:14 +0000370
Chris Lattner7fb29e12003-03-11 00:12:48 +0000371// isOnlyUse - Return true if this instruction will be deleted if we stop using
372// it.
373static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000374 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375}
376
Chris Lattnere79e8542004-02-23 06:38:22 +0000377// getPromotedType - Return the specified type promoted as it would be to pass
378// though a va_arg area...
379static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000380 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
381 if (ITy->getBitWidth() < 32)
382 return Type::Int32Ty;
383 } else if (Ty == Type::FloatTy)
384 return Type::DoubleTy;
385 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000386}
387
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000388/// getBitCastOperand - If the specified operand is a CastInst or a constant
389/// expression bitcast, return the operand value, otherwise return null.
390static Value *getBitCastOperand(Value *V) {
391 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000392 return I->getOperand(0);
393 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000394 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000395 return CE->getOperand(0);
396 return 0;
397}
398
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399/// This function is a wrapper around CastInst::isEliminableCastPair. It
400/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000401static Instruction::CastOps
402isEliminableCastPair(
403 const CastInst *CI, ///< The first cast instruction
404 unsigned opcode, ///< The opcode of the second cast instruction
405 const Type *DstTy, ///< The target type for the second cast instruction
406 TargetData *TD ///< The target data for pointer size
407) {
408
409 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
410 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000411
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000412 // Get the opcodes of the two Cast instructions
413 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
414 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000415
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000416 return Instruction::CastOps(
417 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
418 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000419}
420
421/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
422/// in any code being generated. It does not require codegen if V is simple
423/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000424static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
425 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000426 if (V->getType() == Ty || isa<Constant>(V)) return false;
427
Chris Lattner99155be2006-05-25 23:24:33 +0000428 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000430 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 return false;
432 return true;
433}
434
435/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
436/// InsertBefore instruction. This is specialized a bit to avoid inserting
437/// casts that are known to not do anything...
438///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000439Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
440 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000441 Instruction *InsertBefore) {
442 if (V->getType() == DestTy) return V;
443 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445
Reid Spencer13bc5d72006-12-12 09:18:51 +0000446 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447}
448
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000449// SimplifyCommutative - This performs a few simplifications for commutative
450// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000451//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452// 1. Order operands such that they are listed from right (least complex) to
453// left (most complex). This puts constants before unary operators before
454// binary operators.
455//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000456// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
457// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000459bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 bool Changed = false;
461 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
462 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000463
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000464 if (!I.isAssociative()) return Changed;
465 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
467 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
468 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000469 Constant *Folded = ConstantExpr::get(I.getOpcode(),
470 cast<Constant>(I.getOperand(1)),
471 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000472 I.setOperand(0, Op->getOperand(0));
473 I.setOperand(1, Folded);
474 return true;
475 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
476 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
477 isOnlyUse(Op) && isOnlyUse(Op1)) {
478 Constant *C1 = cast<Constant>(Op->getOperand(1));
479 Constant *C2 = cast<Constant>(Op1->getOperand(1));
480
481 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000482 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
484 Op1->getOperand(0),
485 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000486 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487 I.setOperand(0, New);
488 I.setOperand(1, Folded);
489 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000490 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000491 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000492 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000493}
Chris Lattnerca081252001-12-14 16:52:21 +0000494
Reid Spencer266e42b2006-12-23 06:05:41 +0000495/// SimplifyCompare - For a CmpInst this function just orders the operands
496/// so that theyare listed from right (least complex) to left (most complex).
497/// This puts constants before unary operators before binary operators.
498bool InstCombiner::SimplifyCompare(CmpInst &I) {
499 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
500 return false;
501 I.swapOperands();
502 // Compare instructions are not associative so there's nothing else we can do.
503 return true;
504}
505
Chris Lattnerbb74e222003-03-10 23:06:50 +0000506// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
507// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000508//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509static inline Value *dyn_castNegVal(Value *V) {
510 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000511 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000512
Chris Lattner9ad0d552004-12-14 20:08:06 +0000513 // Constants can be considered to be negated values if they can be folded.
514 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
515 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517}
518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519static inline Value *dyn_castNotVal(Value *V) {
520 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000521 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522
523 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000524 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000525 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000526 return 0;
527}
528
Chris Lattner7fb29e12003-03-11 00:12:48 +0000529// dyn_castFoldableMul - If this value is a multiply that can be folded into
530// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000531// non-constant operand of the multiply, and set CST to point to the multiplier.
532// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000533//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000535 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000538 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000541 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000542 // The multiplier is really 1 << CST.
543 Constant *One = ConstantInt::get(V->getType(), 1);
544 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
545 return I->getOperand(0);
546 }
547 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000548 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000549}
Chris Lattner31ae8632002-08-14 17:51:49 +0000550
Chris Lattner0798af32005-01-13 20:14:25 +0000551/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
552/// expression, return it.
553static User *dyn_castGetElementPtr(Value *V) {
554 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556 if (CE->getOpcode() == Instruction::GetElementPtr)
557 return cast<User>(V);
558 return false;
559}
560
Chris Lattner623826c2004-09-28 21:48:02 +0000561// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000562static ConstantInt *AddOne(ConstantInt *C) {
563 return cast<ConstantInt>(ConstantExpr::getAdd(C,
564 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000565}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000566static ConstantInt *SubOne(ConstantInt *C) {
567 return cast<ConstantInt>(ConstantExpr::getSub(C,
568 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000569}
570
Chris Lattner4534dd592006-02-09 07:38:58 +0000571/// ComputeMaskedBits - Determine which of the bits specified in Mask are
572/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000573/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
574/// processing.
575/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
576/// we cannot optimize based on the assumption that it is zero without changing
577/// it to be an explicit zero. If we don't change it to zero, other code could
578/// optimized based on the contradictory assumption that it is non-zero.
579/// Because instcombine aggressively folds operations with undef args anyway,
580/// this won't lose us code quality.
581static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
582 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000583 assert(V && "No Value?");
584 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000585 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaf4341d2007-03-13 02:23:10 +0000586 const IntegerType *VTy = cast<IntegerType>(V->getType());
587 assert(VTy->getBitWidth() == BitWidth &&
588 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000589 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000590 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000591 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
592 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000593 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000594 KnownZero = ~KnownOne & Mask;
595 return;
596 }
597
Reid Spenceraa696402007-03-08 01:46:38 +0000598 if (Depth == 6 || Mask == 0)
599 return; // Limit search depth.
600
601 Instruction *I = dyn_cast<Instruction>(V);
602 if (!I) return;
603
Zhou Shengaf4341d2007-03-13 02:23:10 +0000604 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000605 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000606 Mask &= APInt::getAllOnesValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000607
608 switch (I->getOpcode()) {
609 case Instruction::And:
610 // If either the LHS or the RHS are Zero, the result is zero.
611 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
612 Mask &= ~KnownZero;
613 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
614 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
615 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
616
617 // Output known-1 bits are only known if set in both the LHS & RHS.
618 KnownOne &= KnownOne2;
619 // Output known-0 are known to be clear if zero in either the LHS | RHS.
620 KnownZero |= KnownZero2;
621 return;
622 case Instruction::Or:
623 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
624 Mask &= ~KnownOne;
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
627 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628
629 // Output known-0 bits are only known if clear in both the LHS & RHS.
630 KnownZero &= KnownZero2;
631 // Output known-1 are known to be set if set in either the LHS | RHS.
632 KnownOne |= KnownOne2;
633 return;
634 case Instruction::Xor: {
635 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
639
640 // Output known-0 bits are known if clear or set in both the LHS & RHS.
641 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
642 // Output known-1 are known to be set if set in only one of the LHS, RHS.
643 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
644 KnownZero = KnownZeroOut;
645 return;
646 }
647 case Instruction::Select:
648 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
649 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
650 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
651 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
652
653 // Only known if known in both the LHS and RHS.
654 KnownOne &= KnownOne2;
655 KnownZero &= KnownZero2;
656 return;
657 case Instruction::FPTrunc:
658 case Instruction::FPExt:
659 case Instruction::FPToUI:
660 case Instruction::FPToSI:
661 case Instruction::SIToFP:
662 case Instruction::PtrToInt:
663 case Instruction::UIToFP:
664 case Instruction::IntToPtr:
665 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000666 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000667 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000668 uint32_t SrcBitWidth =
669 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
670 ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth),
671 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
672 KnownZero.trunc(BitWidth);
673 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000674 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000675 }
Reid Spenceraa696402007-03-08 01:46:38 +0000676 case Instruction::BitCast: {
677 const Type *SrcTy = I->getOperand(0)->getType();
678 if (SrcTy->isInteger()) {
679 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
680 return;
681 }
682 break;
683 }
684 case Instruction::ZExt: {
685 // Compute the bits in the result that are not present in the input.
686 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000687 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000688
Zhou Shengaf4341d2007-03-13 02:23:10 +0000689 uint32_t SrcBitWidth = SrcTy->getBitWidth();
690 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
691 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
693 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000694 KnownZero.zext(BitWidth);
695 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000696 KnownZero |= NewBits;
697 return;
698 }
699 case Instruction::SExt: {
700 // Compute the bits in the result that are not present in the input.
701 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000702 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000703
Zhou Shengaf4341d2007-03-13 02:23:10 +0000704 uint32_t SrcBitWidth = SrcTy->getBitWidth();
705 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
706 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000707 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000708 KnownZero.zext(BitWidth);
709 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000710
711 // If the sign bit of the input is known set or clear, then we know the
712 // top bits of the result.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000713 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Zhou Shengaf4341d2007-03-13 02:23:10 +0000714 InSignBit.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000715 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
716 KnownZero |= NewBits;
717 KnownOne &= ~NewBits;
718 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
719 KnownOne |= NewBits;
720 KnownZero &= ~NewBits;
721 } else { // Input sign bit unknown
722 KnownZero &= ~NewBits;
723 KnownOne &= ~NewBits;
724 }
725 return;
726 }
727 case Instruction::Shl:
728 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
729 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
730 uint64_t ShiftAmt = SA->getZExtValue();
731 Mask = APIntOps::lshr(Mask, ShiftAmt);
732 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
733 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000734 KnownZero <<= ShiftAmt;
735 KnownOne <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000736 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
737 return;
738 }
739 break;
740 case Instruction::LShr:
741 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
742 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
743 // Compute the new bits that are at the top now.
744 uint64_t ShiftAmt = SA->getZExtValue();
745 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
746
747 // Unsigned shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000748 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000749 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
750 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
751 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
752 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
753 KnownZero |= HighBits; // high bits known zero.
754 return;
755 }
756 break;
757 case Instruction::AShr:
758 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
759 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
760 // Compute the new bits that are at the top now.
761 uint64_t ShiftAmt = SA->getZExtValue();
762 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
763
764 // Signed shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000765 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000766 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
767 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
768 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
769 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
770
771 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000772 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000773
774 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
775 KnownZero |= HighBits;
776 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
777 KnownOne |= HighBits;
778 }
779 return;
780 }
781 break;
782 }
783}
784
Reid Spencerbb5741f2007-03-08 01:52:58 +0000785/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
786/// this predicate to simplify operations downstream. Mask is known to be zero
787/// for bits that V cannot have.
788static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000789 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000790 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
791 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
792 return (KnownZero & Mask) == Mask;
793}
794
Chris Lattner0157e7f2006-02-11 09:31:47 +0000795/// ShrinkDemandedConstant - Check to see if the specified operand of the
796/// specified instruction is a constant integer. If so, check to see if there
797/// are any bits set in the constant that are not demanded. If so, shrink the
798/// constant and return true.
799static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000800 APInt Demanded) {
801 assert(I && "No instruction?");
802 assert(OpNo < I->getNumOperands() && "Operand index too large");
803
804 // If the operand is not a constant integer, nothing to do.
805 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
806 if (!OpC) return false;
807
808 // If there are no bits set that aren't demanded, nothing to do.
809 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
810 if ((~Demanded & OpC->getValue()) == 0)
811 return false;
812
813 // This instruction is producing bits that are not demanded. Shrink the RHS.
814 Demanded &= OpC->getValue();
815 I->setOperand(OpNo, ConstantInt::get(Demanded));
816 return true;
817}
818
Chris Lattneree0f2802006-02-12 02:07:56 +0000819// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
820// set of known zero and one bits, compute the maximum and minimum values that
821// could have the specified known zero and known one bits, returning them in
822// min/max.
823static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000824 const APInt& KnownZero,
825 const APInt& KnownOne,
826 APInt& Min, APInt& Max) {
827 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
828 assert(KnownZero.getBitWidth() == BitWidth &&
829 KnownOne.getBitWidth() == BitWidth &&
830 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
831 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
832 APInt TypeBits(APInt::getAllOnesValue(BitWidth));
833 APInt UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
Chris Lattneree0f2802006-02-12 02:07:56 +0000834
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000835 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +0000836
837 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
838 // bit if it is unknown.
839 Min = KnownOne;
840 Max = KnownOne|UnknownBits;
841
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000842 if ((SignBit & UnknownBits) != 0) { // Sign bit is unknown
Chris Lattneree0f2802006-02-12 02:07:56 +0000843 Min |= SignBit;
844 Max &= ~SignBit;
845 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000846}
847
848// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
849// a set of known zero and one bits, compute the maximum and minimum values that
850// could have the specified known zero and known one bits, returning them in
851// min/max.
852static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000853 const APInt& KnownZero,
854 const APInt& KnownOne,
855 APInt& Min,
856 APInt& Max) {
857 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
858 assert(KnownZero.getBitWidth() == BitWidth &&
859 KnownOne.getBitWidth() == BitWidth &&
860 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
861 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
862 APInt TypeBits(APInt::getAllOnesValue(BitWidth));
863 APInt UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
Chris Lattneree0f2802006-02-12 02:07:56 +0000864
865 // The minimum value is when the unknown bits are all zeros.
866 Min = KnownOne;
867 // The maximum value is when the unknown bits are all ones.
868 Max = KnownOne|UnknownBits;
869}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000870
Reid Spencer1791f232007-03-12 17:25:59 +0000871/// SimplifyDemandedBits - This function attempts to replace V with a simpler
872/// value based on the demanded bits. When this function is called, it is known
873/// that only the bits set in DemandedMask of the result of V are ever used
874/// downstream. Consequently, depending on the mask and V, it may be possible
875/// to replace V with a constant or one of its operands. In such cases, this
876/// function does the replacement and returns true. In all other cases, it
877/// returns false after analyzing the expression and setting KnownOne and known
878/// to be one in the expression. KnownZero contains all the bits that are known
879/// to be zero in the expression. These are provided to potentially allow the
880/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
881/// the expression. KnownOne and KnownZero always follow the invariant that
882/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
883/// the bits in KnownOne and KnownZero may only be accurate for those bits set
884/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
885/// and KnownOne must all be the same.
886bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
887 APInt& KnownZero, APInt& KnownOne,
888 unsigned Depth) {
889 assert(V != 0 && "Null pointer of Value???");
890 assert(Depth <= 6 && "Limit Search Depth");
891 uint32_t BitWidth = DemandedMask.getBitWidth();
892 const IntegerType *VTy = cast<IntegerType>(V->getType());
893 assert(VTy->getBitWidth() == BitWidth &&
894 KnownZero.getBitWidth() == BitWidth &&
895 KnownOne.getBitWidth() == BitWidth &&
896 "Value *V, DemandedMask, KnownZero and KnownOne \
897 must have same BitWidth");
898 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
899 // We know all of the bits for a constant!
900 KnownOne = CI->getValue() & DemandedMask;
901 KnownZero = ~KnownOne & DemandedMask;
902 return false;
903 }
904
Zhou Shengb9128442007-03-14 03:21:24 +0000905 KnownZero.clear();
906 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000907 if (!V->hasOneUse()) { // Other users may use these bits.
908 if (Depth != 0) { // Not at the root.
909 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
910 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
911 return false;
912 }
913 // If this is the root being simplified, allow it to have multiple uses,
914 // just set the DemandedMask to all bits.
915 DemandedMask = APInt::getAllOnesValue(BitWidth);
916 } else if (DemandedMask == 0) { // Not demanding any bits from V.
917 if (V != UndefValue::get(VTy))
918 return UpdateValueUsesWith(V, UndefValue::get(VTy));
919 return false;
920 } else if (Depth == 6) { // Limit search depth.
921 return false;
922 }
923
924 Instruction *I = dyn_cast<Instruction>(V);
925 if (!I) return false; // Only analyze instructions.
926
927 DemandedMask &= APInt::getAllOnesValue(BitWidth);
928
929 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
930 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
931 switch (I->getOpcode()) {
932 default: break;
933 case Instruction::And:
934 // If either the LHS or the RHS are Zero, the result is zero.
935 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
936 RHSKnownZero, RHSKnownOne, Depth+1))
937 return true;
938 assert((RHSKnownZero & RHSKnownOne) == 0 &&
939 "Bits known to be one AND zero?");
940
941 // If something is known zero on the RHS, the bits aren't demanded on the
942 // LHS.
943 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
944 LHSKnownZero, LHSKnownOne, Depth+1))
945 return true;
946 assert((LHSKnownZero & LHSKnownOne) == 0 &&
947 "Bits known to be one AND zero?");
948
949 // If all of the demanded bits are known 1 on one side, return the other.
950 // These bits cannot contribute to the result of the 'and'.
951 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
952 (DemandedMask & ~LHSKnownZero))
953 return UpdateValueUsesWith(I, I->getOperand(0));
954 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
955 (DemandedMask & ~RHSKnownZero))
956 return UpdateValueUsesWith(I, I->getOperand(1));
957
958 // If all of the demanded bits in the inputs are known zeros, return zero.
959 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
960 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
961
962 // If the RHS is a constant, see if we can simplify it.
963 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
964 return UpdateValueUsesWith(I, I);
965
966 // Output known-1 bits are only known if set in both the LHS & RHS.
967 RHSKnownOne &= LHSKnownOne;
968 // Output known-0 are known to be clear if zero in either the LHS | RHS.
969 RHSKnownZero |= LHSKnownZero;
970 break;
971 case Instruction::Or:
972 // If either the LHS or the RHS are One, the result is One.
973 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
974 RHSKnownZero, RHSKnownOne, Depth+1))
975 return true;
976 assert((RHSKnownZero & RHSKnownOne) == 0 &&
977 "Bits known to be one AND zero?");
978 // If something is known one on the RHS, the bits aren't demanded on the
979 // LHS.
980 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
981 LHSKnownZero, LHSKnownOne, Depth+1))
982 return true;
983 assert((LHSKnownZero & LHSKnownOne) == 0 &&
984 "Bits known to be one AND zero?");
985
986 // If all of the demanded bits are known zero on one side, return the other.
987 // These bits cannot contribute to the result of the 'or'.
988 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
989 (DemandedMask & ~LHSKnownOne))
990 return UpdateValueUsesWith(I, I->getOperand(0));
991 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
992 (DemandedMask & ~RHSKnownOne))
993 return UpdateValueUsesWith(I, I->getOperand(1));
994
995 // If all of the potentially set bits on one side are known to be set on
996 // the other side, just use the 'other' side.
997 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
998 (DemandedMask & (~RHSKnownZero)))
999 return UpdateValueUsesWith(I, I->getOperand(0));
1000 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1001 (DemandedMask & (~LHSKnownZero)))
1002 return UpdateValueUsesWith(I, I->getOperand(1));
1003
1004 // If the RHS is a constant, see if we can simplify it.
1005 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006 return UpdateValueUsesWith(I, I);
1007
1008 // Output known-0 bits are only known if clear in both the LHS & RHS.
1009 RHSKnownZero &= LHSKnownZero;
1010 // Output known-1 are known to be set if set in either the LHS | RHS.
1011 RHSKnownOne |= LHSKnownOne;
1012 break;
1013 case Instruction::Xor: {
1014 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1015 RHSKnownZero, RHSKnownOne, Depth+1))
1016 return true;
1017 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1018 "Bits known to be one AND zero?");
1019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 LHSKnownZero, LHSKnownOne, Depth+1))
1021 return true;
1022 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1023 "Bits known to be one AND zero?");
1024
1025 // If all of the demanded bits are known zero on one side, return the other.
1026 // These bits cannot contribute to the result of the 'xor'.
1027 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1028 return UpdateValueUsesWith(I, I->getOperand(0));
1029 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1030 return UpdateValueUsesWith(I, I->getOperand(1));
1031
1032 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1033 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1034 (RHSKnownOne & LHSKnownOne);
1035 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1036 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1037 (RHSKnownOne & LHSKnownZero);
1038
1039 // If all of the demanded bits are known to be zero on one side or the
1040 // other, turn this into an *inclusive* or.
1041 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1042 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1043 Instruction *Or =
1044 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1045 I->getName());
1046 InsertNewInstBefore(Or, *I);
1047 return UpdateValueUsesWith(I, Or);
1048 }
1049
1050 // If all of the demanded bits on one side are known, and all of the set
1051 // bits on that side are also known to be set on the other side, turn this
1052 // into an AND, as we know the bits will be cleared.
1053 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1054 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1055 // all known
1056 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1057 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1058 Instruction *And =
1059 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1060 InsertNewInstBefore(And, *I);
1061 return UpdateValueUsesWith(I, And);
1062 }
1063 }
1064
1065 // If the RHS is a constant, see if we can simplify it.
1066 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1067 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1068 return UpdateValueUsesWith(I, I);
1069
1070 RHSKnownZero = KnownZeroOut;
1071 RHSKnownOne = KnownOneOut;
1072 break;
1073 }
1074 case Instruction::Select:
1075 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1076 RHSKnownZero, RHSKnownOne, Depth+1))
1077 return true;
1078 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1079 LHSKnownZero, LHSKnownOne, Depth+1))
1080 return true;
1081 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1082 "Bits known to be one AND zero?");
1083 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1084 "Bits known to be one AND zero?");
1085
1086 // If the operands are constants, see if we can simplify them.
1087 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1088 return UpdateValueUsesWith(I, I);
1089 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1090 return UpdateValueUsesWith(I, I);
1091
1092 // Only known if known in both the LHS and RHS.
1093 RHSKnownOne &= LHSKnownOne;
1094 RHSKnownZero &= LHSKnownZero;
1095 break;
1096 case Instruction::Trunc: {
1097 uint32_t truncBf =
1098 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1099 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1100 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1101 return true;
1102 DemandedMask.trunc(BitWidth);
1103 RHSKnownZero.trunc(BitWidth);
1104 RHSKnownOne.trunc(BitWidth);
1105 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1106 "Bits known to be one AND zero?");
1107 break;
1108 }
1109 case Instruction::BitCast:
1110 if (!I->getOperand(0)->getType()->isInteger())
1111 return false;
1112
1113 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1114 RHSKnownZero, RHSKnownOne, Depth+1))
1115 return true;
1116 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1117 "Bits known to be one AND zero?");
1118 break;
1119 case Instruction::ZExt: {
1120 // Compute the bits in the result that are not present in the input.
1121 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1122 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1123
1124 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1125 uint32_t zextBf = SrcTy->getBitWidth();
1126 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1127 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1128 return true;
1129 DemandedMask.zext(BitWidth);
1130 RHSKnownZero.zext(BitWidth);
1131 RHSKnownOne.zext(BitWidth);
1132 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1133 "Bits known to be one AND zero?");
1134 // The top bits are known to be zero.
1135 RHSKnownZero |= NewBits;
1136 break;
1137 }
1138 case Instruction::SExt: {
1139 // Compute the bits in the result that are not present in the input.
1140 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1141 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1142
1143 // Get the sign bit for the source type
1144 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1145 InSignBit.zext(BitWidth);
1146 APInt InputDemandedBits = DemandedMask &
1147 SrcTy->getMask().zext(BitWidth);
1148
1149 // If any of the sign extended bits are demanded, we know that the sign
1150 // bit is demanded.
1151 if ((NewBits & DemandedMask) != 0)
1152 InputDemandedBits |= InSignBit;
1153
1154 uint32_t sextBf = SrcTy->getBitWidth();
1155 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1156 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1157 return true;
1158 InputDemandedBits.zext(BitWidth);
1159 RHSKnownZero.zext(BitWidth);
1160 RHSKnownOne.zext(BitWidth);
1161 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1162 "Bits known to be one AND zero?");
1163
1164 // If the sign bit of the input is known set or clear, then we know the
1165 // top bits of the result.
1166
1167 // If the input sign bit is known zero, or if the NewBits are not demanded
1168 // convert this into a zero extension.
1169 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1170 {
1171 // Convert to ZExt cast
1172 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1173 return UpdateValueUsesWith(I, NewCast);
1174 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1175 RHSKnownOne |= NewBits;
1176 RHSKnownZero &= ~NewBits;
1177 } else { // Input sign bit unknown
1178 RHSKnownZero &= ~NewBits;
1179 RHSKnownOne &= ~NewBits;
1180 }
1181 break;
1182 }
1183 case Instruction::Add: {
1184 // Figure out what the input bits are. If the top bits of the and result
1185 // are not demanded, then the add doesn't demand them from its input
1186 // either.
1187 unsigned NLZ = DemandedMask.countLeadingZeros();
1188
1189 // If there is a constant on the RHS, there are a variety of xformations
1190 // we can do.
1191 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1192 // If null, this should be simplified elsewhere. Some of the xforms here
1193 // won't work if the RHS is zero.
1194 if (RHS->isZero())
1195 break;
1196
1197 // If the top bit of the output is demanded, demand everything from the
1198 // input. Otherwise, we demand all the input bits except NLZ top bits.
1199 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1200
1201 // Find information about known zero/one bits in the input.
1202 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1203 LHSKnownZero, LHSKnownOne, Depth+1))
1204 return true;
1205
1206 // If the RHS of the add has bits set that can't affect the input, reduce
1207 // the constant.
1208 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1209 return UpdateValueUsesWith(I, I);
1210
1211 // Avoid excess work.
1212 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1213 break;
1214
1215 // Turn it into OR if input bits are zero.
1216 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1217 Instruction *Or =
1218 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1219 I->getName());
1220 InsertNewInstBefore(Or, *I);
1221 return UpdateValueUsesWith(I, Or);
1222 }
1223
1224 // We can say something about the output known-zero and known-one bits,
1225 // depending on potential carries from the input constant and the
1226 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1227 // bits set and the RHS constant is 0x01001, then we know we have a known
1228 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1229
1230 // To compute this, we first compute the potential carry bits. These are
1231 // the bits which may be modified. I'm not aware of a better way to do
1232 // this scan.
1233 APInt RHSVal(RHS->getValue());
1234
1235 bool CarryIn = false;
1236 APInt CarryBits(BitWidth, 0);
1237 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1238 *RHSRawVal = RHSVal.getRawData();
1239 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1240 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1241 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1242 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1243 if (AddVal < RHSRawVal[i])
1244 CarryIn = true;
1245 else
1246 CarryIn = false;
1247 CarryBits.setWordToValue(i, WordCarryBits);
1248 }
1249
1250 // Now that we know which bits have carries, compute the known-1/0 sets.
1251
1252 // Bits are known one if they are known zero in one operand and one in the
1253 // other, and there is no input carry.
1254 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1255 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1256
1257 // Bits are known zero if they are known zero in both operands and there
1258 // is no input carry.
1259 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1260 } else {
1261 // If the high-bits of this ADD are not demanded, then it does not demand
1262 // the high bits of its LHS or RHS.
1263 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1264 // Right fill the mask of bits for this ADD to demand the most
1265 // significant bit and all those below it.
1266 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1267 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1268 LHSKnownZero, LHSKnownOne, Depth+1))
1269 return true;
1270 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1271 LHSKnownZero, LHSKnownOne, Depth+1))
1272 return true;
1273 }
1274 }
1275 break;
1276 }
1277 case Instruction::Sub:
1278 // If the high-bits of this SUB are not demanded, then it does not demand
1279 // the high bits of its LHS or RHS.
1280 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1281 // Right fill the mask of bits for this SUB to demand the most
1282 // significant bit and all those below it.
1283 unsigned NLZ = DemandedMask.countLeadingZeros();
1284 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1285 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1286 LHSKnownZero, LHSKnownOne, Depth+1))
1287 return true;
1288 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1289 LHSKnownZero, LHSKnownOne, Depth+1))
1290 return true;
1291 }
1292 break;
1293 case Instruction::Shl:
1294 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1295 uint64_t ShiftAmt = SA->getZExtValue();
1296 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1297 RHSKnownZero, RHSKnownOne, Depth+1))
1298 return true;
1299 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1300 "Bits known to be one AND zero?");
1301 RHSKnownZero <<= ShiftAmt;
1302 RHSKnownOne <<= ShiftAmt;
1303 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001304 if (ShiftAmt)
1305 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001306 }
1307 break;
1308 case Instruction::LShr:
1309 // For a logical shift right
1310 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1311 unsigned ShiftAmt = SA->getZExtValue();
1312
1313 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1314 // Unsigned shift right.
1315 if (SimplifyDemandedBits(I->getOperand(0),
1316 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1317 RHSKnownZero, RHSKnownOne, Depth+1))
1318 return true;
1319 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1320 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001321 RHSKnownZero &= TypeMask;
1322 RHSKnownOne &= TypeMask;
1323 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1324 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001325 if (ShiftAmt) {
1326 // Compute the new bits that are at the top now.
1327 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
1328 BitWidth - ShiftAmt));
1329 RHSKnownZero |= HighBits; // high bits known zero.
1330 }
Reid Spencer1791f232007-03-12 17:25:59 +00001331 }
1332 break;
1333 case Instruction::AShr:
1334 // If this is an arithmetic shift right and only the low-bit is set, we can
1335 // always convert this into a logical shr, even if the shift amount is
1336 // variable. The low bit of the shift cannot be an input sign bit unless
1337 // the shift amount is >= the size of the datatype, which is undefined.
1338 if (DemandedMask == 1) {
1339 // Perform the logical shift right.
1340 Value *NewVal = BinaryOperator::createLShr(
1341 I->getOperand(0), I->getOperand(1), I->getName());
1342 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1343 return UpdateValueUsesWith(I, NewVal);
1344 }
1345
1346 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1347 unsigned ShiftAmt = SA->getZExtValue();
1348
1349 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1350 // Signed shift right.
1351 if (SimplifyDemandedBits(I->getOperand(0),
1352 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1353 RHSKnownZero, RHSKnownOne, Depth+1))
1354 return true;
1355 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1356 "Bits known to be one AND zero?");
1357 // Compute the new bits that are at the top now.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001358 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001359 RHSKnownZero &= TypeMask;
1360 RHSKnownOne &= TypeMask;
1361 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1362 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1363
1364 // Handle the sign bits.
1365 APInt SignBit(APInt::getSignBit(BitWidth));
1366 // Adjust to where it is now in the mask.
1367 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1368
1369 // If the input sign bit is known to be zero, or if none of the top bits
1370 // are demanded, turn this into an unsigned shift right.
1371 if ((RHSKnownZero & SignBit) != 0 ||
1372 (HighBits & ~DemandedMask) == HighBits) {
1373 // Perform the logical shift right.
1374 Value *NewVal = BinaryOperator::createLShr(
1375 I->getOperand(0), SA, I->getName());
1376 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1377 return UpdateValueUsesWith(I, NewVal);
1378 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1379 RHSKnownOne |= HighBits;
1380 }
1381 }
1382 break;
1383 }
1384
1385 // If the client is only demanding bits that we know, return the known
1386 // constant.
1387 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1388 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1389 return false;
1390}
1391
Chris Lattner2deeaea2006-10-05 06:55:50 +00001392
1393/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1394/// 64 or fewer elements. DemandedElts contains the set of elements that are
1395/// actually used by the caller. This method analyzes which elements of the
1396/// operand are undef and returns that information in UndefElts.
1397///
1398/// If the information about demanded elements can be used to simplify the
1399/// operation, the operation is simplified, then the resultant value is
1400/// returned. This returns null if no change was made.
1401Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1402 uint64_t &UndefElts,
1403 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001404 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001405 assert(VWidth <= 64 && "Vector too wide to analyze!");
1406 uint64_t EltMask = ~0ULL >> (64-VWidth);
1407 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1408 "Invalid DemandedElts!");
1409
1410 if (isa<UndefValue>(V)) {
1411 // If the entire vector is undefined, just return this info.
1412 UndefElts = EltMask;
1413 return 0;
1414 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1415 UndefElts = EltMask;
1416 return UndefValue::get(V->getType());
1417 }
1418
1419 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001420 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1421 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001422 Constant *Undef = UndefValue::get(EltTy);
1423
1424 std::vector<Constant*> Elts;
1425 for (unsigned i = 0; i != VWidth; ++i)
1426 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1427 Elts.push_back(Undef);
1428 UndefElts |= (1ULL << i);
1429 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1430 Elts.push_back(Undef);
1431 UndefElts |= (1ULL << i);
1432 } else { // Otherwise, defined.
1433 Elts.push_back(CP->getOperand(i));
1434 }
1435
1436 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001437 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001438 return NewCP != CP ? NewCP : 0;
1439 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001440 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001441 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001442 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001443 Constant *Zero = Constant::getNullValue(EltTy);
1444 Constant *Undef = UndefValue::get(EltTy);
1445 std::vector<Constant*> Elts;
1446 for (unsigned i = 0; i != VWidth; ++i)
1447 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1448 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001449 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001450 }
1451
1452 if (!V->hasOneUse()) { // Other users may use these bits.
1453 if (Depth != 0) { // Not at the root.
1454 // TODO: Just compute the UndefElts information recursively.
1455 return false;
1456 }
1457 return false;
1458 } else if (Depth == 10) { // Limit search depth.
1459 return false;
1460 }
1461
1462 Instruction *I = dyn_cast<Instruction>(V);
1463 if (!I) return false; // Only analyze instructions.
1464
1465 bool MadeChange = false;
1466 uint64_t UndefElts2;
1467 Value *TmpV;
1468 switch (I->getOpcode()) {
1469 default: break;
1470
1471 case Instruction::InsertElement: {
1472 // If this is a variable index, we don't know which element it overwrites.
1473 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001474 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001475 if (Idx == 0) {
1476 // Note that we can't propagate undef elt info, because we don't know
1477 // which elt is getting updated.
1478 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1479 UndefElts2, Depth+1);
1480 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1481 break;
1482 }
1483
1484 // If this is inserting an element that isn't demanded, remove this
1485 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001486 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001487 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1488 return AddSoonDeadInstToWorklist(*I, 0);
1489
1490 // Otherwise, the element inserted overwrites whatever was there, so the
1491 // input demanded set is simpler than the output set.
1492 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1493 DemandedElts & ~(1ULL << IdxNo),
1494 UndefElts, Depth+1);
1495 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496
1497 // The inserted element is defined.
1498 UndefElts |= 1ULL << IdxNo;
1499 break;
1500 }
1501
1502 case Instruction::And:
1503 case Instruction::Or:
1504 case Instruction::Xor:
1505 case Instruction::Add:
1506 case Instruction::Sub:
1507 case Instruction::Mul:
1508 // div/rem demand all inputs, because they don't want divide by zero.
1509 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1510 UndefElts, Depth+1);
1511 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1513 UndefElts2, Depth+1);
1514 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1515
1516 // Output elements are undefined if both are undefined. Consider things
1517 // like undef&0. The result is known zero, not undef.
1518 UndefElts &= UndefElts2;
1519 break;
1520
1521 case Instruction::Call: {
1522 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1523 if (!II) break;
1524 switch (II->getIntrinsicID()) {
1525 default: break;
1526
1527 // Binary vector operations that work column-wise. A dest element is a
1528 // function of the corresponding input elements from the two inputs.
1529 case Intrinsic::x86_sse_sub_ss:
1530 case Intrinsic::x86_sse_mul_ss:
1531 case Intrinsic::x86_sse_min_ss:
1532 case Intrinsic::x86_sse_max_ss:
1533 case Intrinsic::x86_sse2_sub_sd:
1534 case Intrinsic::x86_sse2_mul_sd:
1535 case Intrinsic::x86_sse2_min_sd:
1536 case Intrinsic::x86_sse2_max_sd:
1537 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1538 UndefElts, Depth+1);
1539 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1540 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1541 UndefElts2, Depth+1);
1542 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1543
1544 // If only the low elt is demanded and this is a scalarizable intrinsic,
1545 // scalarize it now.
1546 if (DemandedElts == 1) {
1547 switch (II->getIntrinsicID()) {
1548 default: break;
1549 case Intrinsic::x86_sse_sub_ss:
1550 case Intrinsic::x86_sse_mul_ss:
1551 case Intrinsic::x86_sse2_sub_sd:
1552 case Intrinsic::x86_sse2_mul_sd:
1553 // TODO: Lower MIN/MAX/ABS/etc
1554 Value *LHS = II->getOperand(1);
1555 Value *RHS = II->getOperand(2);
1556 // Extract the element as scalars.
1557 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1558 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1559
1560 switch (II->getIntrinsicID()) {
1561 default: assert(0 && "Case stmts out of sync!");
1562 case Intrinsic::x86_sse_sub_ss:
1563 case Intrinsic::x86_sse2_sub_sd:
1564 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1565 II->getName()), *II);
1566 break;
1567 case Intrinsic::x86_sse_mul_ss:
1568 case Intrinsic::x86_sse2_mul_sd:
1569 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1570 II->getName()), *II);
1571 break;
1572 }
1573
1574 Instruction *New =
1575 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1576 II->getName());
1577 InsertNewInstBefore(New, *II);
1578 AddSoonDeadInstToWorklist(*II, 0);
1579 return New;
1580 }
1581 }
1582
1583 // Output elements are undefined if both are undefined. Consider things
1584 // like undef&0. The result is known zero, not undef.
1585 UndefElts &= UndefElts2;
1586 break;
1587 }
1588 break;
1589 }
1590 }
1591 return MadeChange ? I : 0;
1592}
1593
Reid Spencer266e42b2006-12-23 06:05:41 +00001594/// @returns true if the specified compare instruction is
1595/// true when both operands are equal...
1596/// @brief Determine if the ICmpInst returns true if both operands are equal
1597static bool isTrueWhenEqual(ICmpInst &ICI) {
1598 ICmpInst::Predicate pred = ICI.getPredicate();
1599 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1600 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1601 pred == ICmpInst::ICMP_SLE;
1602}
1603
Chris Lattnerb8b97502003-08-13 19:01:45 +00001604/// AssociativeOpt - Perform an optimization on an associative operator. This
1605/// function is designed to check a chain of associative operators for a
1606/// potential to apply a certain optimization. Since the optimization may be
1607/// applicable if the expression was reassociated, this checks the chain, then
1608/// reassociates the expression as necessary to expose the optimization
1609/// opportunity. This makes use of a special Functor, which must define
1610/// 'shouldApply' and 'apply' methods.
1611///
1612template<typename Functor>
1613Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1614 unsigned Opcode = Root.getOpcode();
1615 Value *LHS = Root.getOperand(0);
1616
1617 // Quick check, see if the immediate LHS matches...
1618 if (F.shouldApply(LHS))
1619 return F.apply(Root);
1620
1621 // Otherwise, if the LHS is not of the same opcode as the root, return.
1622 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001623 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001624 // Should we apply this transform to the RHS?
1625 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1626
1627 // If not to the RHS, check to see if we should apply to the LHS...
1628 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1629 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1630 ShouldApply = true;
1631 }
1632
1633 // If the functor wants to apply the optimization to the RHS of LHSI,
1634 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1635 if (ShouldApply) {
1636 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001637
Chris Lattnerb8b97502003-08-13 19:01:45 +00001638 // Now all of the instructions are in the current basic block, go ahead
1639 // and perform the reassociation.
1640 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1641
1642 // First move the selected RHS to the LHS of the root...
1643 Root.setOperand(0, LHSI->getOperand(1));
1644
1645 // Make what used to be the LHS of the root be the user of the root...
1646 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001647 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001648 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1649 return 0;
1650 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001651 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001652 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001653 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1654 BasicBlock::iterator ARI = &Root; ++ARI;
1655 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1656 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001657
1658 // Now propagate the ExtraOperand down the chain of instructions until we
1659 // get to LHSI.
1660 while (TmpLHSI != LHSI) {
1661 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001662 // Move the instruction to immediately before the chain we are
1663 // constructing to avoid breaking dominance properties.
1664 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1665 BB->getInstList().insert(ARI, NextLHSI);
1666 ARI = NextLHSI;
1667
Chris Lattnerb8b97502003-08-13 19:01:45 +00001668 Value *NextOp = NextLHSI->getOperand(1);
1669 NextLHSI->setOperand(1, ExtraOperand);
1670 TmpLHSI = NextLHSI;
1671 ExtraOperand = NextOp;
1672 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001673
Chris Lattnerb8b97502003-08-13 19:01:45 +00001674 // Now that the instructions are reassociated, have the functor perform
1675 // the transformation...
1676 return F.apply(Root);
1677 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001678
Chris Lattnerb8b97502003-08-13 19:01:45 +00001679 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1680 }
1681 return 0;
1682}
1683
1684
1685// AddRHS - Implements: X + X --> X << 1
1686struct AddRHS {
1687 Value *RHS;
1688 AddRHS(Value *rhs) : RHS(rhs) {}
1689 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1690 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001691 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001692 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001693 }
1694};
1695
1696// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1697// iff C1&C2 == 0
1698struct AddMaskingAnd {
1699 Constant *C2;
1700 AddMaskingAnd(Constant *c) : C2(c) {}
1701 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001702 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001703 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001704 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001705 }
1706 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001707 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001708 }
1709};
1710
Chris Lattner86102b82005-01-01 16:22:27 +00001711static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001712 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001713 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001714 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001715 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001716
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001717 return IC->InsertNewInstBefore(CastInst::create(
1718 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001719 }
1720
Chris Lattner183b3362004-04-09 19:05:30 +00001721 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001722 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1723 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001724
Chris Lattner183b3362004-04-09 19:05:30 +00001725 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1726 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001727 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1728 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001729 }
1730
1731 Value *Op0 = SO, *Op1 = ConstOperand;
1732 if (!ConstIsRHS)
1733 std::swap(Op0, Op1);
1734 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001735 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1736 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001737 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1738 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1739 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001740 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001741 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001742 abort();
1743 }
Chris Lattner86102b82005-01-01 16:22:27 +00001744 return IC->InsertNewInstBefore(New, I);
1745}
1746
1747// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1748// constant as the other operand, try to fold the binary operator into the
1749// select arguments. This also works for Cast instructions, which obviously do
1750// not have a second operand.
1751static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1752 InstCombiner *IC) {
1753 // Don't modify shared select instructions
1754 if (!SI->hasOneUse()) return 0;
1755 Value *TV = SI->getOperand(1);
1756 Value *FV = SI->getOperand(2);
1757
1758 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001759 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001760 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001761
Chris Lattner86102b82005-01-01 16:22:27 +00001762 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1763 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1764
1765 return new SelectInst(SI->getCondition(), SelectTrueVal,
1766 SelectFalseVal);
1767 }
1768 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001769}
1770
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001771
1772/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1773/// node as operand #0, see if we can fold the instruction into the PHI (which
1774/// is only possible if all operands to the PHI are constants).
1775Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1776 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001777 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001778 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001779
Chris Lattner04689872006-09-09 22:02:56 +00001780 // Check to see if all of the operands of the PHI are constants. If there is
1781 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001782 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001783 BasicBlock *NonConstBB = 0;
1784 for (unsigned i = 0; i != NumPHIValues; ++i)
1785 if (!isa<Constant>(PN->getIncomingValue(i))) {
1786 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001787 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001788 NonConstBB = PN->getIncomingBlock(i);
1789
1790 // If the incoming non-constant value is in I's block, we have an infinite
1791 // loop.
1792 if (NonConstBB == I.getParent())
1793 return 0;
1794 }
1795
1796 // If there is exactly one non-constant value, we can insert a copy of the
1797 // operation in that block. However, if this is a critical edge, we would be
1798 // inserting the computation one some other paths (e.g. inside a loop). Only
1799 // do this if the pred block is unconditionally branching into the phi block.
1800 if (NonConstBB) {
1801 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1802 if (!BI || !BI->isUnconditional()) return 0;
1803 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001804
1805 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001806 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001807 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001808 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001809 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001810
1811 // Next, add all of the operands to the PHI.
1812 if (I.getNumOperands() == 2) {
1813 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001814 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001815 Value *InV;
1816 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001817 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1818 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1819 else
1820 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001821 } else {
1822 assert(PN->getIncomingBlock(i) == NonConstBB);
1823 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1824 InV = BinaryOperator::create(BO->getOpcode(),
1825 PN->getIncomingValue(i), C, "phitmp",
1826 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001827 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1828 InV = CmpInst::create(CI->getOpcode(),
1829 CI->getPredicate(),
1830 PN->getIncomingValue(i), C, "phitmp",
1831 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001832 else
1833 assert(0 && "Unknown binop!");
1834
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001835 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001836 }
1837 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001838 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001839 } else {
1840 CastInst *CI = cast<CastInst>(&I);
1841 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001842 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001843 Value *InV;
1844 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001845 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001846 } else {
1847 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001848 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1849 I.getType(), "phitmp",
1850 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001851 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001852 }
1853 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001854 }
1855 }
1856 return ReplaceInstUsesWith(I, NewPN);
1857}
1858
Chris Lattner113f4f42002-06-25 16:13:24 +00001859Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001860 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001861 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001862
Chris Lattnercf4a9962004-04-10 22:01:55 +00001863 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001864 // X + undef -> undef
1865 if (isa<UndefValue>(RHS))
1866 return ReplaceInstUsesWith(I, RHS);
1867
Chris Lattnercf4a9962004-04-10 22:01:55 +00001868 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001869 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001870 if (RHSC->isNullValue())
1871 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001872 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1873 if (CFP->isExactlyValue(-0.0))
1874 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001875 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001876
Chris Lattnercf4a9962004-04-10 22:01:55 +00001877 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001878 // X + (signbit) --> X ^ signbit
Reid Spencer959a21d2007-03-23 21:24:59 +00001879 APInt Val(CI->getValue());
1880 unsigned BitWidth = Val.getBitWidth();
1881 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001882 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001883
1884 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1885 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001886 if (!isa<VectorType>(I.getType())) {
1887 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1888 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1889 KnownZero, KnownOne))
1890 return &I;
1891 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001892 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001893
1894 if (isa<PHINode>(LHS))
1895 if (Instruction *NV = FoldOpIntoPhi(I))
1896 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001897
Chris Lattner330628a2006-01-06 17:59:59 +00001898 ConstantInt *XorRHS = 0;
1899 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001900 if (isa<ConstantInt>(RHSC) &&
1901 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001902 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00001903 APInt RHSVal(cast<ConstantInt>(RHSC)->getValue());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001904
Reid Spencer959a21d2007-03-23 21:24:59 +00001905 unsigned Size = TySizeBits / 2;
1906 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1907 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001908 do {
1909 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001910 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1911 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001912 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1913 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001914 // This is a sign extend if the top bits are known zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00001915 APInt Mask(APInt::getAllOnesValue(TySizeBits));
1916 Mask <<= Size;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001917 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001918 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001919 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001920 }
1921 }
1922 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001923 C0080Val = APIntOps::lshr(C0080Val, Size);
1924 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1925 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001926
Reid Spencer959a21d2007-03-23 21:24:59 +00001927 if (Size) {
1928 const Type *MiddleType = IntegerType::get(Size);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001929 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001930 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001931 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001932 }
1933 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001934 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001935
Chris Lattnerb8b97502003-08-13 19:01:45 +00001936 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001937 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001938 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001939
1940 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1941 if (RHSI->getOpcode() == Instruction::Sub)
1942 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1943 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1944 }
1945 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1946 if (LHSI->getOpcode() == Instruction::Sub)
1947 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1948 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1949 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001950 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001951
Chris Lattner147e9752002-05-08 22:46:53 +00001952 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001953 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001954 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001955
1956 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001957 if (!isa<Constant>(RHS))
1958 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001959 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001960
Misha Brukmanb1c93172005-04-21 23:48:37 +00001961
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001962 ConstantInt *C2;
1963 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1964 if (X == RHS) // X*C + X --> X * (C+1)
1965 return BinaryOperator::createMul(RHS, AddOne(C2));
1966
1967 // X*C1 + X*C2 --> X * (C1+C2)
1968 ConstantInt *C1;
1969 if (X == dyn_castFoldableMul(RHS, C1))
1970 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001971 }
1972
1973 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001974 if (dyn_castFoldableMul(RHS, C2) == LHS)
1975 return BinaryOperator::createMul(LHS, AddOne(C2));
1976
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001977 // X + ~X --> -1 since ~X = -X-1
1978 if (dyn_castNotVal(LHS) == RHS ||
1979 dyn_castNotVal(RHS) == LHS)
1980 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1981
Chris Lattner57c8d992003-02-18 19:57:07 +00001982
Chris Lattnerb8b97502003-08-13 19:01:45 +00001983 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001984 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001985 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1986 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001987
Chris Lattnerb9cde762003-10-02 15:11:26 +00001988 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001989 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001990 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1991 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1992 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001993 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001994
Chris Lattnerbff91d92004-10-08 05:07:56 +00001995 // (X & FF00) + xx00 -> (X+xx00) & FF00
1996 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1997 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1998 if (Anded == CRHS) {
1999 // See if all bits from the first bit set in the Add RHS up are included
2000 // in the mask. First, get the rightmost bit.
Reid Spencer959a21d2007-03-23 21:24:59 +00002001 APInt AddRHSV(CRHS->getValue());
Chris Lattnerbff91d92004-10-08 05:07:56 +00002002
2003 // Form a mask of all bits from the lowest bit added through the top.
Reid Spencer959a21d2007-03-23 21:24:59 +00002004 APInt AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2005 AddRHSHighBits &= C2->getType()->getMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002006
2007 // See if the and mask includes all of these bits.
Reid Spencer959a21d2007-03-23 21:24:59 +00002008 APInt AddRHSHighBitsAnd = AddRHSHighBits & C2->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002009
Chris Lattnerbff91d92004-10-08 05:07:56 +00002010 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2011 // Okay, the xform is safe. Insert the new add pronto.
2012 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2013 LHS->getName()), I);
2014 return BinaryOperator::createAnd(NewAdd, C2);
2015 }
2016 }
2017 }
2018
Chris Lattnerd4252a72004-07-30 07:50:03 +00002019 // Try to fold constant add into select arguments.
2020 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002021 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002022 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002023 }
2024
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002025 // add (cast *A to intptrtype) B ->
2026 // cast (GEP (cast *A to sbyte*) B) ->
2027 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002028 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002029 CastInst *CI = dyn_cast<CastInst>(LHS);
2030 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002031 if (!CI) {
2032 CI = dyn_cast<CastInst>(RHS);
2033 Other = LHS;
2034 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002035 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002036 (CI->getType()->getPrimitiveSizeInBits() ==
2037 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002038 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002039 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002040 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002041 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002042 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002043 }
2044 }
2045
Chris Lattner113f4f42002-06-25 16:13:24 +00002046 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002047}
2048
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002049// isSignBit - Return true if the value represented by the constant only has the
2050// highest order bit set.
2051static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002052 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002053 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002054}
2055
Chris Lattner113f4f42002-06-25 16:13:24 +00002056Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002058
Chris Lattnere6794492002-08-12 21:17:25 +00002059 if (Op0 == Op1) // sub X, X -> 0
2060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002061
Chris Lattnere6794492002-08-12 21:17:25 +00002062 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002063 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002064 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002065
Chris Lattner81a7a232004-10-16 18:11:37 +00002066 if (isa<UndefValue>(Op0))
2067 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2068 if (isa<UndefValue>(Op1))
2069 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2070
Chris Lattner8f2f5982003-11-05 01:06:05 +00002071 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2072 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002073 if (C->isAllOnesValue())
2074 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002075
Chris Lattner8f2f5982003-11-05 01:06:05 +00002076 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002077 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002078 if (match(Op1, m_Not(m_Value(X))))
2079 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002080 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00002081 // -(X >>u 31) -> (X >>s 31)
2082 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002083 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002084 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002085 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002086 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002087 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002088 if (CU->getZExtValue() ==
2089 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002090 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002091 return BinaryOperator::create(Instruction::AShr,
2092 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002093 }
2094 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002095 }
2096 else if (SI->getOpcode() == Instruction::AShr) {
2097 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2098 // Check to see if we are shifting out everything but the sign bit.
2099 if (CU->getZExtValue() ==
2100 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002101 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002102 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002103 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002104 }
2105 }
2106 }
Chris Lattner022167f2004-03-13 00:11:49 +00002107 }
Chris Lattner183b3362004-04-09 19:05:30 +00002108
2109 // Try to fold constant sub into select arguments.
2110 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002111 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002112 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002113
2114 if (isa<PHINode>(Op0))
2115 if (Instruction *NV = FoldOpIntoPhi(I))
2116 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002117 }
2118
Chris Lattnera9be4492005-04-07 16:15:25 +00002119 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2120 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002121 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002122 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002123 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002124 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002125 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002126 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2127 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2128 // C1-(X+C2) --> (C1-C2)-X
2129 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2130 Op1I->getOperand(0));
2131 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002132 }
2133
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002134 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002135 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2136 // is not used by anyone else...
2137 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002138 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002139 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002140 // Swap the two operands of the subexpr...
2141 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2142 Op1I->setOperand(0, IIOp1);
2143 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002144
Chris Lattner3082c5a2003-02-18 19:28:33 +00002145 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002146 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002147 }
2148
2149 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2150 //
2151 if (Op1I->getOpcode() == Instruction::And &&
2152 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2153 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2154
Chris Lattner396dbfe2004-06-09 05:08:07 +00002155 Value *NewNot =
2156 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002157 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002158 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002159
Reid Spencer3c514952006-10-16 23:08:08 +00002160 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002161 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002162 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002163 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002164 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002165 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002166 ConstantExpr::getNeg(DivRHS));
2167
Chris Lattner57c8d992003-02-18 19:57:07 +00002168 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002169 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002170 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002171 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002172 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002173 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002174 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002175 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002176 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002177
Chris Lattner7a002fe2006-12-02 00:13:08 +00002178 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002179 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2180 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002181 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2182 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2183 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2184 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002185 } else if (Op0I->getOpcode() == Instruction::Sub) {
2186 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2187 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002188 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002189
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002190 ConstantInt *C1;
2191 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2192 if (X == Op1) { // X*C - X --> X * (C-1)
2193 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2194 return BinaryOperator::createMul(Op1, CP1);
2195 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002196
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002197 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2198 if (X == dyn_castFoldableMul(Op1, C2))
2199 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2200 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002201 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002202}
2203
Reid Spencer266e42b2006-12-23 06:05:41 +00002204/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002205/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002206static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2207 switch (pred) {
2208 case ICmpInst::ICMP_SLT:
2209 // True if LHS s< RHS and RHS == 0
2210 return RHS->isNullValue();
2211 case ICmpInst::ICMP_SLE:
2212 // True if LHS s<= RHS and RHS == -1
2213 return RHS->isAllOnesValue();
2214 case ICmpInst::ICMP_UGE:
2215 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2216 return RHS->getZExtValue() == (1ULL <<
2217 (RHS->getType()->getPrimitiveSizeInBits()-1));
2218 case ICmpInst::ICMP_UGT:
2219 // True if LHS u> RHS and RHS == high-bit-mask - 1
2220 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002221 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002222 default:
2223 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002224 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002225}
2226
Chris Lattner113f4f42002-06-25 16:13:24 +00002227Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002228 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002229 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002230
Chris Lattner81a7a232004-10-16 18:11:37 +00002231 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2233
Chris Lattnere6794492002-08-12 21:17:25 +00002234 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002235 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2236 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002237
2238 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002239 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002240 if (SI->getOpcode() == Instruction::Shl)
2241 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002242 return BinaryOperator::createMul(SI->getOperand(0),
2243 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002244
Chris Lattnercce81be2003-09-11 22:24:54 +00002245 if (CI->isNullValue())
2246 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2247 if (CI->equalsInt(1)) // X * 1 == X
2248 return ReplaceInstUsesWith(I, Op0);
2249 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002250 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002251
Reid Spencer6d392062007-03-23 20:05:17 +00002252 APInt Val(cast<ConstantInt>(CI)->getValue());
2253 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002254 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002255 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002256 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002257 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002258 if (Op1F->isNullValue())
2259 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002260
Chris Lattner3082c5a2003-02-18 19:28:33 +00002261 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2262 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2263 if (Op1F->getValue() == 1.0)
2264 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2265 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002266
2267 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2268 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2269 isa<ConstantInt>(Op0I->getOperand(1))) {
2270 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2271 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2272 Op1, "tmp");
2273 InsertNewInstBefore(Add, I);
2274 Value *C1C2 = ConstantExpr::getMul(Op1,
2275 cast<Constant>(Op0I->getOperand(1)));
2276 return BinaryOperator::createAdd(Add, C1C2);
2277
2278 }
Chris Lattner183b3362004-04-09 19:05:30 +00002279
2280 // Try to fold constant mul into select arguments.
2281 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002282 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002283 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002284
2285 if (isa<PHINode>(Op0))
2286 if (Instruction *NV = FoldOpIntoPhi(I))
2287 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002288 }
2289
Chris Lattner934a64cf2003-03-10 23:23:04 +00002290 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2291 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002292 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002293
Chris Lattner2635b522004-02-23 05:39:21 +00002294 // If one of the operands of the multiply is a cast from a boolean value, then
2295 // we know the bool is either zero or one, so this is a 'masking' multiply.
2296 // See if we can simplify things based on how the boolean was originally
2297 // formed.
2298 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002299 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002300 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002301 BoolCast = CI;
2302 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002303 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002304 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002305 BoolCast = CI;
2306 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002307 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002308 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2309 const Type *SCOpTy = SCIOp0->getType();
2310
Reid Spencer266e42b2006-12-23 06:05:41 +00002311 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002312 // multiply into a shift/and combination.
2313 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002314 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002315 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002316 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002317 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002318 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002319 InsertNewInstBefore(
2320 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002321 BoolCast->getOperand(0)->getName()+
2322 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002323
2324 // If the multiply type is not the same as the source type, sign extend
2325 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002326 if (I.getType() != V->getType()) {
2327 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2328 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2329 Instruction::CastOps opcode =
2330 (SrcBits == DstBits ? Instruction::BitCast :
2331 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2332 V = InsertCastBefore(opcode, V, I.getType(), I);
2333 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002334
Chris Lattner2635b522004-02-23 05:39:21 +00002335 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002336 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002337 }
2338 }
2339 }
2340
Chris Lattner113f4f42002-06-25 16:13:24 +00002341 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002342}
2343
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002344/// This function implements the transforms on div instructions that work
2345/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2346/// used by the visitors to those instructions.
2347/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002348Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002350
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002351 // undef / X -> 0
2352 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002354
2355 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002356 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002357 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002358
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002359 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002360 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2361 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002362 // same basic block, then we replace the select with Y, and the condition
2363 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002364 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002365 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002366 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2367 if (ST->isNullValue()) {
2368 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2369 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002370 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002371 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2372 I.setOperand(1, SI->getOperand(2));
2373 else
2374 UpdateValueUsesWith(SI, SI->getOperand(2));
2375 return &I;
2376 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377
Chris Lattnerd79dc792006-09-09 20:26:32 +00002378 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2379 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2380 if (ST->isNullValue()) {
2381 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2382 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002383 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002384 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2385 I.setOperand(1, SI->getOperand(1));
2386 else
2387 UpdateValueUsesWith(SI, SI->getOperand(1));
2388 return &I;
2389 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002390 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002391
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002392 return 0;
2393}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002394
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002395/// This function implements the transforms common to both integer division
2396/// instructions (udiv and sdiv). It is called by the visitors to those integer
2397/// division instructions.
2398/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002399Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2401
2402 if (Instruction *Common = commonDivTransforms(I))
2403 return Common;
2404
2405 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2406 // div X, 1 == X
2407 if (RHS->equalsInt(1))
2408 return ReplaceInstUsesWith(I, Op0);
2409
2410 // (X / C1) / C2 -> X / (C1*C2)
2411 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2412 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2413 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2414 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2415 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002416 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002417
Reid Spencer6d392062007-03-23 20:05:17 +00002418 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002419 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2420 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2421 return R;
2422 if (isa<PHINode>(Op0))
2423 if (Instruction *NV = FoldOpIntoPhi(I))
2424 return NV;
2425 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002426 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002427
Chris Lattner3082c5a2003-02-18 19:28:33 +00002428 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002429 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002430 if (LHS->equalsInt(0))
2431 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2432
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002433 return 0;
2434}
2435
2436Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2438
2439 // Handle the integer div common cases
2440 if (Instruction *Common = commonIDivTransforms(I))
2441 return Common;
2442
2443 // X udiv C^2 -> X >> C
2444 // Check to see if this is an unsigned division with an exact power of 2,
2445 // if so, convert to a right shift.
2446 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6d392062007-03-23 20:05:17 +00002447 APInt Val(C->getValue());
2448 if (Val != 0 && Val.isPowerOf2()) // Don't break X / 0
2449 return BinaryOperator::createLShr(Op0,
2450 ConstantInt::get(Op0->getType(), Val.logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002451 }
2452
2453 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002454 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002455 if (RHSI->getOpcode() == Instruction::Shl &&
2456 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002457 APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2458 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002459 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002460 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002461 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002462 Constant *C2V = ConstantInt::get(NTy, C2);
2463 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002464 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002465 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002466 }
2467 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002468 }
2469
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002470 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2471 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002472 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002473 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002474 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002475 APInt TVA(STO->getValue()), FVA(SFO->getValue());
2476 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002477 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002478 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002479 // Construct the "on true" case of the select
2480 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2481 Instruction *TSI = BinaryOperator::createLShr(
2482 Op0, TC, SI->getName()+".t");
2483 TSI = InsertNewInstBefore(TSI, I);
2484
2485 // Construct the "on false" case of the select
2486 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2487 Instruction *FSI = BinaryOperator::createLShr(
2488 Op0, FC, SI->getName()+".f");
2489 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002490
Reid Spencer3939b1a2007-03-05 23:36:13 +00002491 // construct the select instruction and return it.
2492 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002493 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002494 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002495 return 0;
2496}
2497
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002498Instruction *InstCombiner::visitSDiv(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 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2506 // sdiv X, -1 == -X
2507 if (RHS->isAllOnesValue())
2508 return BinaryOperator::createNeg(Op0);
2509
2510 // -X/C -> X/-C
2511 if (Value *LHSNeg = dyn_castNegVal(Op0))
2512 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2513 }
2514
2515 // If the sign bits of both operands are zero (i.e. we can prove they are
2516 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002517 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002518 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002519 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2520 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2521 }
2522 }
2523
2524 return 0;
2525}
2526
2527Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2528 return commonDivTransforms(I);
2529}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002530
Chris Lattner85dda9a2006-03-02 06:50:58 +00002531/// GetFactor - If we can prove that the specified value is at least a multiple
2532/// of some factor, return that factor.
2533static Constant *GetFactor(Value *V) {
2534 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2535 return CI;
2536
2537 // Unless we can be tricky, we know this is a multiple of 1.
2538 Constant *Result = ConstantInt::get(V->getType(), 1);
2539
2540 Instruction *I = dyn_cast<Instruction>(V);
2541 if (!I) return Result;
2542
2543 if (I->getOpcode() == Instruction::Mul) {
2544 // Handle multiplies by a constant, etc.
2545 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2546 GetFactor(I->getOperand(1)));
2547 } else if (I->getOpcode() == Instruction::Shl) {
2548 // (X<<C) -> X * (1 << C)
2549 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2550 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2551 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2552 }
2553 } else if (I->getOpcode() == Instruction::And) {
2554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2555 // X & 0xFFF0 is known to be a multiple of 16.
2556 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2557 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2558 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002559 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002560 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002561 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002562 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002563 if (!CI->isIntegerCast())
2564 return Result;
2565 Value *Op = CI->getOperand(0);
2566 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002567 }
2568 return Result;
2569}
2570
Reid Spencer7eb55b32006-11-02 01:53:59 +00002571/// This function implements the transforms on rem instructions that work
2572/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2573/// is used by the visitors to those instructions.
2574/// @brief Transforms common to all three rem instructions
2575Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002577
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002578 // 0 % X == 0, we don't need to preserve faults!
2579 if (Constant *LHS = dyn_cast<Constant>(Op0))
2580 if (LHS->isNullValue())
2581 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2582
2583 if (isa<UndefValue>(Op0)) // undef % X -> 0
2584 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2585 if (isa<UndefValue>(Op1))
2586 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002587
2588 // Handle cases involving: rem X, (select Cond, Y, Z)
2589 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2590 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2591 // the same basic block, then we replace the select with Y, and the
2592 // condition of the select with false (if the cond value is in the same
2593 // BB). If the select has uses other than the div, this allows them to be
2594 // simplified also.
2595 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2596 if (ST->isNullValue()) {
2597 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2598 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002599 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002600 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2601 I.setOperand(1, SI->getOperand(2));
2602 else
2603 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002604 return &I;
2605 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002606 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2607 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2608 if (ST->isNullValue()) {
2609 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2610 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002611 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002612 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2613 I.setOperand(1, SI->getOperand(1));
2614 else
2615 UpdateValueUsesWith(SI, SI->getOperand(1));
2616 return &I;
2617 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002618 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002619
Reid Spencer7eb55b32006-11-02 01:53:59 +00002620 return 0;
2621}
2622
2623/// This function implements the transforms common to both integer remainder
2624/// instructions (urem and srem). It is called by the visitors to those integer
2625/// remainder instructions.
2626/// @brief Common integer remainder transforms
2627Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2628 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2629
2630 if (Instruction *common = commonRemTransforms(I))
2631 return common;
2632
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002633 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002634 // X % 0 == undef, we don't need to preserve faults!
2635 if (RHS->equalsInt(0))
2636 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2637
Chris Lattner3082c5a2003-02-18 19:28:33 +00002638 if (RHS->equalsInt(1)) // X % 1 == 0
2639 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2640
Chris Lattnerb70f1412006-02-28 05:49:21 +00002641 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2642 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2643 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2644 return R;
2645 } else if (isa<PHINode>(Op0I)) {
2646 if (Instruction *NV = FoldOpIntoPhi(I))
2647 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002648 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002649 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2650 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002651 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002652 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002653 }
2654
Reid Spencer7eb55b32006-11-02 01:53:59 +00002655 return 0;
2656}
2657
2658Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2660
2661 if (Instruction *common = commonIRemTransforms(I))
2662 return common;
2663
2664 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2665 // X urem C^2 -> X and C
2666 // Check to see if this is an unsigned remainder with an exact power of 2,
2667 // if so, convert to a bitwise and.
2668 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002669 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002670 return BinaryOperator::createAnd(Op0, SubOne(C));
2671 }
2672
Chris Lattner2e90b732006-02-05 07:54:04 +00002673 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002674 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2675 if (RHSI->getOpcode() == Instruction::Shl &&
2676 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002677 APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2678 if (C1.isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002679 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2680 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2681 "tmp"), I);
2682 return BinaryOperator::createAnd(Op0, Add);
2683 }
2684 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002685 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002686
Reid Spencer7eb55b32006-11-02 01:53:59 +00002687 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2688 // where C1&C2 are powers of two.
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2690 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2691 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2692 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002693 if ((STO->getValue().isPowerOf2()) &&
2694 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002695 Value *TrueAnd = InsertNewInstBefore(
2696 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2697 Value *FalseAnd = InsertNewInstBefore(
2698 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2699 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2700 }
2701 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002702 }
2703
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002704 return 0;
2705}
2706
Reid Spencer7eb55b32006-11-02 01:53:59 +00002707Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2708 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2709
2710 if (Instruction *common = commonIRemTransforms(I))
2711 return common;
2712
2713 if (Value *RHSNeg = dyn_castNegVal(Op1))
2714 if (!isa<ConstantInt>(RHSNeg) ||
Reid Spencer6d392062007-03-23 20:05:17 +00002715 cast<ConstantInt>(RHSNeg)->getValue().isPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002716 // X % -Y -> X % Y
2717 AddUsesToWorkList(I);
2718 I.setOperand(1, RHSNeg);
2719 return &I;
2720 }
2721
2722 // If the top bits of both operands are zero (i.e. we can prove they are
2723 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002724 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002725 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2726 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2727 return BinaryOperator::createURem(Op0, Op1, I.getName());
2728 }
2729
2730 return 0;
2731}
2732
2733Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002734 return commonRemTransforms(I);
2735}
2736
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002737// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002738static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002739 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002740 if (isSigned) {
2741 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002742 APInt Val(APInt::getSignedMaxValue(TypeBits));
2743 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002744 }
Reid Spenceref599b02007-03-19 21:10:28 +00002745 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002746}
2747
2748// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002749static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2750 if (isSigned) {
2751 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002752 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2753 APInt Val(APInt::getSignedMinValue(TypeBits));
2754 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002755 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002756 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002757}
2758
Chris Lattner35167c32004-06-09 07:59:58 +00002759// isOneBitSet - Return true if there is exactly one bit set in the specified
2760// constant.
2761static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002762 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002763}
2764
Chris Lattner8fc5af42004-09-23 21:46:38 +00002765// isHighOnes - Return true if the constant is of the form 1+0+.
2766// This is the same as lowones(~X).
2767static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002768 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002769}
2770
Reid Spencer266e42b2006-12-23 06:05:41 +00002771/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002772/// are carefully arranged to allow folding of expressions such as:
2773///
2774/// (A < B) | (A > B) --> (A != B)
2775///
Reid Spencer266e42b2006-12-23 06:05:41 +00002776/// Note that this is only valid if the first and second predicates have the
2777/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002778///
Reid Spencer266e42b2006-12-23 06:05:41 +00002779/// Three bits are used to represent the condition, as follows:
2780/// 0 A > B
2781/// 1 A == B
2782/// 2 A < B
2783///
2784/// <=> Value Definition
2785/// 000 0 Always false
2786/// 001 1 A > B
2787/// 010 2 A == B
2788/// 011 3 A >= B
2789/// 100 4 A < B
2790/// 101 5 A != B
2791/// 110 6 A <= B
2792/// 111 7 Always true
2793///
2794static unsigned getICmpCode(const ICmpInst *ICI) {
2795 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002796 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002797 case ICmpInst::ICMP_UGT: return 1; // 001
2798 case ICmpInst::ICMP_SGT: return 1; // 001
2799 case ICmpInst::ICMP_EQ: return 2; // 010
2800 case ICmpInst::ICMP_UGE: return 3; // 011
2801 case ICmpInst::ICMP_SGE: return 3; // 011
2802 case ICmpInst::ICMP_ULT: return 4; // 100
2803 case ICmpInst::ICMP_SLT: return 4; // 100
2804 case ICmpInst::ICMP_NE: return 5; // 101
2805 case ICmpInst::ICMP_ULE: return 6; // 110
2806 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002807 // True -> 7
2808 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002809 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002810 return 0;
2811 }
2812}
2813
Reid Spencer266e42b2006-12-23 06:05:41 +00002814/// getICmpValue - This is the complement of getICmpCode, which turns an
2815/// opcode and two operands into either a constant true or false, or a brand
2816/// new /// ICmp instruction. The sign is passed in to determine which kind
2817/// of predicate to use in new icmp instructions.
2818static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2819 switch (code) {
2820 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002821 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002822 case 1:
2823 if (sign)
2824 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2825 else
2826 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2827 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2828 case 3:
2829 if (sign)
2830 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2831 else
2832 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2833 case 4:
2834 if (sign)
2835 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2836 else
2837 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2838 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2839 case 6:
2840 if (sign)
2841 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2842 else
2843 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002844 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002845 }
2846}
2847
Reid Spencer266e42b2006-12-23 06:05:41 +00002848static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2849 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2850 (ICmpInst::isSignedPredicate(p1) &&
2851 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2852 (ICmpInst::isSignedPredicate(p2) &&
2853 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2854}
2855
2856namespace {
2857// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2858struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002859 InstCombiner &IC;
2860 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002861 ICmpInst::Predicate pred;
2862 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2863 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2864 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002865 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002866 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2867 if (PredicatesFoldable(pred, ICI->getPredicate()))
2868 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2869 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002870 return false;
2871 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002872 Instruction *apply(Instruction &Log) const {
2873 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2874 if (ICI->getOperand(0) != LHS) {
2875 assert(ICI->getOperand(1) == LHS);
2876 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002877 }
2878
Chris Lattnerd1bce952007-03-13 14:27:42 +00002879 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002880 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002881 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002882 unsigned Code;
2883 switch (Log.getOpcode()) {
2884 case Instruction::And: Code = LHSCode & RHSCode; break;
2885 case Instruction::Or: Code = LHSCode | RHSCode; break;
2886 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002887 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002888 }
2889
Chris Lattnerd1bce952007-03-13 14:27:42 +00002890 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2891 ICmpInst::isSignedPredicate(ICI->getPredicate());
2892
2893 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002894 if (Instruction *I = dyn_cast<Instruction>(RV))
2895 return I;
2896 // Otherwise, it's a constant boolean value...
2897 return IC.ReplaceInstUsesWith(Log, RV);
2898 }
2899};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002900} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002901
Chris Lattnerba1cb382003-09-19 17:17:26 +00002902// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2903// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002904// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002905Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002906 ConstantInt *OpRHS,
2907 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002908 BinaryOperator &TheAnd) {
2909 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002910 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002911 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002912 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002913
Chris Lattnerba1cb382003-09-19 17:17:26 +00002914 switch (Op->getOpcode()) {
2915 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002916 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002917 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002918 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002919 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002920 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002921 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002922 }
2923 break;
2924 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002925 if (Together == AndRHS) // (X | C) & C --> C
2926 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002927
Chris Lattner86102b82005-01-01 16:22:27 +00002928 if (Op->hasOneUse() && Together != OpRHS) {
2929 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002930 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002931 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002932 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002933 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002934 }
2935 break;
2936 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002937 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002938 // Adding a one to a single bit bit-field should be turned into an XOR
2939 // of the bit. First thing to check is to see if this AND is with a
2940 // single bit constant.
Reid Spencer6274c722007-03-23 18:46:34 +00002941 APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
Chris Lattnerba1cb382003-09-19 17:17:26 +00002942
2943 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002944 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002945 // Ok, at this point, we know that we are masking the result of the
2946 // ADD down to exactly one bit. If the constant we are adding has
2947 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencer6274c722007-03-23 18:46:34 +00002948 APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002949
Chris Lattnerba1cb382003-09-19 17:17:26 +00002950 // Check to see if any bits below the one bit set in AndRHSV are set.
2951 if ((AddRHS & (AndRHSV-1)) == 0) {
2952 // If not, the only thing that can effect the output of the AND is
2953 // the bit specified by AndRHSV. If that bit is set, the effect of
2954 // the XOR is to toggle the bit. If it is clear, then the ADD has
2955 // no effect.
2956 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2957 TheAnd.setOperand(0, X);
2958 return &TheAnd;
2959 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002960 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002961 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002962 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002963 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002964 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002965 }
2966 }
2967 }
2968 }
2969 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002970
2971 case Instruction::Shl: {
2972 // We know that the AND will not produce any of the bits shifted in, so if
2973 // the anded constant includes them, clear them now!
2974 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002975 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002976 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2977 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002978
Chris Lattner7e794272004-09-24 15:21:34 +00002979 if (CI == ShlMask) { // Masking out bits that the shift already masks
2980 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2981 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002982 TheAnd.setOperand(1, CI);
2983 return &TheAnd;
2984 }
2985 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002986 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002987 case Instruction::LShr:
2988 {
Chris Lattner2da29172003-09-19 19:05:02 +00002989 // We know that the AND will not produce any of the bits shifted in, so if
2990 // the anded constant includes them, clear them now! This only applies to
2991 // unsigned shifts, because a signed shr may bring in set bits!
2992 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002993 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002994 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2995 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002996
Reid Spencerfdff9382006-11-08 06:47:33 +00002997 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2998 return ReplaceInstUsesWith(TheAnd, Op);
2999 } else if (CI != AndRHS) {
3000 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3001 return &TheAnd;
3002 }
3003 break;
3004 }
3005 case Instruction::AShr:
3006 // Signed shr.
3007 // See if this is shifting in some sign extension, then masking it out
3008 // with an and.
3009 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003010 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003011 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003012 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3013 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003014 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003015 // Make the argument unsigned.
3016 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003017 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003018 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003019 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003020 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003021 }
Chris Lattner2da29172003-09-19 19:05:02 +00003022 }
3023 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003024 }
3025 return 0;
3026}
3027
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003028
Chris Lattner6862fbd2004-09-29 17:40:11 +00003029/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3030/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003031/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3032/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003033/// insert new instructions.
3034Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003035 bool isSigned, bool Inside,
3036 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003037 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003038 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003039 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003040
Chris Lattner6862fbd2004-09-29 17:40:11 +00003041 if (Inside) {
3042 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003043 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003044
Reid Spencer266e42b2006-12-23 06:05:41 +00003045 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003046 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003047 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003048 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3049 return new ICmpInst(pred, V, Hi);
3050 }
3051
3052 // Emit V-Lo <u Hi-Lo
3053 Constant *NegLo = ConstantExpr::getNeg(Lo);
3054 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003055 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003056 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3057 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003058 }
3059
3060 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003061 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003062
Reid Spencerf4071162007-03-21 23:19:50 +00003063 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003064 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003065 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003066 ICmpInst::Predicate pred = (isSigned ?
3067 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3068 return new ICmpInst(pred, V, Hi);
3069 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003070
Reid Spencerf4071162007-03-21 23:19:50 +00003071 // Emit V-Lo >u Hi-1-Lo
3072 // Note that Hi has already had one subtracted from it, above.
3073 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003074 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003075 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003076 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3077 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003078}
3079
Chris Lattnerb4b25302005-09-18 07:22:02 +00003080// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3081// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3082// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3083// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003084static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003085 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003086 if (!isShiftedMask_64(V)) return false;
3087
3088 // look for the first zero bit after the run of ones
3089 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3090 // look for the first non-zero bit
3091 ME = 64-CountLeadingZeros_64(V);
3092 return true;
3093}
3094
3095
3096
3097/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3098/// where isSub determines whether the operator is a sub. If we can fold one of
3099/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003100///
3101/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3102/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3103/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3104///
3105/// return (A +/- B).
3106///
3107Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003108 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003109 Instruction &I) {
3110 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3111 if (!LHSI || LHSI->getNumOperands() != 2 ||
3112 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3113
3114 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3115
3116 switch (LHSI->getOpcode()) {
3117 default: return 0;
3118 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003119 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3120 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencer6274c722007-03-23 18:46:34 +00003121 if ((Mask->getValue() & Mask->getValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003122 break;
3123
3124 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3125 // part, we don't need any explicit masks to take them out of A. If that
3126 // is all N is, ignore it.
3127 unsigned MB, ME;
3128 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003129 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3130 APInt Mask(APInt::getAllOnesValue(BitWidth));
3131 Mask = APIntOps::lshr(Mask, BitWidth-MB+1);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003132 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003133 break;
3134 }
3135 }
Chris Lattneraf517572005-09-18 04:24:45 +00003136 return 0;
3137 case Instruction::Or:
3138 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003139 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencer6274c722007-03-23 18:46:34 +00003140 if ((Mask->getValue() & Mask->getValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003141 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003142 break;
3143 return 0;
3144 }
3145
3146 Instruction *New;
3147 if (isSub)
3148 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3149 else
3150 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3151 return InsertNewInstBefore(New, I);
3152}
3153
Chris Lattner113f4f42002-06-25 16:13:24 +00003154Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003155 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003157
Chris Lattner81a7a232004-10-16 18:11:37 +00003158 if (isa<UndefValue>(Op1)) // X & undef -> 0
3159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3160
Chris Lattner86102b82005-01-01 16:22:27 +00003161 // and X, X = X
3162 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003163 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003164
Chris Lattner5b2edb12006-02-12 08:02:11 +00003165 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003166 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003167 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003168 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3169 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3170 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003171 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003172 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003173 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003174 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003175 if (CP->isAllOnesValue())
3176 return ReplaceInstUsesWith(I, I.getOperand(0));
3177 }
3178 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003179
Zhou Sheng75b871f2007-01-11 12:24:14 +00003180 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003181 APInt AndRHSMask(AndRHS->getValue());
3182 APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3183 APInt NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003184
Chris Lattnerba1cb382003-09-19 17:17:26 +00003185 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003186 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003187 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003188 Value *Op0LHS = Op0I->getOperand(0);
3189 Value *Op0RHS = Op0I->getOperand(1);
3190 switch (Op0I->getOpcode()) {
3191 case Instruction::Xor:
3192 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003193 // If the mask is only needed on one incoming arm, push it up.
3194 if (Op0I->hasOneUse()) {
3195 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3196 // Not masking anything out for the LHS, move to RHS.
3197 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3198 Op0RHS->getName()+".masked");
3199 InsertNewInstBefore(NewRHS, I);
3200 return BinaryOperator::create(
3201 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003202 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003203 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003204 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3205 // Not masking anything out for the RHS, move to LHS.
3206 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3207 Op0LHS->getName()+".masked");
3208 InsertNewInstBefore(NewLHS, I);
3209 return BinaryOperator::create(
3210 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3211 }
3212 }
3213
Chris Lattner86102b82005-01-01 16:22:27 +00003214 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003215 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003216 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3217 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3218 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3219 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3220 return BinaryOperator::createAnd(V, AndRHS);
3221 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3222 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003223 break;
3224
3225 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003226 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3227 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3228 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3229 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3230 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003231 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003232 }
3233
Chris Lattner16464b32003-07-23 19:25:52 +00003234 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003235 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003236 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003237 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003238 // If this is an integer truncation or change from signed-to-unsigned, and
3239 // if the source is an and/or with immediate, transform it. This
3240 // frequently occurs for bitfield accesses.
3241 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003242 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003243 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003244 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003245 if (CastOp->getOpcode() == Instruction::And) {
3246 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003247 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3248 // This will fold the two constants together, which may allow
3249 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003250 Instruction *NewCast = CastInst::createTruncOrBitCast(
3251 CastOp->getOperand(0), I.getType(),
3252 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003253 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003254 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003255 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003256 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003257 return BinaryOperator::createAnd(NewCast, C3);
3258 } else if (CastOp->getOpcode() == Instruction::Or) {
3259 // Change: and (cast (or X, C1) to T), C2
3260 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003261 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003262 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3263 return ReplaceInstUsesWith(I, AndRHS);
3264 }
3265 }
Chris Lattner33217db2003-07-23 19:36:21 +00003266 }
Chris Lattner183b3362004-04-09 19:05:30 +00003267
3268 // Try to fold constant and into select arguments.
3269 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003271 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003272 if (isa<PHINode>(Op0))
3273 if (Instruction *NV = FoldOpIntoPhi(I))
3274 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003275 }
3276
Chris Lattnerbb74e222003-03-10 23:06:50 +00003277 Value *Op0NotVal = dyn_castNotVal(Op0);
3278 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003279
Chris Lattner023a4832004-06-18 06:07:51 +00003280 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3281 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3282
Misha Brukman9c003d82004-07-30 12:50:08 +00003283 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003284 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003285 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3286 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003287 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003288 return BinaryOperator::createNot(Or);
3289 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003290
3291 {
3292 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003293 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3294 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3295 return ReplaceInstUsesWith(I, Op1);
3296 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3297 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3298 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003299
3300 if (Op0->hasOneUse() &&
3301 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3302 if (A == Op1) { // (A^B)&A -> A&(A^B)
3303 I.swapOperands(); // Simplify below
3304 std::swap(Op0, Op1);
3305 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3306 cast<BinaryOperator>(Op0)->swapOperands();
3307 I.swapOperands(); // Simplify below
3308 std::swap(Op0, Op1);
3309 }
3310 }
3311 if (Op1->hasOneUse() &&
3312 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3313 if (B == Op0) { // B&(A^B) -> B&(B^A)
3314 cast<BinaryOperator>(Op1)->swapOperands();
3315 std::swap(A, B);
3316 }
3317 if (A == Op0) { // A&(A^B) -> A & ~B
3318 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3319 InsertNewInstBefore(NotB, I);
3320 return BinaryOperator::createAnd(A, NotB);
3321 }
3322 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003323 }
3324
Reid Spencer266e42b2006-12-23 06:05:41 +00003325 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3326 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3327 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003328 return R;
3329
Chris Lattner623826c2004-09-28 21:48:02 +00003330 Value *LHSVal, *RHSVal;
3331 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003332 ICmpInst::Predicate LHSCC, RHSCC;
3333 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3334 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3335 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3336 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3337 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3338 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3339 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3340 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003341 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003342 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3343 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3344 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3345 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003346 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003347 std::swap(LHS, RHS);
3348 std::swap(LHSCst, RHSCst);
3349 std::swap(LHSCC, RHSCC);
3350 }
3351
Reid Spencer266e42b2006-12-23 06:05:41 +00003352 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003353 // comparing a value against two constants and and'ing the result
3354 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003355 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3356 // (from the FoldICmpLogical check above), that the two constants
3357 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003358 assert(LHSCst != RHSCst && "Compares not folded above?");
3359
3360 switch (LHSCC) {
3361 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003362 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003363 switch (RHSCC) {
3364 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003365 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3366 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3367 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003368 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003369 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3370 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3371 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003372 return ReplaceInstUsesWith(I, LHS);
3373 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003374 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003375 switch (RHSCC) {
3376 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003377 case ICmpInst::ICMP_ULT:
3378 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3379 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3380 break; // (X != 13 & X u< 15) -> no change
3381 case ICmpInst::ICMP_SLT:
3382 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3383 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3384 break; // (X != 13 & X s< 15) -> no change
3385 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3386 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3387 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003388 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003389 case ICmpInst::ICMP_NE:
3390 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003391 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3392 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3393 LHSVal->getName()+".off");
3394 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003395 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3396 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003397 }
3398 break; // (X != 13 & X != 15) -> no change
3399 }
3400 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003401 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003402 switch (RHSCC) {
3403 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003404 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3405 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003406 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003407 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3408 break;
3409 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3410 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003411 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003412 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3413 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003414 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003415 break;
3416 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003417 switch (RHSCC) {
3418 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003419 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3420 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003421 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003422 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3423 break;
3424 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3425 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003426 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003427 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3428 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003429 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003430 break;
3431 case ICmpInst::ICMP_UGT:
3432 switch (RHSCC) {
3433 default: assert(0 && "Unknown integer condition code!");
3434 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3435 return ReplaceInstUsesWith(I, LHS);
3436 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3437 return ReplaceInstUsesWith(I, RHS);
3438 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3439 break;
3440 case ICmpInst::ICMP_NE:
3441 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3442 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3443 break; // (X u> 13 & X != 15) -> no change
3444 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3445 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3446 true, I);
3447 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3448 break;
3449 }
3450 break;
3451 case ICmpInst::ICMP_SGT:
3452 switch (RHSCC) {
3453 default: assert(0 && "Unknown integer condition code!");
3454 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3455 return ReplaceInstUsesWith(I, LHS);
3456 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3457 return ReplaceInstUsesWith(I, RHS);
3458 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3459 break;
3460 case ICmpInst::ICMP_NE:
3461 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3462 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3463 break; // (X s> 13 & X != 15) -> no change
3464 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3465 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3466 true, I);
3467 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3468 break;
3469 }
3470 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003471 }
3472 }
3473 }
3474
Chris Lattner3af10532006-05-05 06:39:07 +00003475 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003476 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3477 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3478 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3479 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003480 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003481 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003482 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3483 I.getType(), TD) &&
3484 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3485 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003486 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3487 Op1C->getOperand(0),
3488 I.getName());
3489 InsertNewInstBefore(NewOp, I);
3490 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3491 }
Chris Lattner3af10532006-05-05 06:39:07 +00003492 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003493
3494 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003495 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3496 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3497 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003498 SI0->getOperand(1) == SI1->getOperand(1) &&
3499 (SI0->hasOneUse() || SI1->hasOneUse())) {
3500 Instruction *NewOp =
3501 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3502 SI1->getOperand(0),
3503 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003504 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3505 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003506 }
Chris Lattner3af10532006-05-05 06:39:07 +00003507 }
3508
Chris Lattner113f4f42002-06-25 16:13:24 +00003509 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003510}
3511
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003512/// CollectBSwapParts - Look to see if the specified value defines a single byte
3513/// in the result. If it does, and if the specified byte hasn't been filled in
3514/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003515static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003516 Instruction *I = dyn_cast<Instruction>(V);
3517 if (I == 0) return true;
3518
3519 // If this is an or instruction, it is an inner node of the bswap.
3520 if (I->getOpcode() == Instruction::Or)
3521 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3522 CollectBSwapParts(I->getOperand(1), ByteValues);
3523
3524 // If this is a shift by a constant int, and it is "24", then its operand
3525 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003526 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003527 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003528 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003529 8*(ByteValues.size()-1))
3530 return true;
3531
3532 unsigned DestNo;
3533 if (I->getOpcode() == Instruction::Shl) {
3534 // X << 24 defines the top byte with the lowest of the input bytes.
3535 DestNo = ByteValues.size()-1;
3536 } else {
3537 // X >>u 24 defines the low byte with the highest of the input bytes.
3538 DestNo = 0;
3539 }
3540
3541 // If the destination byte value is already defined, the values are or'd
3542 // together, which isn't a bswap (unless it's an or of the same bits).
3543 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3544 return true;
3545 ByteValues[DestNo] = I->getOperand(0);
3546 return false;
3547 }
3548
3549 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3550 // don't have this.
3551 Value *Shift = 0, *ShiftLHS = 0;
3552 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3553 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3554 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3555 return true;
3556 Instruction *SI = cast<Instruction>(Shift);
3557
3558 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003559 if (ShiftAmt->getZExtValue() & 7 ||
3560 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003561 return true;
3562
3563 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3564 unsigned DestByte;
3565 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003566 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003567 break;
3568 // Unknown mask for bswap.
3569 if (DestByte == ByteValues.size()) return true;
3570
Reid Spencere0fc4df2006-10-20 07:07:24 +00003571 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003572 unsigned SrcByte;
3573 if (SI->getOpcode() == Instruction::Shl)
3574 SrcByte = DestByte - ShiftBytes;
3575 else
3576 SrcByte = DestByte + ShiftBytes;
3577
3578 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3579 if (SrcByte != ByteValues.size()-DestByte-1)
3580 return true;
3581
3582 // If the destination byte value is already defined, the values are or'd
3583 // together, which isn't a bswap (unless it's an or of the same bits).
3584 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3585 return true;
3586 ByteValues[DestByte] = SI->getOperand(0);
3587 return false;
3588}
3589
3590/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3591/// If so, insert the new bswap intrinsic and return it.
3592Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003593 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003594 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003595 return 0;
3596
3597 /// ByteValues - For each byte of the result, we keep track of which value
3598 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003599 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003600 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003601
3602 // Try to find all the pieces corresponding to the bswap.
3603 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3604 CollectBSwapParts(I.getOperand(1), ByteValues))
3605 return 0;
3606
3607 // Check to see if all of the bytes come from the same value.
3608 Value *V = ByteValues[0];
3609 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3610
3611 // Check to make sure that all of the bytes come from the same value.
3612 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3613 if (ByteValues[i] != V)
3614 return 0;
3615
3616 // If they do then *success* we can turn this into a bswap. Figure out what
3617 // bswap to make it into.
3618 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003619 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003620 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003621 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003622 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003623 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003624 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003625 FnName = "llvm.bswap.i64";
3626 else
3627 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003628 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003629 return new CallInst(F, V);
3630}
3631
3632
Chris Lattner113f4f42002-06-25 16:13:24 +00003633Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003634 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003636
Chris Lattner81a7a232004-10-16 18:11:37 +00003637 if (isa<UndefValue>(Op1))
3638 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003639 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003640
Chris Lattner5b2edb12006-02-12 08:02:11 +00003641 // or X, X = X
3642 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003643 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003644
Chris Lattner5b2edb12006-02-12 08:02:11 +00003645 // See if we can simplify any instructions used by the instruction whose sole
3646 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003647 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3648 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Reid Spencerd84d35b2007-02-15 02:26:10 +00003649 if (!isa<VectorType>(I.getType()) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003650 SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003651 KnownZero, KnownOne))
3652 return &I;
3653
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003654 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003655 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003656 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003657 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3658 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003659 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003660 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003661 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003662 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3663 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003664
Chris Lattnerd4252a72004-07-30 07:50:03 +00003665 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3666 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003667 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003668 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003669 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003670 return BinaryOperator::createXor(Or,
3671 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003672 }
Chris Lattner183b3362004-04-09 19:05:30 +00003673
3674 // Try to fold constant and into select arguments.
3675 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003676 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003677 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003678 if (isa<PHINode>(Op0))
3679 if (Instruction *NV = FoldOpIntoPhi(I))
3680 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003681 }
3682
Chris Lattner330628a2006-01-06 17:59:59 +00003683 Value *A = 0, *B = 0;
3684 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003685
3686 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3687 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3688 return ReplaceInstUsesWith(I, Op1);
3689 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3690 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3691 return ReplaceInstUsesWith(I, Op0);
3692
Chris Lattnerb7845d62006-07-10 20:25:24 +00003693 // (A | B) | C and A | (B | C) -> bswap if possible.
3694 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003695 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003696 match(Op1, m_Or(m_Value(), m_Value())) ||
3697 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3698 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003699 if (Instruction *BSwap = MatchBSwap(I))
3700 return BSwap;
3701 }
3702
Chris Lattnerb62f5082005-05-09 04:58:36 +00003703 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3704 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003705 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003706 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3707 InsertNewInstBefore(NOr, I);
3708 NOr->takeName(Op0);
3709 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003710 }
3711
3712 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3713 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003714 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003715 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3716 InsertNewInstBefore(NOr, I);
3717 NOr->takeName(Op0);
3718 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003719 }
3720
Chris Lattner15212982005-09-18 03:42:07 +00003721 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003722 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003723 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3724
3725 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3726 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3727
3728
Chris Lattner01f56c62005-09-18 06:02:59 +00003729 // If we have: ((V + N) & C1) | (V & C2)
3730 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3731 // replace with V+N.
3732 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003733 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003734 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003735 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3736 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003737 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003738 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003739 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003740 return ReplaceInstUsesWith(I, A);
3741 }
3742 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003743 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003744 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3745 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003746 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003747 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003748 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003749 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003750 }
3751 }
3752 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003753
3754 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003755 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3756 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3757 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003758 SI0->getOperand(1) == SI1->getOperand(1) &&
3759 (SI0->hasOneUse() || SI1->hasOneUse())) {
3760 Instruction *NewOp =
3761 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3762 SI1->getOperand(0),
3763 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003764 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3765 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003766 }
3767 }
Chris Lattner812aab72003-08-12 19:11:07 +00003768
Chris Lattnerd4252a72004-07-30 07:50:03 +00003769 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3770 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003771 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003772 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003773 } else {
3774 A = 0;
3775 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003776 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003777 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3778 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003779 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003780 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003781
Misha Brukman9c003d82004-07-30 12:50:08 +00003782 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003783 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3784 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3785 I.getName()+".demorgan"), I);
3786 return BinaryOperator::createNot(And);
3787 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003788 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003789
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3791 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3792 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003793 return R;
3794
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003795 Value *LHSVal, *RHSVal;
3796 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003797 ICmpInst::Predicate LHSCC, RHSCC;
3798 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3799 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3800 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3801 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3802 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3803 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3804 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3805 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003806 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003807 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3808 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3809 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3810 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003811 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003812 std::swap(LHS, RHS);
3813 std::swap(LHSCst, RHSCst);
3814 std::swap(LHSCC, RHSCC);
3815 }
3816
Reid Spencer266e42b2006-12-23 06:05:41 +00003817 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003818 // comparing a value against two constants and or'ing the result
3819 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003820 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3821 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003822 // equal.
3823 assert(LHSCst != RHSCst && "Compares not folded above?");
3824
3825 switch (LHSCC) {
3826 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003827 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003828 switch (RHSCC) {
3829 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003830 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003831 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3832 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3833 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3834 LHSVal->getName()+".off");
3835 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003836 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003837 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003838 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003839 break; // (X == 13 | X == 15) -> no change
3840 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3841 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003842 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003843 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3844 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3845 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003846 return ReplaceInstUsesWith(I, RHS);
3847 }
3848 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003849 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003850 switch (RHSCC) {
3851 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003852 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3853 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3854 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003855 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003856 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3857 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3858 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003859 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003860 }
3861 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003862 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003863 switch (RHSCC) {
3864 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003865 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003866 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003867 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3868 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3869 false, I);
3870 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3871 break;
3872 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3873 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003874 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003875 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3876 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003877 }
3878 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003879 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003880 switch (RHSCC) {
3881 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003882 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3883 break;
3884 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3885 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3886 false, I);
3887 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3888 break;
3889 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3890 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3891 return ReplaceInstUsesWith(I, RHS);
3892 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3893 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003894 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003895 break;
3896 case ICmpInst::ICMP_UGT:
3897 switch (RHSCC) {
3898 default: assert(0 && "Unknown integer condition code!");
3899 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3900 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3901 return ReplaceInstUsesWith(I, LHS);
3902 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3903 break;
3904 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3905 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003906 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003907 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3908 break;
3909 }
3910 break;
3911 case ICmpInst::ICMP_SGT:
3912 switch (RHSCC) {
3913 default: assert(0 && "Unknown integer condition code!");
3914 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3915 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3916 return ReplaceInstUsesWith(I, LHS);
3917 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3920 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003921 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003922 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3923 break;
3924 }
3925 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003926 }
3927 }
3928 }
Chris Lattner3af10532006-05-05 06:39:07 +00003929
3930 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003931 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003932 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003933 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3934 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003935 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003936 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003937 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3938 I.getType(), TD) &&
3939 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3940 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003941 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3942 Op1C->getOperand(0),
3943 I.getName());
3944 InsertNewInstBefore(NewOp, I);
3945 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3946 }
Chris Lattner3af10532006-05-05 06:39:07 +00003947 }
Chris Lattner3af10532006-05-05 06:39:07 +00003948
Chris Lattner15212982005-09-18 03:42:07 +00003949
Chris Lattner113f4f42002-06-25 16:13:24 +00003950 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003951}
3952
Chris Lattnerc2076352004-02-16 01:20:27 +00003953// XorSelf - Implements: X ^ X --> 0
3954struct XorSelf {
3955 Value *RHS;
3956 XorSelf(Value *rhs) : RHS(rhs) {}
3957 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3958 Instruction *apply(BinaryOperator &Xor) const {
3959 return &Xor;
3960 }
3961};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003962
3963
Chris Lattner113f4f42002-06-25 16:13:24 +00003964Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003965 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003967
Chris Lattner81a7a232004-10-16 18:11:37 +00003968 if (isa<UndefValue>(Op1))
3969 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3970
Chris Lattnerc2076352004-02-16 01:20:27 +00003971 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3972 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3973 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003974 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003975 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003976
3977 // See if we can simplify any instructions used by the instruction whose sole
3978 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003979 if (!isa<VectorType>(I.getType())) {
3980 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3981 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3982 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3983 KnownZero, KnownOne))
3984 return &I;
3985 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003986
Zhou Sheng75b871f2007-01-11 12:24:14 +00003987 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003988 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3989 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003990 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003991 return new ICmpInst(ICI->getInversePredicate(),
3992 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003993
Reid Spencer266e42b2006-12-23 06:05:41 +00003994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003995 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003996 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3997 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003998 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3999 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004000 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004001 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004002 }
Chris Lattner023a4832004-06-18 06:07:51 +00004003
4004 // ~(~X & Y) --> (X | ~Y)
4005 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4006 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4007 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4008 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004009 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004010 Op0I->getOperand(1)->getName()+".not");
4011 InsertNewInstBefore(NotY, I);
4012 return BinaryOperator::createOr(Op0NotVal, NotY);
4013 }
4014 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004015
Chris Lattner97638592003-07-23 21:37:07 +00004016 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004017 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004018 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004019 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004020 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4021 return BinaryOperator::createSub(
4022 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004023 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004024 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004025 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004026 } else if (Op0I->getOpcode() == Instruction::Or) {
4027 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004028 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004029 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4030 // Anything in both C1 and C2 is known to be zero, remove it from
4031 // NewRHS.
4032 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4033 NewRHS = ConstantExpr::getAnd(NewRHS,
4034 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004035 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004036 I.setOperand(0, Op0I->getOperand(0));
4037 I.setOperand(1, NewRHS);
4038 return &I;
4039 }
Chris Lattner97638592003-07-23 21:37:07 +00004040 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004041 }
Chris Lattner183b3362004-04-09 19:05:30 +00004042
4043 // Try to fold constant and into select arguments.
4044 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004045 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004046 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004047 if (isa<PHINode>(Op0))
4048 if (Instruction *NV = FoldOpIntoPhi(I))
4049 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004050 }
4051
Chris Lattnerbb74e222003-03-10 23:06:50 +00004052 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004053 if (X == Op1)
4054 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004055 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004056
Chris Lattnerbb74e222003-03-10 23:06:50 +00004057 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004058 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004059 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004060
Chris Lattner07418422007-03-18 22:51:34 +00004061
4062 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4063 if (Op1I) {
4064 Value *A, *B;
4065 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4066 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004067 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004068 I.swapOperands();
4069 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004070 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004071 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004072 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004073 }
Chris Lattner07418422007-03-18 22:51:34 +00004074 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4075 if (Op0 == A) // A^(A^B) == B
4076 return ReplaceInstUsesWith(I, B);
4077 else if (Op0 == B) // A^(B^A) == B
4078 return ReplaceInstUsesWith(I, A);
4079 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4080 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004081 Op1I->swapOperands();
Chris Lattner07418422007-03-18 22:51:34 +00004082 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004083 I.swapOperands(); // Simplified below.
4084 std::swap(Op0, Op1);
4085 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004086 }
Chris Lattner07418422007-03-18 22:51:34 +00004087 }
4088
4089 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4090 if (Op0I) {
4091 Value *A, *B;
4092 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4093 if (A == Op1) // (B|A)^B == (A|B)^B
4094 std::swap(A, B);
4095 if (B == Op1) { // (A|B)^B == A & ~B
4096 Instruction *NotB =
4097 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4098 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004099 }
Chris Lattner07418422007-03-18 22:51:34 +00004100 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4101 if (Op1 == A) // (A^B)^A == B
4102 return ReplaceInstUsesWith(I, B);
4103 else if (Op1 == B) // (B^A)^A == B
4104 return ReplaceInstUsesWith(I, A);
4105 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4106 if (A == Op1) // (A&B)^A -> (B&A)^A
4107 std::swap(A, B);
4108 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004109 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004110 Instruction *N =
4111 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004112 return BinaryOperator::createAnd(N, Op1);
4113 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004114 }
Chris Lattner07418422007-03-18 22:51:34 +00004115 }
4116
4117 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4118 if (Op0I && Op1I && Op0I->isShift() &&
4119 Op0I->getOpcode() == Op1I->getOpcode() &&
4120 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4121 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4122 Instruction *NewOp =
4123 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4124 Op1I->getOperand(0),
4125 Op0I->getName()), I);
4126 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4127 Op1I->getOperand(1));
4128 }
4129
4130 if (Op0I && Op1I) {
4131 Value *A, *B, *C, *D;
4132 // (A & B)^(A | B) -> A ^ B
4133 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4134 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4135 if ((A == C && B == D) || (A == D && B == C))
4136 return BinaryOperator::createXor(A, B);
4137 }
4138 // (A | B)^(A & B) -> A ^ B
4139 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4140 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4141 if ((A == C && B == D) || (A == D && B == C))
4142 return BinaryOperator::createXor(A, B);
4143 }
4144
4145 // (A & B)^(C & D)
4146 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4147 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4148 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4149 // (X & Y)^(X & Y) -> (Y^Z) & X
4150 Value *X = 0, *Y = 0, *Z = 0;
4151 if (A == C)
4152 X = A, Y = B, Z = D;
4153 else if (A == D)
4154 X = A, Y = B, Z = C;
4155 else if (B == C)
4156 X = B, Y = A, Z = D;
4157 else if (B == D)
4158 X = B, Y = A, Z = C;
4159
4160 if (X) {
4161 Instruction *NewOp =
4162 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4163 return BinaryOperator::createAnd(NewOp, X);
4164 }
4165 }
4166 }
4167
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4169 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4170 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004171 return R;
4172
Chris Lattner3af10532006-05-05 06:39:07 +00004173 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004174 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004175 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004176 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4177 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004178 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004179 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004180 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4181 I.getType(), TD) &&
4182 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4183 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004184 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4185 Op1C->getOperand(0),
4186 I.getName());
4187 InsertNewInstBefore(NewOp, I);
4188 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4189 }
Chris Lattner3af10532006-05-05 06:39:07 +00004190 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004191
Chris Lattner113f4f42002-06-25 16:13:24 +00004192 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004193}
4194
Chris Lattner6862fbd2004-09-29 17:40:11 +00004195/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4196/// overflowed for this type.
4197static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004198 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004199 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4200
Reid Spencerf4071162007-03-21 23:19:50 +00004201 if (IsSigned)
4202 if (In2->getValue().isNegative())
4203 return Result->getValue().sgt(In1->getValue());
4204 else
4205 return Result->getValue().slt(In1->getValue());
4206 else
4207 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004208}
4209
Chris Lattner0798af32005-01-13 20:14:25 +00004210/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4211/// code necessary to compute the offset from the base pointer (without adding
4212/// in the base pointer). Return the result as a signed integer of intptr size.
4213static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4214 TargetData &TD = IC.getTargetData();
4215 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004216 const Type *IntPtrTy = TD.getIntPtrType();
4217 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004218
4219 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004220 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004221
Chris Lattner0798af32005-01-13 20:14:25 +00004222 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4223 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004224 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004225 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004226 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4227 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004228 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004229 Scale = ConstantExpr::getMul(OpC, Scale);
4230 if (Constant *RC = dyn_cast<Constant>(Result))
4231 Result = ConstantExpr::getAdd(RC, Scale);
4232 else {
4233 // Emit an add instruction.
4234 Result = IC.InsertNewInstBefore(
4235 BinaryOperator::createAdd(Result, Scale,
4236 GEP->getName()+".offs"), I);
4237 }
4238 }
4239 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004240 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004241 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004242 Op->getName()+".c"), I);
4243 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004244 // We'll let instcombine(mul) convert this to a shl if possible.
4245 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4246 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004247
4248 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004249 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004250 GEP->getName()+".offs"), I);
4251 }
4252 }
4253 return Result;
4254}
4255
Reid Spencer266e42b2006-12-23 06:05:41 +00004256/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004257/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004258Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4259 ICmpInst::Predicate Cond,
4260 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004261 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004262
4263 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4264 if (isa<PointerType>(CI->getOperand(0)->getType()))
4265 RHS = CI->getOperand(0);
4266
Chris Lattner0798af32005-01-13 20:14:25 +00004267 Value *PtrBase = GEPLHS->getOperand(0);
4268 if (PtrBase == RHS) {
4269 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004270 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4271 // each index is zero or not.
4272 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004273 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004274 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4275 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004276 bool EmitIt = true;
4277 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4278 if (isa<UndefValue>(C)) // undef index -> undef.
4279 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4280 if (C->isNullValue())
4281 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004282 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4283 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004284 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004285 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004286 ConstantInt::get(Type::Int1Ty,
4287 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004288 }
4289
4290 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004291 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004292 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004293 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4294 if (InVal == 0)
4295 InVal = Comp;
4296 else {
4297 InVal = InsertNewInstBefore(InVal, I);
4298 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004299 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004300 InVal = BinaryOperator::createOr(InVal, Comp);
4301 else // True if all are equal
4302 InVal = BinaryOperator::createAnd(InVal, Comp);
4303 }
4304 }
4305 }
4306
4307 if (InVal)
4308 return InVal;
4309 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004310 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004311 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4312 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004313 }
Chris Lattner0798af32005-01-13 20:14:25 +00004314
Reid Spencer266e42b2006-12-23 06:05:41 +00004315 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004316 // the result to fold to a constant!
4317 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4318 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4319 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004320 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4321 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004322 }
4323 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004324 // If the base pointers are different, but the indices are the same, just
4325 // compare the base pointer.
4326 if (PtrBase != GEPRHS->getOperand(0)) {
4327 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004328 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004329 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004330 if (IndicesTheSame)
4331 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4332 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4333 IndicesTheSame = false;
4334 break;
4335 }
4336
4337 // If all indices are the same, just compare the base pointers.
4338 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004339 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4340 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004341
4342 // Otherwise, the base pointers are different and the indices are
4343 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004344 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004345 }
Chris Lattner0798af32005-01-13 20:14:25 +00004346
Chris Lattner81e84172005-01-13 22:25:21 +00004347 // If one of the GEPs has all zero indices, recurse.
4348 bool AllZeros = true;
4349 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4350 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4351 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4352 AllZeros = false;
4353 break;
4354 }
4355 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004356 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4357 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004358
4359 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004360 AllZeros = true;
4361 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4362 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4363 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4364 AllZeros = false;
4365 break;
4366 }
4367 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004368 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004369
Chris Lattner4fa89822005-01-14 00:20:05 +00004370 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4371 // If the GEPs only differ by one index, compare it.
4372 unsigned NumDifferences = 0; // Keep track of # differences.
4373 unsigned DiffOperand = 0; // The operand that differs.
4374 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4375 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004376 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4377 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004378 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004379 NumDifferences = 2;
4380 break;
4381 } else {
4382 if (NumDifferences++) break;
4383 DiffOperand = i;
4384 }
4385 }
4386
4387 if (NumDifferences == 0) // SAME GEP?
4388 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004389 ConstantInt::get(Type::Int1Ty,
4390 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004391 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004392 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4393 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004394 // Make sure we do a signed comparison here.
4395 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004396 }
4397 }
4398
Reid Spencer266e42b2006-12-23 06:05:41 +00004399 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004400 // the result to fold to a constant!
4401 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4402 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4403 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4404 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4405 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004406 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004407 }
4408 }
4409 return 0;
4410}
4411
Reid Spencer266e42b2006-12-23 06:05:41 +00004412Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4413 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004415
Chris Lattner6ee923f2007-01-14 19:42:17 +00004416 // Fold trivial predicates.
4417 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4418 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4419 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4420 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4421
4422 // Simplify 'fcmp pred X, X'
4423 if (Op0 == Op1) {
4424 switch (I.getPredicate()) {
4425 default: assert(0 && "Unknown predicate!");
4426 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4427 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4428 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4429 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4430 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4431 case FCmpInst::FCMP_OLT: // True if ordered and less than
4432 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4433 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4434
4435 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4436 case FCmpInst::FCMP_ULT: // True if unordered or less than
4437 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4438 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4439 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4440 I.setPredicate(FCmpInst::FCMP_UNO);
4441 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4442 return &I;
4443
4444 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4445 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4446 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4447 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4448 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4449 I.setPredicate(FCmpInst::FCMP_ORD);
4450 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4451 return &I;
4452 }
4453 }
4454
Reid Spencer266e42b2006-12-23 06:05:41 +00004455 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004456 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004457
Reid Spencer266e42b2006-12-23 06:05:41 +00004458 // Handle fcmp with constant RHS
4459 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4460 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4461 switch (LHSI->getOpcode()) {
4462 case Instruction::PHI:
4463 if (Instruction *NV = FoldOpIntoPhi(I))
4464 return NV;
4465 break;
4466 case Instruction::Select:
4467 // If either operand of the select is a constant, we can fold the
4468 // comparison into the select arms, which will cause one to be
4469 // constant folded and the select turned into a bitwise or.
4470 Value *Op1 = 0, *Op2 = 0;
4471 if (LHSI->hasOneUse()) {
4472 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4473 // Fold the known value into the constant operand.
4474 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4475 // Insert a new FCmp of the other select operand.
4476 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4477 LHSI->getOperand(2), RHSC,
4478 I.getName()), I);
4479 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4480 // Fold the known value into the constant operand.
4481 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4482 // Insert a new FCmp of the other select operand.
4483 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4484 LHSI->getOperand(1), RHSC,
4485 I.getName()), I);
4486 }
4487 }
4488
4489 if (Op1)
4490 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4491 break;
4492 }
4493 }
4494
4495 return Changed ? &I : 0;
4496}
4497
4498Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4499 bool Changed = SimplifyCompare(I);
4500 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4501 const Type *Ty = Op0->getType();
4502
4503 // icmp X, X
4504 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004505 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4506 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004507
4508 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004509 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004510
4511 // icmp of GlobalValues can never equal each other as long as they aren't
4512 // external weak linkage type.
4513 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4514 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4515 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004516 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4517 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004518
4519 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004520 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004521 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4522 isa<ConstantPointerNull>(Op0)) &&
4523 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004524 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004525 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4526 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004527
Reid Spencer266e42b2006-12-23 06:05:41 +00004528 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004529 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 switch (I.getPredicate()) {
4531 default: assert(0 && "Invalid icmp instruction!");
4532 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004533 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004534 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004535 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004536 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004537 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004538 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004539
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 case ICmpInst::ICMP_UGT:
4541 case ICmpInst::ICMP_SGT:
4542 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004543 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004544 case ICmpInst::ICMP_ULT:
4545 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004546 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4547 InsertNewInstBefore(Not, I);
4548 return BinaryOperator::createAnd(Not, Op1);
4549 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 case ICmpInst::ICMP_UGE:
4551 case ICmpInst::ICMP_SGE:
4552 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004553 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 case ICmpInst::ICMP_ULE:
4555 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004556 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4557 InsertNewInstBefore(Not, I);
4558 return BinaryOperator::createOr(Not, Op1);
4559 }
4560 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004561 }
4562
Chris Lattner2dd01742004-06-09 04:24:29 +00004563 // See if we are doing a comparison between a constant and an instruction that
4564 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004565 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004566 switch (I.getPredicate()) {
4567 default: break;
4568 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4569 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004570 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004571 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4572 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4573 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4574 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4575 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004576
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 case ICmpInst::ICMP_SLT:
4578 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004579 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004580 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4581 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4582 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4583 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4584 break;
4585
4586 case ICmpInst::ICMP_UGT:
4587 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004588 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004589 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4590 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4591 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4592 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4593 break;
4594
4595 case ICmpInst::ICMP_SGT:
4596 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004597 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004598 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4599 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4600 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4601 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4602 break;
4603
4604 case ICmpInst::ICMP_ULE:
4605 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004606 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004607 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4608 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4609 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4610 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4611 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004612
Reid Spencer266e42b2006-12-23 06:05:41 +00004613 case ICmpInst::ICMP_SLE:
4614 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004615 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004616 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4617 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4618 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4619 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4620 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004621
Reid Spencer266e42b2006-12-23 06:05:41 +00004622 case ICmpInst::ICMP_UGE:
4623 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004624 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004625 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4626 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4627 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4628 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4629 break;
4630
4631 case ICmpInst::ICMP_SGE:
4632 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004633 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004634 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4635 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4636 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4637 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4638 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004639 }
4640
Reid Spencer266e42b2006-12-23 06:05:41 +00004641 // If we still have a icmp le or icmp ge instruction, turn it into the
4642 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004643 // already been handled above, this requires little checking.
4644 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004645 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4646 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4647 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4648 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4649 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4650 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4651 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4652 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004653
4654 // See if we can fold the comparison based on bits known to be zero or one
4655 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004656 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4657 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4658 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004659 KnownZero, KnownOne, 0))
4660 return &I;
4661
4662 // Given the known and unknown bits, compute a range that the LHS could be
4663 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004664 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004665 // Compute the Min, Max and RHS values based on the known bits. For the
4666 // EQ and NE we use unsigned values.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004667 APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004668 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004669 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4670 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004671 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004672 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4673 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004674 }
4675 switch (I.getPredicate()) { // LE/GE have been folded already.
4676 default: assert(0 && "Unknown icmp opcode!");
4677 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004678 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004679 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004680 break;
4681 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004682 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004683 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004684 break;
4685 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004686 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004687 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004688 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004689 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004690 break;
4691 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004692 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004693 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004694 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004696 break;
4697 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004698 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004700 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004702 break;
4703 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004704 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004705 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004706 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004708 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004709 }
4710 }
4711
Reid Spencer266e42b2006-12-23 06:05:41 +00004712 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004713 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004714 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004715 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004716 switch (LHSI->getOpcode()) {
4717 case Instruction::And:
4718 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4719 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004720 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4721
Reid Spencer266e42b2006-12-23 06:05:41 +00004722 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004723 // and/compare to be the input width without changing the value
4724 // produced, eliminating a cast.
4725 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4726 // We can do this transformation if either the AND constant does not
4727 // have its sign bit set or if it is an equality comparison.
4728 // Extending a relational comparison when we're checking the sign
4729 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004730 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004731 (I.isEquality() || AndCST->getValue().isPositive() &&
4732 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004733 ConstantInt *NewCST;
4734 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004735 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4736 uint32_t BitWidth = cast<IntegerType>(
4737 Cast->getOperand(0)->getType())->getBitWidth();
4738 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4739 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00004740 Instruction *NewAnd =
4741 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4742 LHSI->getName());
4743 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004744 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004745 }
4746 }
4747
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004748 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4749 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4750 // happens a LOT in code produced by the C front-end, for bitfield
4751 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004752 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4753 if (Shift && !Shift->isShift())
4754 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004755
Reid Spencere0fc4df2006-10-20 07:07:24 +00004756 ConstantInt *ShAmt;
4757 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004758 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4759 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004760
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004761 // We can fold this as long as we can't shift unknown bits
4762 // into the mask. This can only happen with signed shift
4763 // rights, as they sign-extend.
4764 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004765 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004766 if (!CanFold) {
4767 // To test for the bad case of the signed shr, see if any
4768 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004769 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004770 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4771
Reid Spencer2341c222007-02-02 02:16:23 +00004772 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004773 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004774 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4775 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004776 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4777 CanFold = true;
4778 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004779
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004780 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004781 Constant *NewCst;
4782 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004783 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004784 else
4785 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004786
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004787 // Check to see if we are shifting out any of the bits being
4788 // compared.
4789 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4790 // If we shifted bits out, the fold is not going to work out.
4791 // As a special case, check to see if this means that the
4792 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004793 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004794 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004795 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004796 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004797 } else {
4798 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004799 Constant *NewAndCST;
4800 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004801 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004802 else
4803 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4804 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004805 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004806 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004807 AddUsesToWorkList(I);
4808 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004809 }
4810 }
Chris Lattner35167c32004-06-09 07:59:58 +00004811 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004812
4813 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4814 // preferable because it allows the C<<Y expression to be hoisted out
4815 // of a loop if Y is invariant and X is not.
4816 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004817 I.isEquality() && !Shift->isArithmeticShift() &&
4818 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004819 // Compute C << Y.
4820 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004821 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004822 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004823 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004824 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004825 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004826 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004827 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004828 }
4829 InsertNewInstBefore(cast<Instruction>(NS), I);
4830
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004831 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004832 Instruction *NewAnd = BinaryOperator::createAnd(
4833 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004834 InsertNewInstBefore(NewAnd, I);
4835
4836 I.setOperand(0, NewAnd);
4837 return &I;
4838 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004839 }
4840 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004841
Reid Spencer266e42b2006-12-23 06:05:41 +00004842 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004843 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004844 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004845 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4846
4847 // Check that the shift amount is in range. If not, don't perform
4848 // undefined shifts. When the shift is visited it will be
4849 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004850 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004851 break;
4852
Chris Lattner272d5ca2004-09-28 18:22:15 +00004853 // If we are comparing against bits always shifted out, the
4854 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004855 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004856 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004857 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004858 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004859 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004860 return ReplaceInstUsesWith(I, Cst);
4861 }
4862
4863 if (LHSI->hasOneUse()) {
4864 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004865 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004866 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004867 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004868
Chris Lattner272d5ca2004-09-28 18:22:15 +00004869 Instruction *AndI =
4870 BinaryOperator::createAnd(LHSI->getOperand(0),
4871 Mask, LHSI->getName()+".mask");
4872 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004873 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004874 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004875 }
4876 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004877 }
4878 break;
4879
Reid Spencer266e42b2006-12-23 06:05:41 +00004880 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004881 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004882 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004883 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004884 // Check that the shift amount is in range. If not, don't perform
4885 // undefined shifts. When the shift is visited it will be
4886 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004887 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004888 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004889 break;
4890
Chris Lattner1023b872004-09-27 16:18:50 +00004891 // If we are comparing against bits always shifted out, the
4892 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004893 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004894 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004895 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4896 ShAmt);
4897 else
4898 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4899 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004900
Chris Lattner1023b872004-09-27 16:18:50 +00004901 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004902 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004903 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004904 return ReplaceInstUsesWith(I, Cst);
4905 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004906
Chris Lattner1023b872004-09-27 16:18:50 +00004907 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004908 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004909
Chris Lattner1023b872004-09-27 16:18:50 +00004910 // Otherwise strength reduce the shift into an and.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004911 APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
4912 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004913
Chris Lattner1023b872004-09-27 16:18:50 +00004914 Instruction *AndI =
4915 BinaryOperator::createAnd(LHSI->getOperand(0),
4916 Mask, LHSI->getName()+".mask");
4917 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004918 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004919 ConstantExpr::getShl(CI, ShAmt));
4920 }
Chris Lattner1023b872004-09-27 16:18:50 +00004921 }
4922 }
4923 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004924
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004925 case Instruction::SDiv:
4926 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004927 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004928 // Fold this div into the comparison, producing a range check.
4929 // Determine, based on the divide type, what the range is being
4930 // checked. If there is an overflow on the low or high side, remember
4931 // it, otherwise compute the range [low, hi) bounding the new value.
4932 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004933 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004934 // FIXME: If the operand types don't match the type of the divide
4935 // then don't attempt this transform. The code below doesn't have the
4936 // logic to deal with a signed divide and an unsigned compare (and
4937 // vice versa). This is because (x /s C1) <s C2 produces different
4938 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4939 // (x /u C1) <u C2. Simply casting the operands and result won't
4940 // work. :( The if statement below tests that condition and bails
4941 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004942 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4943 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004944 break;
Reid Spencerf4071162007-03-21 23:19:50 +00004945 if (DivRHS->isZero())
4946 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004947
4948 // Initialize the variables that will indicate the nature of the
4949 // range check.
4950 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004951 ConstantInt *LoBound = 0, *HiBound = 0;
4952
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004953 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4954 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4955 // C2 (CI). By solving for X we can turn this into a range check
4956 // instead of computing a divide.
4957 ConstantInt *Prod =
4958 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004959
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004960 // Determine if the product overflows by seeing if the product is
4961 // not equal to the divide. Make sure we do the same kind of divide
4962 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00004963 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4964 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004965
Reid Spencer266e42b2006-12-23 06:05:41 +00004966 // Get the ICmp opcode
4967 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004968
Reid Spencerf4071162007-03-21 23:19:50 +00004969 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004970 LoBound = Prod;
4971 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004972 HiOverflow = ProdOV ||
4973 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00004974 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004975 if (CI->isNullValue()) { // (X / pos) op 0
4976 // Can't overflow.
4977 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4978 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00004979 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004980 LoBound = Prod;
4981 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004982 HiOverflow = ProdOV ||
4983 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004984 } else { // (X / pos) op neg
4985 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4986 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00004987 cast<ConstantInt>(DivRHSH), true);
4988 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004989 HiOverflow = ProdOV;
4990 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004991 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004992 if (CI->isNullValue()) { // (X / neg) op 0
4993 LoBound = AddOne(DivRHS);
4994 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004995 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004996 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00004997 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004998 HiOverflow = LoOverflow = ProdOV;
4999 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00005000 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5001 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005002 HiBound = AddOne(Prod);
5003 } else { // (X / neg) op neg
5004 LoBound = Prod;
5005 LoOverflow = HiOverflow = ProdOV;
5006 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5007 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005008
Chris Lattnera92af962004-10-11 19:40:04 +00005009 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005010 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005011 }
5012
5013 if (LoBound) {
5014 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005015 switch (predicate) {
5016 default: assert(0 && "Unhandled icmp opcode!");
5017 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005018 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005019 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005020 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5022 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005023 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005024 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5025 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005026 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005027 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5028 true, I);
5029 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005030 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005031 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005032 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005033 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5034 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005035 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005036 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5037 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005038 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5040 false, I);
5041 case ICmpInst::ICMP_ULT:
5042 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005043 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005044 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005045 return new ICmpInst(predicate, X, LoBound);
5046 case ICmpInst::ICMP_UGT:
5047 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005048 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005049 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005050 if (predicate == ICmpInst::ICMP_UGT)
5051 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5052 else
5053 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005054 }
5055 }
5056 }
5057 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005058 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005059
Reid Spencer266e42b2006-12-23 06:05:41 +00005060 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005061 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005062 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005063
Reid Spencere0fc4df2006-10-20 07:07:24 +00005064 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5065 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005066 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5067 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005068 case Instruction::SRem:
5069 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005070 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005071 BO->hasOneUse()) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005072 APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5073 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005074 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5075 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005076 return new ICmpInst(I.getPredicate(), NewRem,
5077 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005078 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005079 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005080 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005081 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005082 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5083 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005084 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005085 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5086 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005087 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005088 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5089 // efficiently invertible, or if the add has just this one use.
5090 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005091
Chris Lattnerc992add2003-08-13 05:33:12 +00005092 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005093 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005094 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005095 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005096 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005097 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005098 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005099 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005100 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005101 }
5102 }
5103 break;
5104 case Instruction::Xor:
5105 // For the xor case, we can xor two constants together, eliminating
5106 // the explicit xor.
5107 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005108 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5109 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005110
5111 // FALLTHROUGH
5112 case Instruction::Sub:
5113 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005114 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005115 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5116 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005117 break;
5118
5119 case Instruction::Or:
5120 // If bits are being or'd in that are not present in the constant we
5121 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005122 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005123 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005124 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005125 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5126 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005127 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005128 break;
5129
5130 case Instruction::And:
5131 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005132 // If bits are being compared against that are and'd out, then the
5133 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005134 if (!ConstantExpr::getAnd(CI,
5135 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005136 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5137 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005138
Chris Lattner35167c32004-06-09 07:59:58 +00005139 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005140 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005141 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5142 ICmpInst::ICMP_NE, Op0,
5143 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005144
Reid Spencer266e42b2006-12-23 06:05:41 +00005145 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005146 if (isSignBit(BOC)) {
5147 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005148 Constant *Zero = Constant::getNullValue(X->getType());
5149 ICmpInst::Predicate pred = isICMP_NE ?
5150 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5151 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005152 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005153
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005154 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005155 if (CI->isNullValue() && isHighOnes(BOC)) {
5156 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005157 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005158 ICmpInst::Predicate pred = isICMP_NE ?
5159 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5160 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005161 }
5162
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005163 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005164 default: break;
5165 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005166 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5167 // Handle set{eq|ne} <intrinsic>, intcst.
5168 switch (II->getIntrinsicID()) {
5169 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005170 case Intrinsic::bswap_i16:
5171 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005172 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005173 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005174 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005175 ByteSwap_16(CI->getZExtValue())));
5176 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005177 case Intrinsic::bswap_i32:
5178 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005179 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005180 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005181 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005182 ByteSwap_32(CI->getZExtValue())));
5183 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005184 case Intrinsic::bswap_i64:
5185 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005186 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005187 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005188 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005189 ByteSwap_64(CI->getZExtValue())));
5190 return &I;
5191 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005192 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005193 } else { // Not a ICMP_EQ/ICMP_NE
5194 // If the LHS is a cast from an integral value of the same size, then
5195 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005196 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5197 Value *CastOp = Cast->getOperand(0);
5198 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005199 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005200 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005201 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005202 // If this is an unsigned comparison, try to make the comparison use
5203 // smaller constant values.
5204 switch (I.getPredicate()) {
5205 default: break;
5206 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5207 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005208 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005209 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005210 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005211 break;
5212 }
5213 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5214 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005215 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005216 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5217 Constant::getNullValue(SrcTy));
5218 break;
5219 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005220 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005221
Chris Lattner2b55ea32004-02-23 07:16:20 +00005222 }
5223 }
Chris Lattnere967b342003-06-04 05:10:11 +00005224 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005225 }
5226
Reid Spencer266e42b2006-12-23 06:05:41 +00005227 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005228 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5229 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5230 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005231 case Instruction::GetElementPtr:
5232 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005233 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005234 bool isAllZeros = true;
5235 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5236 if (!isa<Constant>(LHSI->getOperand(i)) ||
5237 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5238 isAllZeros = false;
5239 break;
5240 }
5241 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005242 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005243 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5244 }
5245 break;
5246
Chris Lattner77c32c32005-04-23 15:31:55 +00005247 case Instruction::PHI:
5248 if (Instruction *NV = FoldOpIntoPhi(I))
5249 return NV;
5250 break;
5251 case Instruction::Select:
5252 // If either operand of the select is a constant, we can fold the
5253 // comparison into the select arms, which will cause one to be
5254 // constant folded and the select turned into a bitwise or.
5255 Value *Op1 = 0, *Op2 = 0;
5256 if (LHSI->hasOneUse()) {
5257 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5258 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005259 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5260 // Insert a new ICmp of the other select operand.
5261 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5262 LHSI->getOperand(2), RHSC,
5263 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005264 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5265 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005266 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5267 // Insert a new ICmp of the other select operand.
5268 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5269 LHSI->getOperand(1), RHSC,
5270 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005271 }
5272 }
Jeff Cohen82639852005-04-23 21:38:35 +00005273
Chris Lattner77c32c32005-04-23 15:31:55 +00005274 if (Op1)
5275 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5276 break;
5277 }
5278 }
5279
Reid Spencer266e42b2006-12-23 06:05:41 +00005280 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005281 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005282 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005283 return NI;
5284 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005285 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5286 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005287 return NI;
5288
Reid Spencer266e42b2006-12-23 06:05:41 +00005289 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005290 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5291 // now.
5292 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5293 if (isa<PointerType>(Op0->getType()) &&
5294 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005295 // We keep moving the cast from the left operand over to the right
5296 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005297 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005298
Chris Lattner64d87b02007-01-06 01:45:59 +00005299 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5300 // so eliminate it as well.
5301 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5302 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005303
Chris Lattner16930792003-11-03 04:25:02 +00005304 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005305 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005306 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005307 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005308 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005309 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005310 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005311 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005312 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005313 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005314 }
5315
5316 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005317 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005318 // This comes up when you have code like
5319 // int X = A < B;
5320 // if (X) ...
5321 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005322 // with a constant or another cast from the same type.
5323 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005324 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005325 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005326 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005327
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005328 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005329 Value *A, *B, *C, *D;
5330 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5331 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5332 Value *OtherVal = A == Op1 ? B : A;
5333 return new ICmpInst(I.getPredicate(), OtherVal,
5334 Constant::getNullValue(A->getType()));
5335 }
5336
5337 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5338 // A^c1 == C^c2 --> A == C^(c1^c2)
5339 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5340 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5341 if (Op1->hasOneUse()) {
5342 Constant *NC = ConstantExpr::getXor(C1, C2);
5343 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5344 return new ICmpInst(I.getPredicate(), A,
5345 InsertNewInstBefore(Xor, I));
5346 }
5347
5348 // A^B == A^D -> B == D
5349 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5350 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5351 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5352 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5353 }
5354 }
5355
5356 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5357 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005358 // A == (A^B) -> B == 0
5359 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005360 return new ICmpInst(I.getPredicate(), OtherVal,
5361 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005362 }
5363 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005364 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005365 return new ICmpInst(I.getPredicate(), B,
5366 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005367 }
5368 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005369 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005370 return new ICmpInst(I.getPredicate(), B,
5371 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005372 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005373
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005374 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5375 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5376 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5377 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5378 Value *X = 0, *Y = 0, *Z = 0;
5379
5380 if (A == C) {
5381 X = B; Y = D; Z = A;
5382 } else if (A == D) {
5383 X = B; Y = C; Z = A;
5384 } else if (B == C) {
5385 X = A; Y = D; Z = B;
5386 } else if (B == D) {
5387 X = A; Y = C; Z = B;
5388 }
5389
5390 if (X) { // Build (X^Y) & Z
5391 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5392 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5393 I.setOperand(0, Op1);
5394 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5395 return &I;
5396 }
5397 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005398 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005399 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005400}
5401
Reid Spencer266e42b2006-12-23 06:05:41 +00005402// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005403// We only handle extending casts so far.
5404//
Reid Spencer266e42b2006-12-23 06:05:41 +00005405Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5406 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005407 Value *LHSCIOp = LHSCI->getOperand(0);
5408 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005409 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005410 Value *RHSCIOp;
5411
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 // We only handle extension cast instructions, so far. Enforce this.
5413 if (LHSCI->getOpcode() != Instruction::ZExt &&
5414 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005415 return 0;
5416
Reid Spencer266e42b2006-12-23 06:05:41 +00005417 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5418 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005419
Reid Spencer266e42b2006-12-23 06:05:41 +00005420 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005421 // Not an extension from the same type?
5422 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005423 if (RHSCIOp->getType() != LHSCIOp->getType())
5424 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005425
5426 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5427 // and the other is a zext), then we can't handle this.
5428 if (CI->getOpcode() != LHSCI->getOpcode())
5429 return 0;
5430
5431 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5432 // then we can't handle this.
5433 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5434 return 0;
5435
5436 // Okay, just insert a compare of the reduced operands now!
5437 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005438 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005439
Reid Spencer266e42b2006-12-23 06:05:41 +00005440 // If we aren't dealing with a constant on the RHS, exit early
5441 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5442 if (!CI)
5443 return 0;
5444
5445 // Compute the constant that would happen if we truncated to SrcTy then
5446 // reextended to DestTy.
5447 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5448 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5449
5450 // If the re-extended constant didn't change...
5451 if (Res2 == CI) {
5452 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5453 // For example, we might have:
5454 // %A = sext short %X to uint
5455 // %B = icmp ugt uint %A, 1330
5456 // It is incorrect to transform this into
5457 // %B = icmp ugt short %X, 1330
5458 // because %A may have negative value.
5459 //
5460 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5461 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005462 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005463 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5464 else
5465 return 0;
5466 }
5467
5468 // The re-extended constant changed so the constant cannot be represented
5469 // in the shorter type. Consequently, we cannot emit a simple comparison.
5470
5471 // First, handle some easy cases. We know the result cannot be equal at this
5472 // point so handle the ICI.isEquality() cases
5473 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005474 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005475 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005476 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005477
5478 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5479 // should have been folded away previously and not enter in here.
5480 Value *Result;
5481 if (isSignedCmp) {
5482 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005483 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005484 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005485 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005486 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005487 } else {
5488 // We're performing an unsigned comparison.
5489 if (isSignedExt) {
5490 // We're performing an unsigned comp with a sign extended value.
5491 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005492 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005493 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5494 NegOne, ICI.getName()), ICI);
5495 } else {
5496 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005497 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005498 }
5499 }
5500
5501 // Finally, return the value computed.
5502 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5503 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5504 return ReplaceInstUsesWith(ICI, Result);
5505 } else {
5506 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5507 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5508 "ICmp should be folded!");
5509 if (Constant *CI = dyn_cast<Constant>(Result))
5510 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5511 else
5512 return BinaryOperator::createNot(Result);
5513 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005514}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005515
Reid Spencer2341c222007-02-02 02:16:23 +00005516Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5517 return commonShiftTransforms(I);
5518}
5519
5520Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5521 return commonShiftTransforms(I);
5522}
5523
5524Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5525 return commonShiftTransforms(I);
5526}
5527
5528Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5529 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005530 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005531
5532 // shl X, 0 == X and shr X, 0 == X
5533 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005534 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005535 Op0 == Constant::getNullValue(Op0->getType()))
5536 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005537
Reid Spencer266e42b2006-12-23 06:05:41 +00005538 if (isa<UndefValue>(Op0)) {
5539 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005540 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005541 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005542 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5543 }
5544 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005545 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5546 return ReplaceInstUsesWith(I, Op0);
5547 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005549 }
5550
Chris Lattnerd4dee402006-11-10 23:38:52 +00005551 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5552 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005553 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005554 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005555 return ReplaceInstUsesWith(I, CSI);
5556
Chris Lattner183b3362004-04-09 19:05:30 +00005557 // Try to fold constant and into select arguments.
5558 if (isa<Constant>(Op0))
5559 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005560 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005561 return R;
5562
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005563 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005564 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005565 if (MaskedValueIsZero(Op0,
5566 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005567 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005568 }
5569 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005570
Reid Spencere0fc4df2006-10-20 07:07:24 +00005571 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005572 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5573 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005574 return 0;
5575}
5576
Reid Spencere0fc4df2006-10-20 07:07:24 +00005577Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005578 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005579 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005580
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005581 // See if we can simplify any instructions used by the instruction whose sole
5582 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005583 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5584 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5585 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005586 KnownZero, KnownOne))
5587 return &I;
5588
Chris Lattner14553932006-01-06 07:12:35 +00005589 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5590 // of a signed value.
5591 //
Reid Spencer6274c722007-03-23 18:46:34 +00005592 if (Op1->getZExtValue() >= TypeBits) { // shift amount always <= 32 bits
Chris Lattnerd5fea612007-02-02 05:29:55 +00005593 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005594 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5595 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005596 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005597 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005598 }
Chris Lattner14553932006-01-06 07:12:35 +00005599 }
5600
5601 // ((X*C1) << C2) == (X * (C1 << C2))
5602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5603 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5604 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5605 return BinaryOperator::createMul(BO->getOperand(0),
5606 ConstantExpr::getShl(BOOp, Op1));
5607
5608 // Try to fold constant and into select arguments.
5609 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5610 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5611 return R;
5612 if (isa<PHINode>(Op0))
5613 if (Instruction *NV = FoldOpIntoPhi(I))
5614 return NV;
5615
5616 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005617 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5618 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5619 Value *V1, *V2;
5620 ConstantInt *CC;
5621 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005622 default: break;
5623 case Instruction::Add:
5624 case Instruction::And:
5625 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005626 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005627 // These operators commute.
5628 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005629 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5630 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005631 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005632 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005633 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005634 Op0BO->getName());
5635 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005636 Instruction *X =
5637 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5638 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005639 InsertNewInstBefore(X, I); // (X + (Y << C))
5640 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005641 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005642 return BinaryOperator::createAnd(X, C2);
5643 }
Chris Lattner14553932006-01-06 07:12:35 +00005644
Chris Lattner797dee72005-09-18 06:30:59 +00005645 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005646 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005647 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005648 match(Op0BOOp1,
5649 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005650 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5651 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005652 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005653 Op0BO->getOperand(0), Op1,
5654 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005655 InsertNewInstBefore(YS, I); // (Y << C)
5656 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005657 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005658 V1->getName()+".mask");
5659 InsertNewInstBefore(XM, I); // X & (CC << C)
5660
5661 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5662 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005663 }
Chris Lattner14553932006-01-06 07:12:35 +00005664
Reid Spencer2f34b982007-02-02 14:41:37 +00005665 // FALL THROUGH.
5666 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005667 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005668 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5669 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005670 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005671 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005672 Op0BO->getOperand(1), Op1,
5673 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005674 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005675 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005676 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005677 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005678 InsertNewInstBefore(X, I); // (X + (Y << C))
5679 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005680 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005681 return BinaryOperator::createAnd(X, C2);
5682 }
Chris Lattner14553932006-01-06 07:12:35 +00005683
Chris Lattner1df0e982006-05-31 21:14:00 +00005684 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005685 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5686 match(Op0BO->getOperand(0),
5687 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005688 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005689 cast<BinaryOperator>(Op0BO->getOperand(0))
5690 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005691 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005692 Op0BO->getOperand(1), Op1,
5693 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005694 InsertNewInstBefore(YS, I); // (Y << C)
5695 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005696 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005697 V1->getName()+".mask");
5698 InsertNewInstBefore(XM, I); // X & (CC << C)
5699
Chris Lattner1df0e982006-05-31 21:14:00 +00005700 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005701 }
Chris Lattner14553932006-01-06 07:12:35 +00005702
Chris Lattner27cb9db2005-09-18 05:12:10 +00005703 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005704 }
Chris Lattner14553932006-01-06 07:12:35 +00005705 }
5706
5707
5708 // If the operand is an bitwise operator with a constant RHS, and the
5709 // shift is the only use, we can pull it out of the shift.
5710 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5711 bool isValid = true; // Valid only for And, Or, Xor
5712 bool highBitSet = false; // Transform if high bit of constant set?
5713
5714 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005715 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005716 case Instruction::Add:
5717 isValid = isLeftShift;
5718 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005719 case Instruction::Or:
5720 case Instruction::Xor:
5721 highBitSet = false;
5722 break;
5723 case Instruction::And:
5724 highBitSet = true;
5725 break;
Chris Lattner14553932006-01-06 07:12:35 +00005726 }
5727
5728 // If this is a signed shift right, and the high bit is modified
5729 // by the logical operation, do not perform the transformation.
5730 // The highBitSet boolean indicates the value of the high bit of
5731 // the constant which would cause it to be modified for this
5732 // operation.
5733 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005734 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencer6274c722007-03-23 18:46:34 +00005735 APInt Val(Op0C->getValue());
5736 isValid = ((Val & APInt::getSignBit(TypeBits)) != 0) == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005737 }
5738
5739 if (isValid) {
5740 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5741
5742 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005743 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005744 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005745 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005746
5747 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5748 NewRHS);
5749 }
5750 }
5751 }
5752 }
5753
Chris Lattnereb372a02006-01-06 07:52:12 +00005754 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005755 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5756 if (ShiftOp && !ShiftOp->isShift())
5757 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005758
Reid Spencere0fc4df2006-10-20 07:07:24 +00005759 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005760 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencer6274c722007-03-23 18:46:34 +00005761 // shift amount always <= 32 bits
Reid Spencere0fc4df2006-10-20 07:07:24 +00005762 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5763 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005764 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5765 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5766 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005767
Chris Lattner3e009e82007-02-05 00:57:54 +00005768 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005769 if (AmtSum > TypeBits)
5770 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005771
5772 const IntegerType *Ty = cast<IntegerType>(I.getType());
5773
5774 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005775 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005776 return BinaryOperator::create(I.getOpcode(), X,
5777 ConstantInt::get(Ty, AmtSum));
5778 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5779 I.getOpcode() == Instruction::AShr) {
5780 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5781 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5782 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5783 I.getOpcode() == Instruction::LShr) {
5784 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5785 Instruction *Shift =
5786 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5787 InsertNewInstBefore(Shift, I);
5788
Reid Spencer6274c722007-03-23 18:46:34 +00005789 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt2));
5790 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005791 }
5792
Chris Lattner3e009e82007-02-05 00:57:54 +00005793 // Okay, if we get here, one shift must be left, and the other shift must be
5794 // right. See if the amounts are equal.
5795 if (ShiftAmt1 == ShiftAmt2) {
5796 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5797 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer6274c722007-03-23 18:46:34 +00005798 APInt Mask(APInt::getAllOnesValue(TypeBits).shl(ShiftAmt1));
5799 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005800 }
5801 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5802 if (I.getOpcode() == Instruction::LShr) {
Reid Spencer6274c722007-03-23 18:46:34 +00005803 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt1));
5804 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005805 }
5806 // We can simplify ((X << C) >>s C) into a trunc + sext.
5807 // NOTE: we could do this for any C, but that would make 'unusual' integer
5808 // types. For now, just stick to ones well-supported by the code
5809 // generators.
5810 const Type *SExtType = 0;
5811 switch (Ty->getBitWidth() - ShiftAmt1) {
Reid Spencer6274c722007-03-23 18:46:34 +00005812 case 1 : SExtType = Type::Int1Ty; break;
5813 case 8 : SExtType = Type::Int8Ty; break;
5814 case 16 : SExtType = Type::Int16Ty; break;
5815 case 32 : SExtType = Type::Int32Ty; break;
5816 case 64 : SExtType = Type::Int64Ty; break;
5817 case 128: SExtType = IntegerType::get(128); break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005818 default: break;
5819 }
5820 if (SExtType) {
5821 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5822 InsertNewInstBefore(NewTrunc, I);
5823 return new SExtInst(NewTrunc, Ty);
5824 }
5825 // Otherwise, we can't handle it yet.
5826 } else if (ShiftAmt1 < ShiftAmt2) {
5827 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005828
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005829 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005830 if (I.getOpcode() == Instruction::Shl) {
5831 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5832 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005833 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005834 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005835 InsertNewInstBefore(Shift, I);
5836
Reid Spencer6274c722007-03-23 18:46:34 +00005837 APInt Mask(APInt::getAllOnesValue(TypeBits).shl(ShiftAmt2));
5838 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005839 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005840
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005841 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005842 if (I.getOpcode() == Instruction::LShr) {
5843 assert(ShiftOp->getOpcode() == Instruction::Shl);
5844 Instruction *Shift =
5845 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5846 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005847
Reid Spencer6274c722007-03-23 18:46:34 +00005848 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt2));
5849 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005850 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005851
5852 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5853 } else {
5854 assert(ShiftAmt2 < ShiftAmt1);
5855 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5856
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005857 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005858 if (I.getOpcode() == Instruction::Shl) {
5859 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5860 ShiftOp->getOpcode() == Instruction::AShr);
5861 Instruction *Shift =
5862 BinaryOperator::create(ShiftOp->getOpcode(), X,
5863 ConstantInt::get(Ty, ShiftDiff));
5864 InsertNewInstBefore(Shift, I);
5865
Reid Spencer6274c722007-03-23 18:46:34 +00005866 APInt Mask(APInt::getAllOnesValue(TypeBits).shl(ShiftAmt2));
5867 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005868 }
5869
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005870 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005871 if (I.getOpcode() == Instruction::LShr) {
5872 assert(ShiftOp->getOpcode() == Instruction::Shl);
5873 Instruction *Shift =
5874 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5875 InsertNewInstBefore(Shift, I);
5876
Reid Spencer6274c722007-03-23 18:46:34 +00005877 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt2));
5878 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005879 }
5880
5881 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005882 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005883 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005884 return 0;
5885}
5886
Chris Lattner48a44f72002-05-02 17:06:02 +00005887
Chris Lattner8f663e82005-10-29 04:36:15 +00005888/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5889/// expression. If so, decompose it, returning some value X, such that Val is
5890/// X*Scale+Offset.
5891///
5892static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5893 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005894 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005895 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005896 Offset = CI->getZExtValue();
5897 Scale = 1;
5898 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005899 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5900 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005901 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005902 if (I->getOpcode() == Instruction::Shl) {
5903 // This is a value scaled by '1 << the shift amt'.
5904 Scale = 1U << CUI->getZExtValue();
5905 Offset = 0;
5906 return I->getOperand(0);
5907 } else if (I->getOpcode() == Instruction::Mul) {
5908 // This value is scaled by 'CUI'.
5909 Scale = CUI->getZExtValue();
5910 Offset = 0;
5911 return I->getOperand(0);
5912 } else if (I->getOpcode() == Instruction::Add) {
5913 // We have X+C. Check to see if we really have (X*C2)+C1,
5914 // where C1 is divisible by C2.
5915 unsigned SubScale;
5916 Value *SubVal =
5917 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5918 Offset += CUI->getZExtValue();
5919 if (SubScale > 1 && (Offset % SubScale == 0)) {
5920 Scale = SubScale;
5921 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005922 }
5923 }
5924 }
5925 }
5926 }
5927
5928 // Otherwise, we can't look past this.
5929 Scale = 1;
5930 Offset = 0;
5931 return Val;
5932}
5933
5934
Chris Lattner216be912005-10-24 06:03:58 +00005935/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5936/// try to eliminate the cast by moving the type information into the alloc.
5937Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5938 AllocationInst &AI) {
5939 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005940 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005941
Chris Lattnerac87beb2005-10-24 06:22:12 +00005942 // Remove any uses of AI that are dead.
5943 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005944
Chris Lattnerac87beb2005-10-24 06:22:12 +00005945 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5946 Instruction *User = cast<Instruction>(*UI++);
5947 if (isInstructionTriviallyDead(User)) {
5948 while (UI != E && *UI == User)
5949 ++UI; // If this instruction uses AI more than once, don't break UI.
5950
Chris Lattnerac87beb2005-10-24 06:22:12 +00005951 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005952 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005953 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005954 }
5955 }
5956
Chris Lattner216be912005-10-24 06:03:58 +00005957 // Get the type really allocated and the type casted to.
5958 const Type *AllocElTy = AI.getAllocatedType();
5959 const Type *CastElTy = PTy->getElementType();
5960 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005961
Chris Lattner945e4372007-02-14 05:52:17 +00005962 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5963 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005964 if (CastElTyAlign < AllocElTyAlign) return 0;
5965
Chris Lattner46705b22005-10-24 06:35:18 +00005966 // If the allocation has multiple uses, only promote it if we are strictly
5967 // increasing the alignment of the resultant allocation. If we keep it the
5968 // same, we open the door to infinite loops of various kinds.
5969 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5970
Chris Lattner216be912005-10-24 06:03:58 +00005971 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5972 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005973 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005974
Chris Lattner8270c332005-10-29 03:19:53 +00005975 // See if we can satisfy the modulus by pulling a scale out of the array
5976 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005977 unsigned ArraySizeScale, ArrayOffset;
5978 Value *NumElements = // See if the array size is a decomposable linear expr.
5979 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5980
Chris Lattner8270c332005-10-29 03:19:53 +00005981 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5982 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005983 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5984 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005985
Chris Lattner8270c332005-10-29 03:19:53 +00005986 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5987 Value *Amt = 0;
5988 if (Scale == 1) {
5989 Amt = NumElements;
5990 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005991 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005992 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5993 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005994 Amt = ConstantExpr::getMul(
5995 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5996 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005997 else if (Scale != 1) {
5998 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5999 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006000 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006001 }
6002
Chris Lattner8f663e82005-10-29 04:36:15 +00006003 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006004 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006005 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6006 Amt = InsertNewInstBefore(Tmp, AI);
6007 }
6008
Chris Lattner216be912005-10-24 06:03:58 +00006009 AllocationInst *New;
6010 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006011 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006012 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006013 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006014 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006015 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006016
6017 // If the allocation has multiple uses, insert a cast and change all things
6018 // that used it to use the new cast. This will also hack on CI, but it will
6019 // die soon.
6020 if (!AI.hasOneUse()) {
6021 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006022 // New is the allocation instruction, pointer typed. AI is the original
6023 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6024 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006025 InsertNewInstBefore(NewCast, AI);
6026 AI.replaceAllUsesWith(NewCast);
6027 }
Chris Lattner216be912005-10-24 06:03:58 +00006028 return ReplaceInstUsesWith(CI, New);
6029}
6030
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006031/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006032/// and return it as type Ty without inserting any new casts and without
6033/// changing the computed value. This is used by code that tries to decide
6034/// whether promoting or shrinking integer operations to wider or smaller types
6035/// will allow us to eliminate a truncate or extend.
6036///
6037/// This is a truncation operation if Ty is smaller than V->getType(), or an
6038/// extension operation if Ty is larger.
6039static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006040 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006041 // We can always evaluate constants in another type.
6042 if (isa<ConstantInt>(V))
6043 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006044
6045 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006046 if (!I) return false;
6047
6048 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006049
6050 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006051 case Instruction::Add:
6052 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006053 case Instruction::And:
6054 case Instruction::Or:
6055 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006056 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006057 // These operators can all arbitrarily be extended or truncated.
6058 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6059 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006060
Chris Lattner960acb02006-11-29 07:18:39 +00006061 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006062 if (!I->hasOneUse()) return false;
6063 // If we are truncating the result of this SHL, and if it's a shift of a
6064 // constant amount, we can always perform a SHL in a smaller type.
6065 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6066 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6067 CI->getZExtValue() < Ty->getBitWidth())
6068 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6069 }
6070 break;
6071 case Instruction::LShr:
6072 if (!I->hasOneUse()) return false;
6073 // If this is a truncate of a logical shr, we can truncate it to a smaller
6074 // lshr iff we know that the bits we would otherwise be shifting in are
6075 // already zeros.
6076 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006077 uint32_t BitWidth = OrigTy->getBitWidth();
Zhou Sheng755f04b2007-03-23 02:39:25 +00006078 if (Ty->getBitWidth() < BitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006079 MaskedValueIsZero(I->getOperand(0),
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006080 APInt::getAllOnesValue(BitWidth) &
6081 APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6082 && CI->getZExtValue() < Ty->getBitWidth()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006083 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6084 }
6085 }
Chris Lattner960acb02006-11-29 07:18:39 +00006086 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006087 case Instruction::Trunc:
6088 case Instruction::ZExt:
6089 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006090 // If this is a cast from the destination type, we can trivially eliminate
6091 // it, and this will remove a cast overall.
6092 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006093 // If the first operand is itself a cast, and is eliminable, do not count
6094 // this as an eliminable cast. We would prefer to eliminate those two
6095 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006096 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006097 return true;
6098
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006099 ++NumCastsRemoved;
6100 return true;
6101 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006102 break;
6103 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006104 // TODO: Can handle more cases here.
6105 break;
6106 }
6107
6108 return false;
6109}
6110
6111/// EvaluateInDifferentType - Given an expression that
6112/// CanEvaluateInDifferentType returns true for, actually insert the code to
6113/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006114Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006115 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006116 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006117 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006118
6119 // Otherwise, it must be an instruction.
6120 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006121 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006122 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006123 case Instruction::Add:
6124 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006125 case Instruction::And:
6126 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006127 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006128 case Instruction::AShr:
6129 case Instruction::LShr:
6130 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006131 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006132 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6133 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6134 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006135 break;
6136 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006137 case Instruction::Trunc:
6138 case Instruction::ZExt:
6139 case Instruction::SExt:
6140 case Instruction::BitCast:
6141 // If the source type of the cast is the type we're trying for then we can
6142 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006143 if (I->getOperand(0)->getType() == Ty)
6144 return I->getOperand(0);
6145
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006146 // Some other kind of cast, which shouldn't happen, so just ..
6147 // FALL THROUGH
6148 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006149 // TODO: Can handle more cases here.
6150 assert(0 && "Unreachable!");
6151 break;
6152 }
6153
6154 return InsertNewInstBefore(Res, *I);
6155}
6156
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006157/// @brief Implement the transforms common to all CastInst visitors.
6158Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006159 Value *Src = CI.getOperand(0);
6160
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006161 // Casting undef to anything results in undef so might as just replace it and
6162 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006163 if (isa<UndefValue>(Src)) // cast undef -> undef
6164 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6165
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006166 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6167 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006168 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006169 if (Instruction::CastOps opc =
6170 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6171 // The first cast (CSrc) is eliminable so we need to fix up or replace
6172 // the second cast (CI). CSrc will then have a good chance of being dead.
6173 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006174 }
6175 }
Chris Lattner03841652004-05-25 04:29:21 +00006176
Chris Lattnerd0d51602003-06-21 23:12:02 +00006177 // If casting the result of a getelementptr instruction with no offset, turn
6178 // this into a cast of the original pointer!
6179 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006180 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006181 bool AllZeroOperands = true;
6182 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6183 if (!isa<Constant>(GEP->getOperand(i)) ||
6184 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6185 AllZeroOperands = false;
6186 break;
6187 }
6188 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006189 // Changing the cast operand is usually not a good idea but it is safe
6190 // here because the pointer operand is being replaced with another
6191 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006192 CI.setOperand(0, GEP->getOperand(0));
6193 return &CI;
6194 }
6195 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006196
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006197 // If we are casting a malloc or alloca to a pointer to a type of the same
6198 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006199 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006200 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6201 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006202
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006203 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006204 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6205 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6206 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006207
6208 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006209 if (isa<PHINode>(Src))
6210 if (Instruction *NV = FoldOpIntoPhi(CI))
6211 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006212
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006213 return 0;
6214}
6215
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006216/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6217/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006218/// cases.
6219/// @brief Implement the transforms common to CastInst with integer operands
6220Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6221 if (Instruction *Result = commonCastTransforms(CI))
6222 return Result;
6223
6224 Value *Src = CI.getOperand(0);
6225 const Type *SrcTy = Src->getType();
6226 const Type *DestTy = CI.getType();
6227 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6228 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6229
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006230 // See if we can simplify any instructions used by the LHS whose sole
6231 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006232 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6233 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006234 KnownZero, KnownOne))
6235 return &CI;
6236
6237 // If the source isn't an instruction or has more than one use then we
6238 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006239 Instruction *SrcI = dyn_cast<Instruction>(Src);
6240 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006241 return 0;
6242
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006243 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006244 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006245 if (!isa<BitCastInst>(CI) &&
6246 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6247 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006248 // If this cast is a truncate, evaluting in a different type always
6249 // eliminates the cast, so it is always a win. If this is a noop-cast
6250 // this just removes a noop cast which isn't pointful, but simplifies
6251 // the code. If this is a zero-extension, we need to do an AND to
6252 // maintain the clear top-part of the computation, so we require that
6253 // the input have eliminated at least one cast. If this is a sign
6254 // extension, we insert two new casts (to do the extension) so we
6255 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006256 bool DoXForm;
6257 switch (CI.getOpcode()) {
6258 default:
6259 // All the others use floating point so we shouldn't actually
6260 // get here because of the check above.
6261 assert(0 && "Unknown cast type");
6262 case Instruction::Trunc:
6263 DoXForm = true;
6264 break;
6265 case Instruction::ZExt:
6266 DoXForm = NumCastsRemoved >= 1;
6267 break;
6268 case Instruction::SExt:
6269 DoXForm = NumCastsRemoved >= 2;
6270 break;
6271 case Instruction::BitCast:
6272 DoXForm = false;
6273 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006274 }
6275
6276 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006277 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6278 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006279 assert(Res->getType() == DestTy);
6280 switch (CI.getOpcode()) {
6281 default: assert(0 && "Unknown cast type!");
6282 case Instruction::Trunc:
6283 case Instruction::BitCast:
6284 // Just replace this cast with the result.
6285 return ReplaceInstUsesWith(CI, Res);
6286 case Instruction::ZExt: {
6287 // We need to emit an AND to clear the high bits.
6288 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencer4154e732007-03-22 20:56:53 +00006289 Constant *C = ConstantInt::get(APInt::getAllOnesValue(SrcBitSize));
6290 C = ConstantExpr::getZExt(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006291 return BinaryOperator::createAnd(Res, C);
6292 }
6293 case Instruction::SExt:
6294 // We need to emit a cast to truncate, then a cast to sext.
6295 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006296 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6297 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006298 }
6299 }
6300 }
6301
6302 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6303 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6304
6305 switch (SrcI->getOpcode()) {
6306 case Instruction::Add:
6307 case Instruction::Mul:
6308 case Instruction::And:
6309 case Instruction::Or:
6310 case Instruction::Xor:
6311 // If we are discarding information, or just changing the sign,
6312 // rewrite.
6313 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6314 // Don't insert two casts if they cannot be eliminated. We allow
6315 // two casts to be inserted if the sizes are the same. This could
6316 // only be converting signedness, which is a noop.
6317 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006318 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6319 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006320 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006321 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6322 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6323 return BinaryOperator::create(
6324 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006325 }
6326 }
6327
6328 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6329 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6330 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006331 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006332 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006333 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006334 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6335 }
6336 break;
6337 case Instruction::SDiv:
6338 case Instruction::UDiv:
6339 case Instruction::SRem:
6340 case Instruction::URem:
6341 // If we are just changing the sign, rewrite.
6342 if (DestBitSize == SrcBitSize) {
6343 // Don't insert two casts if they cannot be eliminated. We allow
6344 // two casts to be inserted if the sizes are the same. This could
6345 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006346 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6347 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006348 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6349 Op0, DestTy, SrcI);
6350 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6351 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006352 return BinaryOperator::create(
6353 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6354 }
6355 }
6356 break;
6357
6358 case Instruction::Shl:
6359 // Allow changing the sign of the source operand. Do not allow
6360 // changing the size of the shift, UNLESS the shift amount is a
6361 // constant. We must not change variable sized shifts to a smaller
6362 // size, because it is undefined to shift more bits out than exist
6363 // in the value.
6364 if (DestBitSize == SrcBitSize ||
6365 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006366 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6367 Instruction::BitCast : Instruction::Trunc);
6368 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006369 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006370 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006371 }
6372 break;
6373 case Instruction::AShr:
6374 // If this is a signed shr, and if all bits shifted in are about to be
6375 // truncated off, turn it into an unsigned shr to allow greater
6376 // simplifications.
6377 if (DestBitSize < SrcBitSize &&
6378 isa<ConstantInt>(Op1)) {
6379 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6380 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6381 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006382 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006383 }
6384 }
6385 break;
6386
Reid Spencer266e42b2006-12-23 06:05:41 +00006387 case Instruction::ICmp:
6388 // If we are just checking for a icmp eq of a single bit and casting it
6389 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006390 // cast to integer to avoid the comparison.
6391 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer4154e732007-03-22 20:56:53 +00006392 APInt Op1CV(Op1C->getValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006393 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6394 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6395 // cast (X == 1) to int --> X iff X has only the low bit set.
6396 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6397 // cast (X != 0) to int --> X iff X has only the low bit set.
6398 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6399 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6400 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006401 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006402 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006403 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6404 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6405 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006406 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006407
6408 // This only works for EQ and NE
6409 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6410 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6411 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006412
Zhou Sheng0900993e2007-03-23 03:13:21 +00006413 APInt KnownZeroMask(KnownZero ^ TypeMask);
6414 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006415 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006416 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006417 // (X&4) == 2 --> false
6418 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006419 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006420 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006421 return ReplaceInstUsesWith(CI, Res);
6422 }
6423
Zhou Sheng0900993e2007-03-23 03:13:21 +00006424 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006425 Value *In = Op0;
6426 if (ShiftAmt) {
6427 // Perform a logical shr by shiftamt.
6428 // Insert the shift to put the result in the low bit.
6429 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006430 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006431 ConstantInt::get(In->getType(), ShiftAmt),
6432 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006433 }
6434
Reid Spencer266e42b2006-12-23 06:05:41 +00006435 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006436 Constant *One = ConstantInt::get(In->getType(), 1);
6437 In = BinaryOperator::createXor(In, One, "tmp");
6438 InsertNewInstBefore(cast<Instruction>(In), CI);
6439 }
6440
6441 if (CI.getType() == In->getType())
6442 return ReplaceInstUsesWith(CI, In);
6443 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006444 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006445 }
6446 }
6447 }
6448 break;
6449 }
6450 return 0;
6451}
6452
6453Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006454 if (Instruction *Result = commonIntCastTransforms(CI))
6455 return Result;
6456
6457 Value *Src = CI.getOperand(0);
6458 const Type *Ty = CI.getType();
6459 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00006460 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006461
6462 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6463 switch (SrcI->getOpcode()) {
6464 default: break;
6465 case Instruction::LShr:
6466 // We can shrink lshr to something smaller if we know the bits shifted in
6467 // are already zeros.
6468 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6469 unsigned ShAmt = ShAmtV->getZExtValue();
6470
6471 // Get a mask for the bits shifting in.
Reid Spencer4154e732007-03-22 20:56:53 +00006472 APInt Mask(APInt::getAllOnesValue(SrcBitWidth).lshr(
6473 SrcBitWidth-ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006474 Value* SrcIOp0 = SrcI->getOperand(0);
6475 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006476 if (ShAmt >= DestBitWidth) // All zeros.
6477 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6478
6479 // Okay, we can shrink this. Truncate the input, then return a new
6480 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006481 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6482 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6483 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006484 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006485 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006486 } else { // This is a variable shr.
6487
6488 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6489 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6490 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006491 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006492 Value *One = ConstantInt::get(SrcI->getType(), 1);
6493
Reid Spencer2341c222007-02-02 02:16:23 +00006494 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006495 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006496 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006497 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6498 SrcI->getOperand(0),
6499 "tmp"), CI);
6500 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006501 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006502 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006503 }
6504 break;
6505 }
6506 }
6507
6508 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006509}
6510
6511Instruction *InstCombiner::visitZExt(CastInst &CI) {
6512 // If one of the common conversion will work ..
6513 if (Instruction *Result = commonIntCastTransforms(CI))
6514 return Result;
6515
6516 Value *Src = CI.getOperand(0);
6517
6518 // If this is a cast of a cast
6519 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006520 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6521 // types and if the sizes are just right we can convert this into a logical
6522 // 'and' which will be much cheaper than the pair of casts.
6523 if (isa<TruncInst>(CSrc)) {
6524 // Get the sizes of the types involved
6525 Value *A = CSrc->getOperand(0);
6526 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6527 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6528 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6529 // If we're actually extending zero bits and the trunc is a no-op
6530 if (MidSize < DstSize && SrcSize == DstSize) {
6531 // Replace both of the casts with an And of the type mask.
Reid Spencer4154e732007-03-22 20:56:53 +00006532 APInt AndValue(APInt::getAllOnesValue(MidSize).zext(SrcSize));
6533 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006534 Instruction *And =
6535 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6536 // Unfortunately, if the type changed, we need to cast it back.
6537 if (And->getType() != CI.getType()) {
6538 And->setName(CSrc->getName()+".mask");
6539 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006540 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006541 }
6542 return And;
6543 }
6544 }
6545 }
6546
6547 return 0;
6548}
6549
6550Instruction *InstCombiner::visitSExt(CastInst &CI) {
6551 return commonIntCastTransforms(CI);
6552}
6553
6554Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6555 return commonCastTransforms(CI);
6556}
6557
6558Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6559 return commonCastTransforms(CI);
6560}
6561
6562Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006563 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006564}
6565
6566Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006567 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006568}
6569
6570Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6571 return commonCastTransforms(CI);
6572}
6573
6574Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6575 return commonCastTransforms(CI);
6576}
6577
6578Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006579 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006580}
6581
6582Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6583 return commonCastTransforms(CI);
6584}
6585
6586Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6587
6588 // If the operands are integer typed then apply the integer transforms,
6589 // otherwise just apply the common ones.
6590 Value *Src = CI.getOperand(0);
6591 const Type *SrcTy = Src->getType();
6592 const Type *DestTy = CI.getType();
6593
Chris Lattner03c49532007-01-15 02:27:26 +00006594 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006595 if (Instruction *Result = commonIntCastTransforms(CI))
6596 return Result;
6597 } else {
6598 if (Instruction *Result = commonCastTransforms(CI))
6599 return Result;
6600 }
6601
6602
6603 // Get rid of casts from one type to the same type. These are useless and can
6604 // be replaced by the operand.
6605 if (DestTy == Src->getType())
6606 return ReplaceInstUsesWith(CI, Src);
6607
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006608 // If the source and destination are pointers, and this cast is equivalent to
6609 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6610 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006611 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6612 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6613 const Type *DstElTy = DstPTy->getElementType();
6614 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006615
Reid Spencerc635f472006-12-31 05:48:39 +00006616 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006617 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006618 while (SrcElTy != DstElTy &&
6619 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6620 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6621 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006622 ++NumZeros;
6623 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006624
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006625 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006626 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006627 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6628 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006629 }
6630 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006631 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006632
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006633 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6634 if (SVI->hasOneUse()) {
6635 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6636 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006637 if (isa<VectorType>(DestTy) &&
6638 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006639 SVI->getType()->getNumElements()) {
6640 CastInst *Tmp;
6641 // If either of the operands is a cast from CI.getType(), then
6642 // evaluating the shuffle in the casted destination's type will allow
6643 // us to eliminate at least one cast.
6644 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6645 Tmp->getOperand(0)->getType() == DestTy) ||
6646 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6647 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006648 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6649 SVI->getOperand(0), DestTy, &CI);
6650 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6651 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006652 // Return a new shuffle vector. Use the same element ID's, as we
6653 // know the vector types match #elts.
6654 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006655 }
6656 }
6657 }
6658 }
Chris Lattner260ab202002-04-18 17:39:14 +00006659 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006660}
6661
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006662/// GetSelectFoldableOperands - We want to turn code that looks like this:
6663/// %C = or %A, %B
6664/// %D = select %cond, %C, %A
6665/// into:
6666/// %C = select %cond, %B, 0
6667/// %D = or %A, %C
6668///
6669/// Assuming that the specified instruction is an operand to the select, return
6670/// a bitmask indicating which operands of this instruction are foldable if they
6671/// equal the other incoming value of the select.
6672///
6673static unsigned GetSelectFoldableOperands(Instruction *I) {
6674 switch (I->getOpcode()) {
6675 case Instruction::Add:
6676 case Instruction::Mul:
6677 case Instruction::And:
6678 case Instruction::Or:
6679 case Instruction::Xor:
6680 return 3; // Can fold through either operand.
6681 case Instruction::Sub: // Can only fold on the amount subtracted.
6682 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006683 case Instruction::LShr:
6684 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006685 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006686 default:
6687 return 0; // Cannot fold
6688 }
6689}
6690
6691/// GetSelectFoldableConstant - For the same transformation as the previous
6692/// function, return the identity constant that goes into the select.
6693static Constant *GetSelectFoldableConstant(Instruction *I) {
6694 switch (I->getOpcode()) {
6695 default: assert(0 && "This cannot happen!"); abort();
6696 case Instruction::Add:
6697 case Instruction::Sub:
6698 case Instruction::Or:
6699 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006700 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006701 case Instruction::LShr:
6702 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006703 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006704 case Instruction::And:
6705 return ConstantInt::getAllOnesValue(I->getType());
6706 case Instruction::Mul:
6707 return ConstantInt::get(I->getType(), 1);
6708 }
6709}
6710
Chris Lattner411336f2005-01-19 21:50:18 +00006711/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6712/// have the same opcode and only one use each. Try to simplify this.
6713Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6714 Instruction *FI) {
6715 if (TI->getNumOperands() == 1) {
6716 // If this is a non-volatile load or a cast from the same type,
6717 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006718 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006719 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6720 return 0;
6721 } else {
6722 return 0; // unknown unary op.
6723 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006724
Chris Lattner411336f2005-01-19 21:50:18 +00006725 // Fold this by inserting a select from the input values.
6726 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6727 FI->getOperand(0), SI.getName()+".v");
6728 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006729 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6730 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006731 }
6732
Reid Spencer2341c222007-02-02 02:16:23 +00006733 // Only handle binary operators here.
6734 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006735 return 0;
6736
6737 // Figure out if the operations have any operands in common.
6738 Value *MatchOp, *OtherOpT, *OtherOpF;
6739 bool MatchIsOpZero;
6740 if (TI->getOperand(0) == FI->getOperand(0)) {
6741 MatchOp = TI->getOperand(0);
6742 OtherOpT = TI->getOperand(1);
6743 OtherOpF = FI->getOperand(1);
6744 MatchIsOpZero = true;
6745 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6746 MatchOp = TI->getOperand(1);
6747 OtherOpT = TI->getOperand(0);
6748 OtherOpF = FI->getOperand(0);
6749 MatchIsOpZero = false;
6750 } else if (!TI->isCommutative()) {
6751 return 0;
6752 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6753 MatchOp = TI->getOperand(0);
6754 OtherOpT = TI->getOperand(1);
6755 OtherOpF = FI->getOperand(0);
6756 MatchIsOpZero = true;
6757 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6758 MatchOp = TI->getOperand(1);
6759 OtherOpT = TI->getOperand(0);
6760 OtherOpF = FI->getOperand(1);
6761 MatchIsOpZero = true;
6762 } else {
6763 return 0;
6764 }
6765
6766 // If we reach here, they do have operations in common.
6767 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6768 OtherOpF, SI.getName()+".v");
6769 InsertNewInstBefore(NewSI, SI);
6770
6771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6772 if (MatchIsOpZero)
6773 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6774 else
6775 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006776 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006777 assert(0 && "Shouldn't get here");
6778 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006779}
6780
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006781Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006782 Value *CondVal = SI.getCondition();
6783 Value *TrueVal = SI.getTrueValue();
6784 Value *FalseVal = SI.getFalseValue();
6785
6786 // select true, X, Y -> X
6787 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006788 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006789 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006790
6791 // select C, X, X -> X
6792 if (TrueVal == FalseVal)
6793 return ReplaceInstUsesWith(SI, TrueVal);
6794
Chris Lattner81a7a232004-10-16 18:11:37 +00006795 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6796 return ReplaceInstUsesWith(SI, FalseVal);
6797 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6798 return ReplaceInstUsesWith(SI, TrueVal);
6799 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6800 if (isa<Constant>(TrueVal))
6801 return ReplaceInstUsesWith(SI, TrueVal);
6802 else
6803 return ReplaceInstUsesWith(SI, FalseVal);
6804 }
6805
Reid Spencer542964f2007-01-11 18:21:29 +00006806 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006807 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006808 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006809 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006810 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006811 } else {
6812 // Change: A = select B, false, C --> A = and !B, C
6813 Value *NotCond =
6814 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6815 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006816 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006817 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006818 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006819 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006820 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006821 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006822 } else {
6823 // Change: A = select B, C, true --> A = or !B, C
6824 Value *NotCond =
6825 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6826 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006827 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006828 }
6829 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006830 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006831
Chris Lattner183b3362004-04-09 19:05:30 +00006832 // Selecting between two integer constants?
6833 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6834 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6835 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006836 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006837 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006838 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006839 // select C, 0, 1 -> cast !C to int
6840 Value *NotCond =
6841 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006842 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006843 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006844 }
Chris Lattner35167c32004-06-09 07:59:58 +00006845
Reid Spencer266e42b2006-12-23 06:05:41 +00006846 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006847
Reid Spencer266e42b2006-12-23 06:05:41 +00006848 // (x <s 0) ? -1 : 0 -> ashr x, 31
6849 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006850 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006851 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6852 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006853 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006854 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006855 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006856 else {
6857 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006858 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006859 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006860 }
6861
6862 if (CanXForm) {
6863 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006864 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006865 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006866 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006867 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6868 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6869 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006870 InsertNewInstBefore(SRA, SI);
6871
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006872 // Finally, convert to the type of the select RHS. We figure out
6873 // if this requires a SExt, Trunc or BitCast based on the sizes.
6874 Instruction::CastOps opc = Instruction::BitCast;
6875 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6876 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6877 if (SRASize < SISize)
6878 opc = Instruction::SExt;
6879 else if (SRASize > SISize)
6880 opc = Instruction::Trunc;
6881 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006882 }
6883 }
6884
6885
6886 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006887 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006888 // non-constant value, eliminate this whole mess. This corresponds to
6889 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006890 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006891 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006892 cast<Constant>(IC->getOperand(1))->isNullValue())
6893 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6894 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006895 isa<ConstantInt>(ICA->getOperand(1)) &&
6896 (ICA->getOperand(1) == TrueValC ||
6897 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006898 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6899 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006900 // know whether we have a icmp_ne or icmp_eq and whether the
6901 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006902 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006903 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006904 Value *V = ICA;
6905 if (ShouldNotVal)
6906 V = InsertNewInstBefore(BinaryOperator::create(
6907 Instruction::Xor, V, ICA->getOperand(1)), SI);
6908 return ReplaceInstUsesWith(SI, V);
6909 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006910 }
Chris Lattner533bc492004-03-30 19:37:13 +00006911 }
Chris Lattner623fba12004-04-10 22:21:27 +00006912
6913 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006914 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6915 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006916 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006917 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006918 return ReplaceInstUsesWith(SI, FalseVal);
6919 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006920 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006921 return ReplaceInstUsesWith(SI, TrueVal);
6922 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6923
Reid Spencer266e42b2006-12-23 06:05:41 +00006924 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006925 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006926 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006927 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006928 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006929 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6930 return ReplaceInstUsesWith(SI, TrueVal);
6931 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6932 }
6933 }
6934
6935 // See if we are selecting two values based on a comparison of the two values.
6936 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6937 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6938 // Transform (X == Y) ? X : Y -> Y
6939 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6940 return ReplaceInstUsesWith(SI, FalseVal);
6941 // Transform (X != Y) ? X : Y -> X
6942 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6943 return ReplaceInstUsesWith(SI, TrueVal);
6944 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6945
6946 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6947 // Transform (X == Y) ? Y : X -> X
6948 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6949 return ReplaceInstUsesWith(SI, FalseVal);
6950 // Transform (X != Y) ? Y : X -> Y
6951 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006952 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006953 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6954 }
6955 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006956
Chris Lattnera04c9042005-01-13 22:52:24 +00006957 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6958 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6959 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006960 Instruction *AddOp = 0, *SubOp = 0;
6961
Chris Lattner411336f2005-01-19 21:50:18 +00006962 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6963 if (TI->getOpcode() == FI->getOpcode())
6964 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6965 return IV;
6966
6967 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6968 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006969 if (TI->getOpcode() == Instruction::Sub &&
6970 FI->getOpcode() == Instruction::Add) {
6971 AddOp = FI; SubOp = TI;
6972 } else if (FI->getOpcode() == Instruction::Sub &&
6973 TI->getOpcode() == Instruction::Add) {
6974 AddOp = TI; SubOp = FI;
6975 }
6976
6977 if (AddOp) {
6978 Value *OtherAddOp = 0;
6979 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6980 OtherAddOp = AddOp->getOperand(1);
6981 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6982 OtherAddOp = AddOp->getOperand(0);
6983 }
6984
6985 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006986 // So at this point we know we have (Y -> OtherAddOp):
6987 // select C, (add X, Y), (sub X, Z)
6988 Value *NegVal; // Compute -Z
6989 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6990 NegVal = ConstantExpr::getNeg(C);
6991 } else {
6992 NegVal = InsertNewInstBefore(
6993 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006994 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006995
6996 Value *NewTrueOp = OtherAddOp;
6997 Value *NewFalseOp = NegVal;
6998 if (AddOp != TI)
6999 std::swap(NewTrueOp, NewFalseOp);
7000 Instruction *NewSel =
7001 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7002
7003 NewSel = InsertNewInstBefore(NewSel, SI);
7004 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007005 }
7006 }
7007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007008
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007009 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007010 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007011 // See the comment above GetSelectFoldableOperands for a description of the
7012 // transformation we are doing here.
7013 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7014 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7015 !isa<Constant>(FalseVal))
7016 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7017 unsigned OpToFold = 0;
7018 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7019 OpToFold = 1;
7020 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7021 OpToFold = 2;
7022 }
7023
7024 if (OpToFold) {
7025 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007026 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007027 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007028 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007029 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7031 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007032 else {
7033 assert(0 && "Unknown instruction!!");
7034 }
7035 }
7036 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007037
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007038 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7039 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7040 !isa<Constant>(TrueVal))
7041 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7042 unsigned OpToFold = 0;
7043 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7044 OpToFold = 1;
7045 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7046 OpToFold = 2;
7047 }
7048
7049 if (OpToFold) {
7050 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007051 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007052 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007053 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007054 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007055 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7056 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007057 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007058 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007059 }
7060 }
7061 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007062
7063 if (BinaryOperator::isNot(CondVal)) {
7064 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7065 SI.setOperand(1, FalseVal);
7066 SI.setOperand(2, TrueVal);
7067 return &SI;
7068 }
7069
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007070 return 0;
7071}
7072
Chris Lattner82f2ef22006-03-06 20:18:44 +00007073/// GetKnownAlignment - If the specified pointer has an alignment that we can
7074/// determine, return it, otherwise return 0.
7075static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7076 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7077 unsigned Align = GV->getAlignment();
7078 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007079 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007080 return Align;
7081 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7082 unsigned Align = AI->getAlignment();
7083 if (Align == 0 && TD) {
7084 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007085 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007086 else if (isa<MallocInst>(AI)) {
7087 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007088 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007089 Align =
7090 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007091 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007092 Align =
7093 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007094 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007095 }
7096 }
7097 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007098 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007099 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007100 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007101 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007102 if (isa<PointerType>(CI->getOperand(0)->getType()))
7103 return GetKnownAlignment(CI->getOperand(0), TD);
7104 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007105 } else if (isa<GetElementPtrInst>(V) ||
7106 (isa<ConstantExpr>(V) &&
7107 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7108 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007109 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7110 if (BaseAlignment == 0) return 0;
7111
7112 // If all indexes are zero, it is just the alignment of the base pointer.
7113 bool AllZeroOperands = true;
7114 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7115 if (!isa<Constant>(GEPI->getOperand(i)) ||
7116 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7117 AllZeroOperands = false;
7118 break;
7119 }
7120 if (AllZeroOperands)
7121 return BaseAlignment;
7122
7123 // Otherwise, if the base alignment is >= the alignment we expect for the
7124 // base pointer type, then we know that the resultant pointer is aligned at
7125 // least as much as its type requires.
7126 if (!TD) return 0;
7127
7128 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007129 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007130 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007131 <= BaseAlignment) {
7132 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007133 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007134 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007135 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007136 return 0;
7137 }
7138 return 0;
7139}
7140
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007141
Chris Lattnerc66b2232006-01-13 20:11:04 +00007142/// visitCallInst - CallInst simplification. This mostly only handles folding
7143/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7144/// the heavy lifting.
7145///
Chris Lattner970c33a2003-06-19 17:00:31 +00007146Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007147 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7148 if (!II) return visitCallSite(&CI);
7149
Chris Lattner51ea1272004-02-28 05:22:00 +00007150 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7151 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007152 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007153 bool Changed = false;
7154
7155 // memmove/cpy/set of zero bytes is a noop.
7156 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7157 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7158
Chris Lattner00648e12004-10-12 04:52:52 +00007159 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007160 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007161 // Replace the instruction with just byte operations. We would
7162 // transform other cases to loads/stores, but we don't know if
7163 // alignment is sufficient.
7164 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007165 }
7166
Chris Lattner00648e12004-10-12 04:52:52 +00007167 // If we have a memmove and the source operation is a constant global,
7168 // then the source and dest pointers can't alias, so we can change this
7169 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007170 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007171 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7172 if (GVSrc->isConstant()) {
7173 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007174 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007175 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007176 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007177 Name = "llvm.memcpy.i32";
7178 else
7179 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007180 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007181 CI.getCalledFunction()->getFunctionType());
7182 CI.setOperand(0, MemCpy);
7183 Changed = true;
7184 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007185 }
Chris Lattner00648e12004-10-12 04:52:52 +00007186
Chris Lattner82f2ef22006-03-06 20:18:44 +00007187 // If we can determine a pointer alignment that is bigger than currently
7188 // set, update the alignment.
7189 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7190 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7191 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7192 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007193 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007194 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007195 Changed = true;
7196 }
7197 } else if (isa<MemSetInst>(MI)) {
7198 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007199 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007200 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007201 Changed = true;
7202 }
7203 }
7204
Chris Lattnerc66b2232006-01-13 20:11:04 +00007205 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007206 } else {
7207 switch (II->getIntrinsicID()) {
7208 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007209 case Intrinsic::ppc_altivec_lvx:
7210 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007211 case Intrinsic::x86_sse_loadu_ps:
7212 case Intrinsic::x86_sse2_loadu_pd:
7213 case Intrinsic::x86_sse2_loadu_dq:
7214 // Turn PPC lvx -> load if the pointer is known aligned.
7215 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007216 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007217 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007218 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007219 return new LoadInst(Ptr);
7220 }
7221 break;
7222 case Intrinsic::ppc_altivec_stvx:
7223 case Intrinsic::ppc_altivec_stvxl:
7224 // Turn stvx -> store if the pointer is known aligned.
7225 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007226 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007227 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7228 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007229 return new StoreInst(II->getOperand(1), Ptr);
7230 }
7231 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007232 case Intrinsic::x86_sse_storeu_ps:
7233 case Intrinsic::x86_sse2_storeu_pd:
7234 case Intrinsic::x86_sse2_storeu_dq:
7235 case Intrinsic::x86_sse2_storel_dq:
7236 // Turn X86 storeu -> store if the pointer is known aligned.
7237 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7238 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007239 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7240 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007241 return new StoreInst(II->getOperand(2), Ptr);
7242 }
7243 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007244
7245 case Intrinsic::x86_sse_cvttss2si: {
7246 // These intrinsics only demands the 0th element of its input vector. If
7247 // we can simplify the input based on that, do so now.
7248 uint64_t UndefElts;
7249 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7250 UndefElts)) {
7251 II->setOperand(1, V);
7252 return II;
7253 }
7254 break;
7255 }
7256
Chris Lattnere79d2492006-04-06 19:19:17 +00007257 case Intrinsic::ppc_altivec_vperm:
7258 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007259 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007260 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7261
7262 // Check that all of the elements are integer constants or undefs.
7263 bool AllEltsOk = true;
7264 for (unsigned i = 0; i != 16; ++i) {
7265 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7266 !isa<UndefValue>(Mask->getOperand(i))) {
7267 AllEltsOk = false;
7268 break;
7269 }
7270 }
7271
7272 if (AllEltsOk) {
7273 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007274 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7275 II->getOperand(1), Mask->getType(), CI);
7276 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7277 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007278 Value *Result = UndefValue::get(Op0->getType());
7279
7280 // Only extract each element once.
7281 Value *ExtractedElts[32];
7282 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7283
7284 for (unsigned i = 0; i != 16; ++i) {
7285 if (isa<UndefValue>(Mask->getOperand(i)))
7286 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007287 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007288 Idx &= 31; // Match the hardware behavior.
7289
7290 if (ExtractedElts[Idx] == 0) {
7291 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007292 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007293 InsertNewInstBefore(Elt, CI);
7294 ExtractedElts[Idx] = Elt;
7295 }
7296
7297 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007298 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007299 InsertNewInstBefore(cast<Instruction>(Result), CI);
7300 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007301 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007302 }
7303 }
7304 break;
7305
Chris Lattner503221f2006-01-13 21:28:09 +00007306 case Intrinsic::stackrestore: {
7307 // If the save is right next to the restore, remove the restore. This can
7308 // happen when variable allocas are DCE'd.
7309 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7310 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7311 BasicBlock::iterator BI = SS;
7312 if (&*++BI == II)
7313 return EraseInstFromFunction(CI);
7314 }
7315 }
7316
7317 // If the stack restore is in a return/unwind block and if there are no
7318 // allocas or calls between the restore and the return, nuke the restore.
7319 TerminatorInst *TI = II->getParent()->getTerminator();
7320 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7321 BasicBlock::iterator BI = II;
7322 bool CannotRemove = false;
7323 for (++BI; &*BI != TI; ++BI) {
7324 if (isa<AllocaInst>(BI) ||
7325 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7326 CannotRemove = true;
7327 break;
7328 }
7329 }
7330 if (!CannotRemove)
7331 return EraseInstFromFunction(CI);
7332 }
7333 break;
7334 }
7335 }
Chris Lattner00648e12004-10-12 04:52:52 +00007336 }
7337
Chris Lattnerc66b2232006-01-13 20:11:04 +00007338 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007339}
7340
7341// InvokeInst simplification
7342//
7343Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007344 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007345}
7346
Chris Lattneraec3d942003-10-07 22:32:43 +00007347// visitCallSite - Improvements for call and invoke instructions.
7348//
7349Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007350 bool Changed = false;
7351
7352 // If the callee is a constexpr cast of a function, attempt to move the cast
7353 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007354 if (transformConstExprCastCall(CS)) return 0;
7355
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007356 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007357
Chris Lattner61d9d812005-05-13 07:09:09 +00007358 if (Function *CalleeF = dyn_cast<Function>(Callee))
7359 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7360 Instruction *OldCall = CS.getInstruction();
7361 // If the call and callee calling conventions don't match, this call must
7362 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007363 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007364 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007365 if (!OldCall->use_empty())
7366 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7367 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7368 return EraseInstFromFunction(*OldCall);
7369 return 0;
7370 }
7371
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007372 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7373 // This instruction is not reachable, just remove it. We insert a store to
7374 // undef so that we know that this code is not reachable, despite the fact
7375 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007376 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007377 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007378 CS.getInstruction());
7379
7380 if (!CS.getInstruction()->use_empty())
7381 CS.getInstruction()->
7382 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7383
7384 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7385 // Don't break the CFG, insert a dummy cond branch.
7386 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007387 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007388 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007389 return EraseInstFromFunction(*CS.getInstruction());
7390 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007391
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007392 const PointerType *PTy = cast<PointerType>(Callee->getType());
7393 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7394 if (FTy->isVarArg()) {
7395 // See if we can optimize any arguments passed through the varargs area of
7396 // the call.
7397 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7398 E = CS.arg_end(); I != E; ++I)
7399 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7400 // If this cast does not effect the value passed through the varargs
7401 // area, we can eliminate the use of the cast.
7402 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007403 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007404 *I = Op;
7405 Changed = true;
7406 }
7407 }
7408 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007409
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007410 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007411}
7412
Chris Lattner970c33a2003-06-19 17:00:31 +00007413// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7414// attempt to move the cast to the arguments of the call/invoke.
7415//
7416bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7417 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7418 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007419 if (CE->getOpcode() != Instruction::BitCast ||
7420 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007421 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007422 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007423 Instruction *Caller = CS.getInstruction();
7424
7425 // Okay, this is a cast from a function to a different type. Unless doing so
7426 // would cause a type conversion of one of our arguments, change this call to
7427 // be a direct call with arguments casted to the appropriate types.
7428 //
7429 const FunctionType *FT = Callee->getFunctionType();
7430 const Type *OldRetTy = Caller->getType();
7431
Chris Lattner1f7942f2004-01-14 06:06:08 +00007432 // Check to see if we are changing the return type...
7433 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007434 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007435 // Conversion is ok if changing from pointer to int of same size.
7436 !(isa<PointerType>(FT->getReturnType()) &&
7437 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007438 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007439
7440 // If the callsite is an invoke instruction, and the return value is used by
7441 // a PHI node in a successor, we cannot change the return type of the call
7442 // because there is no place to put the cast instruction (without breaking
7443 // the critical edge). Bail out in this case.
7444 if (!Caller->use_empty())
7445 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7446 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7447 UI != E; ++UI)
7448 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7449 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007450 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007451 return false;
7452 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007453
7454 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7455 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007456
Chris Lattner970c33a2003-06-19 17:00:31 +00007457 CallSite::arg_iterator AI = CS.arg_begin();
7458 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7459 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007460 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007461 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007462 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007463 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007464 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007465 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007466 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7467 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Reid Spencer6274c722007-03-23 18:46:34 +00007468 && c->getValue().isPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007469 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007470 }
7471
7472 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007473 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007474 return false; // Do not delete arguments unless we have a function body...
7475
7476 // Okay, we decided that this is a safe thing to do: go ahead and start
7477 // inserting cast instructions as necessary...
7478 std::vector<Value*> Args;
7479 Args.reserve(NumActualArgs);
7480
7481 AI = CS.arg_begin();
7482 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7483 const Type *ParamTy = FT->getParamType(i);
7484 if ((*AI)->getType() == ParamTy) {
7485 Args.push_back(*AI);
7486 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007487 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007488 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007489 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007490 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007491 }
7492 }
7493
7494 // If the function takes more arguments than the call was taking, add them
7495 // now...
7496 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7497 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7498
7499 // If we are removing arguments to the function, emit an obnoxious warning...
7500 if (FT->getNumParams() < NumActualArgs)
7501 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007502 cerr << "WARNING: While resolving call to function '"
7503 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007504 } else {
7505 // Add all of the arguments in their promoted form to the arg list...
7506 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7507 const Type *PTy = getPromotedType((*AI)->getType());
7508 if (PTy != (*AI)->getType()) {
7509 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007510 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7511 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007512 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007513 InsertNewInstBefore(Cast, *Caller);
7514 Args.push_back(Cast);
7515 } else {
7516 Args.push_back(*AI);
7517 }
7518 }
7519 }
7520
7521 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007522 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007523
7524 Instruction *NC;
7525 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007526 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007527 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007528 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007529 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007530 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007531 if (cast<CallInst>(Caller)->isTailCall())
7532 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007533 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007534 }
7535
Chris Lattner6e0123b2007-02-11 01:23:03 +00007536 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007537 Value *NV = NC;
7538 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7539 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007540 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007541 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7542 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007543 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007544
7545 // If this is an invoke instruction, we should insert it after the first
7546 // non-phi, instruction in the normal successor block.
7547 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7548 BasicBlock::iterator I = II->getNormalDest()->begin();
7549 while (isa<PHINode>(I)) ++I;
7550 InsertNewInstBefore(NC, *I);
7551 } else {
7552 // Otherwise, it's a call, just insert cast right after the call instr
7553 InsertNewInstBefore(NC, *Caller);
7554 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007555 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007556 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007557 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007558 }
7559 }
7560
7561 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7562 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007563 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007564 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007565 return true;
7566}
7567
Chris Lattnercadac0c2006-11-01 04:51:18 +00007568/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7569/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7570/// and a single binop.
7571Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7572 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007573 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7574 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007575 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007576 Value *LHSVal = FirstInst->getOperand(0);
7577 Value *RHSVal = FirstInst->getOperand(1);
7578
7579 const Type *LHSType = LHSVal->getType();
7580 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007581
7582 // Scan to see if all operands are the same opcode, all have one use, and all
7583 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007584 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007585 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007586 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007587 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007588 // types or GEP's with different index types.
7589 I->getOperand(0)->getType() != LHSType ||
7590 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007591 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007592
7593 // If they are CmpInst instructions, check their predicates
7594 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7595 if (cast<CmpInst>(I)->getPredicate() !=
7596 cast<CmpInst>(FirstInst)->getPredicate())
7597 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007598
7599 // Keep track of which operand needs a phi node.
7600 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7601 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007602 }
7603
Chris Lattner4f218d52006-11-08 19:42:28 +00007604 // Otherwise, this is safe to transform, determine if it is profitable.
7605
7606 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7607 // Indexes are often folded into load/store instructions, so we don't want to
7608 // hide them behind a phi.
7609 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7610 return 0;
7611
Chris Lattnercadac0c2006-11-01 04:51:18 +00007612 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007613 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007614 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007615 if (LHSVal == 0) {
7616 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7617 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7618 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007619 InsertNewInstBefore(NewLHS, PN);
7620 LHSVal = NewLHS;
7621 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007622
7623 if (RHSVal == 0) {
7624 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7625 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7626 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007627 InsertNewInstBefore(NewRHS, PN);
7628 RHSVal = NewRHS;
7629 }
7630
Chris Lattnercd62f112006-11-08 19:29:23 +00007631 // Add all operands to the new PHIs.
7632 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7633 if (NewLHS) {
7634 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7635 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7636 }
7637 if (NewRHS) {
7638 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7639 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7640 }
7641 }
7642
Chris Lattnercadac0c2006-11-01 04:51:18 +00007643 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007644 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007645 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7646 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7647 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007648 else {
7649 assert(isa<GetElementPtrInst>(FirstInst));
7650 return new GetElementPtrInst(LHSVal, RHSVal);
7651 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007652}
7653
Chris Lattner14f82c72006-11-01 07:13:54 +00007654/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7655/// of the block that defines it. This means that it must be obvious the value
7656/// of the load is not changed from the point of the load to the end of the
7657/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007658///
7659/// Finally, it is safe, but not profitable, to sink a load targetting a
7660/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7661/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007662static bool isSafeToSinkLoad(LoadInst *L) {
7663 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7664
7665 for (++BBI; BBI != E; ++BBI)
7666 if (BBI->mayWriteToMemory())
7667 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007668
7669 // Check for non-address taken alloca. If not address-taken already, it isn't
7670 // profitable to do this xform.
7671 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7672 bool isAddressTaken = false;
7673 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7674 UI != E; ++UI) {
7675 if (isa<LoadInst>(UI)) continue;
7676 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7677 // If storing TO the alloca, then the address isn't taken.
7678 if (SI->getOperand(1) == AI) continue;
7679 }
7680 isAddressTaken = true;
7681 break;
7682 }
7683
7684 if (!isAddressTaken)
7685 return false;
7686 }
7687
Chris Lattner14f82c72006-11-01 07:13:54 +00007688 return true;
7689}
7690
Chris Lattner970c33a2003-06-19 17:00:31 +00007691
Chris Lattner7515cab2004-11-14 19:13:23 +00007692// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7693// operator and they all are only used by the PHI, PHI together their
7694// inputs, and do the operation once, to the result of the PHI.
7695Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7696 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7697
7698 // Scan the instruction, looking for input operations that can be folded away.
7699 // If all input operands to the phi are the same instruction (e.g. a cast from
7700 // the same type or "+42") we can pull the operation through the PHI, reducing
7701 // code size and simplifying code.
7702 Constant *ConstantOp = 0;
7703 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007704 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007705 if (isa<CastInst>(FirstInst)) {
7706 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007707 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007708 // Can fold binop, compare or shift here if the RHS is a constant,
7709 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007710 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007711 if (ConstantOp == 0)
7712 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007713 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7714 isVolatile = LI->isVolatile();
7715 // We can't sink the load if the loaded value could be modified between the
7716 // load and the PHI.
7717 if (LI->getParent() != PN.getIncomingBlock(0) ||
7718 !isSafeToSinkLoad(LI))
7719 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007720 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007721 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007722 return FoldPHIArgBinOpIntoPHI(PN);
7723 // Can't handle general GEPs yet.
7724 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007725 } else {
7726 return 0; // Cannot fold this operation.
7727 }
7728
7729 // Check to see if all arguments are the same operation.
7730 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7731 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7732 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007733 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007734 return 0;
7735 if (CastSrcTy) {
7736 if (I->getOperand(0)->getType() != CastSrcTy)
7737 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007738 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007739 // We can't sink the load if the loaded value could be modified between
7740 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007741 if (LI->isVolatile() != isVolatile ||
7742 LI->getParent() != PN.getIncomingBlock(i) ||
7743 !isSafeToSinkLoad(LI))
7744 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007745 } else if (I->getOperand(1) != ConstantOp) {
7746 return 0;
7747 }
7748 }
7749
7750 // Okay, they are all the same operation. Create a new PHI node of the
7751 // correct type, and PHI together all of the LHS's of the instructions.
7752 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7753 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007754 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007755
7756 Value *InVal = FirstInst->getOperand(0);
7757 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007758
7759 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007760 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7761 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7762 if (NewInVal != InVal)
7763 InVal = 0;
7764 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7765 }
7766
7767 Value *PhiVal;
7768 if (InVal) {
7769 // The new PHI unions all of the same values together. This is really
7770 // common, so we handle it intelligently here for compile-time speed.
7771 PhiVal = InVal;
7772 delete NewPN;
7773 } else {
7774 InsertNewInstBefore(NewPN, PN);
7775 PhiVal = NewPN;
7776 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007777
Chris Lattner7515cab2004-11-14 19:13:23 +00007778 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007779 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7780 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007781 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007782 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007783 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007784 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007785 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7786 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7787 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007788 else
Reid Spencer2341c222007-02-02 02:16:23 +00007789 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007790 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007791}
Chris Lattner48a44f72002-05-02 17:06:02 +00007792
Chris Lattner71536432005-01-17 05:10:15 +00007793/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7794/// that is dead.
7795static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7796 if (PN->use_empty()) return true;
7797 if (!PN->hasOneUse()) return false;
7798
7799 // Remember this node, and if we find the cycle, return.
7800 if (!PotentiallyDeadPHIs.insert(PN).second)
7801 return true;
7802
7803 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7804 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007805
Chris Lattner71536432005-01-17 05:10:15 +00007806 return false;
7807}
7808
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007809// PHINode simplification
7810//
Chris Lattner113f4f42002-06-25 16:13:24 +00007811Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007812 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007813 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007814
Owen Andersonae8aa642006-07-10 22:03:18 +00007815 if (Value *V = PN.hasConstantValue())
7816 return ReplaceInstUsesWith(PN, V);
7817
Owen Andersonae8aa642006-07-10 22:03:18 +00007818 // If all PHI operands are the same operation, pull them through the PHI,
7819 // reducing code size.
7820 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7821 PN.getIncomingValue(0)->hasOneUse())
7822 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7823 return Result;
7824
7825 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7826 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7827 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007828 if (PN.hasOneUse()) {
7829 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7830 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007831 std::set<PHINode*> PotentiallyDeadPHIs;
7832 PotentiallyDeadPHIs.insert(&PN);
7833 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7834 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7835 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007836
7837 // If this phi has a single use, and if that use just computes a value for
7838 // the next iteration of a loop, delete the phi. This occurs with unused
7839 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7840 // common case here is good because the only other things that catch this
7841 // are induction variable analysis (sometimes) and ADCE, which is only run
7842 // late.
7843 if (PHIUser->hasOneUse() &&
7844 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7845 PHIUser->use_back() == &PN) {
7846 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7847 }
7848 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007849
Chris Lattner91daeb52003-12-19 05:58:40 +00007850 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007851}
7852
Reid Spencer13bc5d72006-12-12 09:18:51 +00007853static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7854 Instruction *InsertPoint,
7855 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007856 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7857 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007858 // We must cast correctly to the pointer type. Ensure that we
7859 // sign extend the integer value if it is smaller as this is
7860 // used for address computation.
7861 Instruction::CastOps opcode =
7862 (VTySize < PtrSize ? Instruction::SExt :
7863 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7864 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007865}
7866
Chris Lattner48a44f72002-05-02 17:06:02 +00007867
Chris Lattner113f4f42002-06-25 16:13:24 +00007868Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007869 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007870 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007871 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007872 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007873 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007874
Chris Lattner81a7a232004-10-16 18:11:37 +00007875 if (isa<UndefValue>(GEP.getOperand(0)))
7876 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7877
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007878 bool HasZeroPointerIndex = false;
7879 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7880 HasZeroPointerIndex = C->isNullValue();
7881
7882 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007883 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007884
Chris Lattner69193f92004-04-05 01:30:19 +00007885 // Eliminate unneeded casts for indices.
7886 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007887 gep_type_iterator GTI = gep_type_begin(GEP);
7888 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7889 if (isa<SequentialType>(*GTI)) {
7890 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007891 if (CI->getOpcode() == Instruction::ZExt ||
7892 CI->getOpcode() == Instruction::SExt) {
7893 const Type *SrcTy = CI->getOperand(0)->getType();
7894 // We can eliminate a cast from i32 to i64 iff the target
7895 // is a 32-bit pointer target.
7896 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7897 MadeChange = true;
7898 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007899 }
7900 }
7901 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007902 // If we are using a wider index than needed for this platform, shrink it
7903 // to what we need. If the incoming value needs a cast instruction,
7904 // insert it. This explicit cast can make subsequent optimizations more
7905 // obvious.
7906 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007907 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007908 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007909 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007910 MadeChange = true;
7911 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007912 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7913 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007914 GEP.setOperand(i, Op);
7915 MadeChange = true;
7916 }
Chris Lattner69193f92004-04-05 01:30:19 +00007917 }
7918 if (MadeChange) return &GEP;
7919
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007920 // Combine Indices - If the source pointer to this getelementptr instruction
7921 // is a getelementptr instruction, combine the indices of the two
7922 // getelementptr instructions into a single instruction.
7923 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007924 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007925 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007926 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007927
7928 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007929 // Note that if our source is a gep chain itself that we wait for that
7930 // chain to be resolved before we perform this transformation. This
7931 // avoids us creating a TON of code in some cases.
7932 //
7933 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7934 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7935 return 0; // Wait until our source is folded to completion.
7936
Chris Lattneraf6094f2007-02-15 22:48:32 +00007937 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007938
7939 // Find out whether the last index in the source GEP is a sequential idx.
7940 bool EndsWithSequential = false;
7941 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7942 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007943 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007944
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007945 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007946 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007947 // Replace: gep (gep %P, long B), long A, ...
7948 // With: T = long A+B; gep %P, T, ...
7949 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007950 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007951 if (SO1 == Constant::getNullValue(SO1->getType())) {
7952 Sum = GO1;
7953 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7954 Sum = SO1;
7955 } else {
7956 // If they aren't the same type, convert both to an integer of the
7957 // target's pointer size.
7958 if (SO1->getType() != GO1->getType()) {
7959 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007960 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007961 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007962 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007963 } else {
7964 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007965 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007966 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007967 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007968
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007969 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007970 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007971 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007972 } else {
7973 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007974 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7975 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007976 }
7977 }
7978 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007979 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7980 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7981 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007982 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7983 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007984 }
Chris Lattner69193f92004-04-05 01:30:19 +00007985 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007986
7987 // Recycle the GEP we already have if possible.
7988 if (SrcGEPOperands.size() == 2) {
7989 GEP.setOperand(0, SrcGEPOperands[0]);
7990 GEP.setOperand(1, Sum);
7991 return &GEP;
7992 } else {
7993 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7994 SrcGEPOperands.end()-1);
7995 Indices.push_back(Sum);
7996 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7997 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007998 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007999 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008000 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008001 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008002 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8003 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008004 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8005 }
8006
8007 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008008 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8009 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008010
Chris Lattner5f667a62004-05-07 22:09:22 +00008011 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008012 // GEP of global variable. If all of the indices for this GEP are
8013 // constants, we can promote this to a constexpr instead of an instruction.
8014
8015 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008016 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008017 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8018 for (; I != E && isa<Constant>(*I); ++I)
8019 Indices.push_back(cast<Constant>(*I));
8020
8021 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008022 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8023 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008024
8025 // Replace all uses of the GEP with the new constexpr...
8026 return ReplaceInstUsesWith(GEP, CE);
8027 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008028 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008029 if (!isa<PointerType>(X->getType())) {
8030 // Not interesting. Source pointer must be a cast from pointer.
8031 } else if (HasZeroPointerIndex) {
8032 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8033 // into : GEP [10 x ubyte]* X, long 0, ...
8034 //
8035 // This occurs when the program declares an array extern like "int X[];"
8036 //
8037 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8038 const PointerType *XTy = cast<PointerType>(X->getType());
8039 if (const ArrayType *XATy =
8040 dyn_cast<ArrayType>(XTy->getElementType()))
8041 if (const ArrayType *CATy =
8042 dyn_cast<ArrayType>(CPTy->getElementType()))
8043 if (CATy->getElementType() == XATy->getElementType()) {
8044 // At this point, we know that the cast source type is a pointer
8045 // to an array of the same type as the destination pointer
8046 // array. Because the array type is never stepped over (there
8047 // is a leading zero) we can fold the cast into this GEP.
8048 GEP.setOperand(0, X);
8049 return &GEP;
8050 }
8051 } else if (GEP.getNumOperands() == 2) {
8052 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008053 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8054 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008055 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8056 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8057 if (isa<ArrayType>(SrcElTy) &&
8058 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8059 TD->getTypeSize(ResElTy)) {
8060 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008061 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008062 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008063 // V and GEP are both pointer types --> BitCast
8064 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008065 }
Chris Lattner2a893292005-09-13 18:36:04 +00008066
8067 // Transform things like:
8068 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8069 // (where tmp = 8*tmp2) into:
8070 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8071
8072 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008073 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008074 uint64_t ArrayEltSize =
8075 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8076
8077 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8078 // allow either a mul, shift, or constant here.
8079 Value *NewIdx = 0;
8080 ConstantInt *Scale = 0;
8081 if (ArrayEltSize == 1) {
8082 NewIdx = GEP.getOperand(1);
8083 Scale = ConstantInt::get(NewIdx->getType(), 1);
8084 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008085 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008086 Scale = CI;
8087 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8088 if (Inst->getOpcode() == Instruction::Shl &&
8089 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008090 unsigned ShAmt =
8091 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008092 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008093 NewIdx = Inst->getOperand(0);
8094 } else if (Inst->getOpcode() == Instruction::Mul &&
8095 isa<ConstantInt>(Inst->getOperand(1))) {
8096 Scale = cast<ConstantInt>(Inst->getOperand(1));
8097 NewIdx = Inst->getOperand(0);
8098 }
8099 }
8100
8101 // If the index will be to exactly the right offset with the scale taken
8102 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008103 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008104 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008105 Scale = ConstantInt::get(Scale->getType(),
8106 Scale->getZExtValue() / ArrayEltSize);
8107 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008108 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8109 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008110 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8111 NewIdx = InsertNewInstBefore(Sc, GEP);
8112 }
8113
8114 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008115 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008116 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008117 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008118 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8119 // The NewGEP must be pointer typed, so must the old one -> BitCast
8120 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008121 }
8122 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008123 }
Chris Lattnerca081252001-12-14 16:52:21 +00008124 }
8125
Chris Lattnerca081252001-12-14 16:52:21 +00008126 return 0;
8127}
8128
Chris Lattner1085bdf2002-11-04 16:18:53 +00008129Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8130 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8131 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008132 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8133 const Type *NewTy =
8134 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008135 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008136
8137 // Create and insert the replacement instruction...
8138 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008139 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008140 else {
8141 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008142 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008143 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008144
8145 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008146
Chris Lattner1085bdf2002-11-04 16:18:53 +00008147 // Scan to the end of the allocation instructions, to skip over a block of
8148 // allocas if possible...
8149 //
8150 BasicBlock::iterator It = New;
8151 while (isa<AllocationInst>(*It)) ++It;
8152
8153 // Now that I is pointing to the first non-allocation-inst in the block,
8154 // insert our getelementptr instruction...
8155 //
Reid Spencerc635f472006-12-31 05:48:39 +00008156 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008157 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8158 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008159
8160 // Now make everything use the getelementptr instead of the original
8161 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008162 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008163 } else if (isa<UndefValue>(AI.getArraySize())) {
8164 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008165 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008166
8167 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8168 // Note that we only do this for alloca's, because malloc should allocate and
8169 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008170 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008171 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008172 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8173
Chris Lattner1085bdf2002-11-04 16:18:53 +00008174 return 0;
8175}
8176
Chris Lattner8427bff2003-12-07 01:24:23 +00008177Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8178 Value *Op = FI.getOperand(0);
8179
8180 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8181 if (CastInst *CI = dyn_cast<CastInst>(Op))
8182 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8183 FI.setOperand(0, CI->getOperand(0));
8184 return &FI;
8185 }
8186
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008187 // free undef -> unreachable.
8188 if (isa<UndefValue>(Op)) {
8189 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008190 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008191 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008192 return EraseInstFromFunction(FI);
8193 }
8194
Chris Lattnerf3a36602004-02-28 04:57:37 +00008195 // If we have 'free null' delete the instruction. This can happen in stl code
8196 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008197 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008198 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008199
Chris Lattner8427bff2003-12-07 01:24:23 +00008200 return 0;
8201}
8202
8203
Chris Lattner72684fe2005-01-31 05:51:45 +00008204/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008205static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8206 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008207 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008208
8209 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008210 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008211 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008212
Reid Spencer31a4ef42007-01-22 05:51:25 +00008213 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008214 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008215 // If the source is an array, the code below will not succeed. Check to
8216 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8217 // constants.
8218 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8219 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8220 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008221 Value *Idxs[2];
8222 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8223 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008224 SrcTy = cast<PointerType>(CastOp->getType());
8225 SrcPTy = SrcTy->getElementType();
8226 }
8227
Reid Spencer31a4ef42007-01-22 05:51:25 +00008228 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008229 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008230 // Do not allow turning this into a load of an integer, which is then
8231 // casted to a pointer, this pessimizes pointer analysis a lot.
8232 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008233 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8234 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008235
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008236 // Okay, we are casting from one integer or pointer type to another of
8237 // the same size. Instead of casting the pointer before the load, cast
8238 // the result of the loaded value.
8239 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8240 CI->getName(),
8241 LI.isVolatile()),LI);
8242 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008243 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008244 }
Chris Lattner35e24772004-07-13 01:49:43 +00008245 }
8246 }
8247 return 0;
8248}
8249
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008250/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008251/// from this value cannot trap. If it is not obviously safe to load from the
8252/// specified pointer, we do a quick local scan of the basic block containing
8253/// ScanFrom, to determine if the address is already accessed.
8254static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8255 // If it is an alloca or global variable, it is always safe to load from.
8256 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8257
8258 // Otherwise, be a little bit agressive by scanning the local block where we
8259 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008260 // from/to. If so, the previous load or store would have already trapped,
8261 // so there is no harm doing an extra load (also, CSE will later eliminate
8262 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008263 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8264
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008265 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008266 --BBI;
8267
8268 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8269 if (LI->getOperand(0) == V) return true;
8270 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8271 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008272
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008273 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008274 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008275}
8276
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008277Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8278 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008279
Chris Lattnera9d84e32005-05-01 04:24:53 +00008280 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008281 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008282 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8283 return Res;
8284
8285 // None of the following transforms are legal for volatile loads.
8286 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008287
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008288 if (&LI.getParent()->front() != &LI) {
8289 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008290 // If the instruction immediately before this is a store to the same
8291 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008292 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8293 if (SI->getOperand(1) == LI.getOperand(0))
8294 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008295 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8296 if (LIB->getOperand(0) == LI.getOperand(0))
8297 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008298 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008299
8300 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8301 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8302 isa<UndefValue>(GEPI->getOperand(0))) {
8303 // Insert a new store to null instruction before the load to indicate
8304 // that this code is not reachable. We do this instead of inserting
8305 // an unreachable instruction directly because we cannot modify the
8306 // CFG.
8307 new StoreInst(UndefValue::get(LI.getType()),
8308 Constant::getNullValue(Op->getType()), &LI);
8309 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8310 }
8311
Chris Lattner81a7a232004-10-16 18:11:37 +00008312 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008313 // load null/undef -> undef
8314 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008315 // Insert a new store to null instruction before the load to indicate that
8316 // this code is not reachable. We do this instead of inserting an
8317 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008318 new StoreInst(UndefValue::get(LI.getType()),
8319 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008320 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008321 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008322
Chris Lattner81a7a232004-10-16 18:11:37 +00008323 // Instcombine load (constant global) into the value loaded.
8324 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008325 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008326 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008327
Chris Lattner81a7a232004-10-16 18:11:37 +00008328 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8329 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8330 if (CE->getOpcode() == Instruction::GetElementPtr) {
8331 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008332 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008333 if (Constant *V =
8334 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008335 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008336 if (CE->getOperand(0)->isNullValue()) {
8337 // Insert a new store to null instruction before the load to indicate
8338 // that this code is not reachable. We do this instead of inserting
8339 // an unreachable instruction directly because we cannot modify the
8340 // CFG.
8341 new StoreInst(UndefValue::get(LI.getType()),
8342 Constant::getNullValue(Op->getType()), &LI);
8343 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8344 }
8345
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008346 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008347 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8348 return Res;
8349 }
8350 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008351
Chris Lattnera9d84e32005-05-01 04:24:53 +00008352 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008353 // Change select and PHI nodes to select values instead of addresses: this
8354 // helps alias analysis out a lot, allows many others simplifications, and
8355 // exposes redundancy in the code.
8356 //
8357 // Note that we cannot do the transformation unless we know that the
8358 // introduced loads cannot trap! Something like this is valid as long as
8359 // the condition is always false: load (select bool %C, int* null, int* %G),
8360 // but it would not be valid if we transformed it to load from null
8361 // unconditionally.
8362 //
8363 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8364 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008365 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8366 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008367 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008368 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008369 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008370 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008371 return new SelectInst(SI->getCondition(), V1, V2);
8372 }
8373
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008374 // load (select (cond, null, P)) -> load P
8375 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8376 if (C->isNullValue()) {
8377 LI.setOperand(0, SI->getOperand(2));
8378 return &LI;
8379 }
8380
8381 // load (select (cond, P, null)) -> load P
8382 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8383 if (C->isNullValue()) {
8384 LI.setOperand(0, SI->getOperand(1));
8385 return &LI;
8386 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008387 }
8388 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008389 return 0;
8390}
8391
Reid Spencere928a152007-01-19 21:20:31 +00008392/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008393/// when possible.
8394static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8395 User *CI = cast<User>(SI.getOperand(1));
8396 Value *CastOp = CI->getOperand(0);
8397
8398 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8399 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8400 const Type *SrcPTy = SrcTy->getElementType();
8401
Reid Spencer31a4ef42007-01-22 05:51:25 +00008402 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008403 // If the source is an array, the code below will not succeed. Check to
8404 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8405 // constants.
8406 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8407 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8408 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008409 Value* Idxs[2];
8410 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8411 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008412 SrcTy = cast<PointerType>(CastOp->getType());
8413 SrcPTy = SrcTy->getElementType();
8414 }
8415
Reid Spencer9a4bed02007-01-20 23:35:48 +00008416 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8417 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8418 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008419
8420 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008421 // the same size. Instead of casting the pointer before
8422 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008423 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008424 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008425 Instruction::CastOps opcode = Instruction::BitCast;
8426 const Type* CastSrcTy = SIOp0->getType();
8427 const Type* CastDstTy = SrcPTy;
8428 if (isa<PointerType>(CastDstTy)) {
8429 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008430 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008431 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008432 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008433 opcode = Instruction::PtrToInt;
8434 }
8435 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008436 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008437 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008438 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008439 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8440 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008441 return new StoreInst(NewCast, CastOp);
8442 }
8443 }
8444 }
8445 return 0;
8446}
8447
Chris Lattner31f486c2005-01-31 05:36:43 +00008448Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8449 Value *Val = SI.getOperand(0);
8450 Value *Ptr = SI.getOperand(1);
8451
8452 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008453 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008454 ++NumCombined;
8455 return 0;
8456 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008457
8458 // If the RHS is an alloca with a single use, zapify the store, making the
8459 // alloca dead.
8460 if (Ptr->hasOneUse()) {
8461 if (isa<AllocaInst>(Ptr)) {
8462 EraseInstFromFunction(SI);
8463 ++NumCombined;
8464 return 0;
8465 }
8466
8467 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8468 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8469 GEP->getOperand(0)->hasOneUse()) {
8470 EraseInstFromFunction(SI);
8471 ++NumCombined;
8472 return 0;
8473 }
8474 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008475
Chris Lattner5997cf92006-02-08 03:25:32 +00008476 // Do really simple DSE, to catch cases where there are several consequtive
8477 // stores to the same location, separated by a few arithmetic operations. This
8478 // situation often occurs with bitfield accesses.
8479 BasicBlock::iterator BBI = &SI;
8480 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8481 --ScanInsts) {
8482 --BBI;
8483
8484 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8485 // Prev store isn't volatile, and stores to the same location?
8486 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8487 ++NumDeadStore;
8488 ++BBI;
8489 EraseInstFromFunction(*PrevSI);
8490 continue;
8491 }
8492 break;
8493 }
8494
Chris Lattnerdab43b22006-05-26 19:19:20 +00008495 // If this is a load, we have to stop. However, if the loaded value is from
8496 // the pointer we're loading and is producing the pointer we're storing,
8497 // then *this* store is dead (X = load P; store X -> P).
8498 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8499 if (LI == Val && LI->getOperand(0) == Ptr) {
8500 EraseInstFromFunction(SI);
8501 ++NumCombined;
8502 return 0;
8503 }
8504 // Otherwise, this is a load from some other location. Stores before it
8505 // may not be dead.
8506 break;
8507 }
8508
Chris Lattner5997cf92006-02-08 03:25:32 +00008509 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008510 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008511 break;
8512 }
8513
8514
8515 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008516
8517 // store X, null -> turns into 'unreachable' in SimplifyCFG
8518 if (isa<ConstantPointerNull>(Ptr)) {
8519 if (!isa<UndefValue>(Val)) {
8520 SI.setOperand(0, UndefValue::get(Val->getType()));
8521 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008522 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008523 ++NumCombined;
8524 }
8525 return 0; // Do not modify these!
8526 }
8527
8528 // store undef, Ptr -> noop
8529 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008530 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008531 ++NumCombined;
8532 return 0;
8533 }
8534
Chris Lattner72684fe2005-01-31 05:51:45 +00008535 // If the pointer destination is a cast, see if we can fold the cast into the
8536 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008537 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008538 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8539 return Res;
8540 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008541 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008542 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8543 return Res;
8544
Chris Lattner219175c2005-09-12 23:23:25 +00008545
8546 // If this store is the last instruction in the basic block, and if the block
8547 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008548 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008549 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8550 if (BI->isUnconditional()) {
8551 // Check to see if the successor block has exactly two incoming edges. If
8552 // so, see if the other predecessor contains a store to the same location.
8553 // if so, insert a PHI node (if needed) and move the stores down.
8554 BasicBlock *Dest = BI->getSuccessor(0);
8555
8556 pred_iterator PI = pred_begin(Dest);
8557 BasicBlock *Other = 0;
8558 if (*PI != BI->getParent())
8559 Other = *PI;
8560 ++PI;
8561 if (PI != pred_end(Dest)) {
8562 if (*PI != BI->getParent())
8563 if (Other)
8564 Other = 0;
8565 else
8566 Other = *PI;
8567 if (++PI != pred_end(Dest))
8568 Other = 0;
8569 }
8570 if (Other) { // If only one other pred...
8571 BBI = Other->getTerminator();
8572 // Make sure this other block ends in an unconditional branch and that
8573 // there is an instruction before the branch.
8574 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8575 BBI != Other->begin()) {
8576 --BBI;
8577 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8578
8579 // If this instruction is a store to the same location.
8580 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8581 // Okay, we know we can perform this transformation. Insert a PHI
8582 // node now if we need it.
8583 Value *MergedVal = OtherStore->getOperand(0);
8584 if (MergedVal != SI.getOperand(0)) {
8585 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8586 PN->reserveOperandSpace(2);
8587 PN->addIncoming(SI.getOperand(0), SI.getParent());
8588 PN->addIncoming(OtherStore->getOperand(0), Other);
8589 MergedVal = InsertNewInstBefore(PN, Dest->front());
8590 }
8591
8592 // Advance to a place where it is safe to insert the new store and
8593 // insert it.
8594 BBI = Dest->begin();
8595 while (isa<PHINode>(BBI)) ++BBI;
8596 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8597 OtherStore->isVolatile()), *BBI);
8598
8599 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008600 EraseInstFromFunction(SI);
8601 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008602 ++NumCombined;
8603 return 0;
8604 }
8605 }
8606 }
8607 }
8608
Chris Lattner31f486c2005-01-31 05:36:43 +00008609 return 0;
8610}
8611
8612
Chris Lattner9eef8a72003-06-04 04:46:00 +00008613Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8614 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008615 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008616 BasicBlock *TrueDest;
8617 BasicBlock *FalseDest;
8618 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8619 !isa<Constant>(X)) {
8620 // Swap Destinations and condition...
8621 BI.setCondition(X);
8622 BI.setSuccessor(0, FalseDest);
8623 BI.setSuccessor(1, TrueDest);
8624 return &BI;
8625 }
8626
Reid Spencer266e42b2006-12-23 06:05:41 +00008627 // Cannonicalize fcmp_one -> fcmp_oeq
8628 FCmpInst::Predicate FPred; Value *Y;
8629 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8630 TrueDest, FalseDest)))
8631 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8632 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8633 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008634 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008635 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8636 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008637 // Swap Destinations and condition...
8638 BI.setCondition(NewSCC);
8639 BI.setSuccessor(0, FalseDest);
8640 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008641 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008642 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008643 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008644 return &BI;
8645 }
8646
8647 // Cannonicalize icmp_ne -> icmp_eq
8648 ICmpInst::Predicate IPred;
8649 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8650 TrueDest, FalseDest)))
8651 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8652 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8653 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8654 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008655 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008656 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8657 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008658 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008659 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008660 BI.setSuccessor(0, FalseDest);
8661 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008662 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008663 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008664 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008665 return &BI;
8666 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008667
Chris Lattner9eef8a72003-06-04 04:46:00 +00008668 return 0;
8669}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008670
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008671Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8672 Value *Cond = SI.getCondition();
8673 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8674 if (I->getOpcode() == Instruction::Add)
8675 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8676 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8677 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008678 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008679 AddRHS));
8680 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008681 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008682 return &SI;
8683 }
8684 }
8685 return 0;
8686}
8687
Chris Lattner6bc98652006-03-05 00:22:33 +00008688/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8689/// is to leave as a vector operation.
8690static bool CheapToScalarize(Value *V, bool isConstant) {
8691 if (isa<ConstantAggregateZero>(V))
8692 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008693 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008694 if (isConstant) return true;
8695 // If all elts are the same, we can extract.
8696 Constant *Op0 = C->getOperand(0);
8697 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8698 if (C->getOperand(i) != Op0)
8699 return false;
8700 return true;
8701 }
8702 Instruction *I = dyn_cast<Instruction>(V);
8703 if (!I) return false;
8704
8705 // Insert element gets simplified to the inserted element or is deleted if
8706 // this is constant idx extract element and its a constant idx insertelt.
8707 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8708 isa<ConstantInt>(I->getOperand(2)))
8709 return true;
8710 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8711 return true;
8712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8713 if (BO->hasOneUse() &&
8714 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8715 CheapToScalarize(BO->getOperand(1), isConstant)))
8716 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008717 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8718 if (CI->hasOneUse() &&
8719 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8720 CheapToScalarize(CI->getOperand(1), isConstant)))
8721 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008722
8723 return false;
8724}
8725
Chris Lattner945e4372007-02-14 05:52:17 +00008726/// Read and decode a shufflevector mask.
8727///
8728/// It turns undef elements into values that are larger than the number of
8729/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008730static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8731 unsigned NElts = SVI->getType()->getNumElements();
8732 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8733 return std::vector<unsigned>(NElts, 0);
8734 if (isa<UndefValue>(SVI->getOperand(2)))
8735 return std::vector<unsigned>(NElts, 2*NElts);
8736
8737 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008738 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008739 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8740 if (isa<UndefValue>(CP->getOperand(i)))
8741 Result.push_back(NElts*2); // undef -> 8
8742 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008743 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008744 return Result;
8745}
8746
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008747/// FindScalarElement - Given a vector and an element number, see if the scalar
8748/// value is already around as a register, for example if it were inserted then
8749/// extracted from the vector.
8750static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008751 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8752 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008753 unsigned Width = PTy->getNumElements();
8754 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008755 return UndefValue::get(PTy->getElementType());
8756
8757 if (isa<UndefValue>(V))
8758 return UndefValue::get(PTy->getElementType());
8759 else if (isa<ConstantAggregateZero>(V))
8760 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008761 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008762 return CP->getOperand(EltNo);
8763 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8764 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008765 if (!isa<ConstantInt>(III->getOperand(2)))
8766 return 0;
8767 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008768
8769 // If this is an insert to the element we are looking for, return the
8770 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008771 if (EltNo == IIElt)
8772 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008773
8774 // Otherwise, the insertelement doesn't modify the value, recurse on its
8775 // vector input.
8776 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008777 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008778 unsigned InEl = getShuffleMask(SVI)[EltNo];
8779 if (InEl < Width)
8780 return FindScalarElement(SVI->getOperand(0), InEl);
8781 else if (InEl < Width*2)
8782 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8783 else
8784 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008785 }
8786
8787 // Otherwise, we don't know.
8788 return 0;
8789}
8790
Robert Bocchinoa8352962006-01-13 22:48:06 +00008791Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008792
Chris Lattner92346c32006-03-31 18:25:14 +00008793 // If packed val is undef, replace extract with scalar undef.
8794 if (isa<UndefValue>(EI.getOperand(0)))
8795 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8796
8797 // If packed val is constant 0, replace extract with scalar 0.
8798 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8799 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8800
Reid Spencerd84d35b2007-02-15 02:26:10 +00008801 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008802 // If packed val is constant with uniform operands, replace EI
8803 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008804 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008805 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008806 if (C->getOperand(i) != op0) {
8807 op0 = 0;
8808 break;
8809 }
8810 if (op0)
8811 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008812 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008813
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008814 // If extracting a specified index from the vector, see if we can recursively
8815 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008816 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008817 // This instruction only demands the single element from the input vector.
8818 // If the input vector has a single use, simplify it based on this use
8819 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008820 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008821 if (EI.getOperand(0)->hasOneUse()) {
8822 uint64_t UndefElts;
8823 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008824 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008825 UndefElts)) {
8826 EI.setOperand(0, V);
8827 return &EI;
8828 }
8829 }
8830
Reid Spencere0fc4df2006-10-20 07:07:24 +00008831 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008832 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008833 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008834
Chris Lattner83f65782006-05-25 22:53:38 +00008835 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008836 if (I->hasOneUse()) {
8837 // Push extractelement into predecessor operation if legal and
8838 // profitable to do so
8839 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008840 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8841 if (CheapToScalarize(BO, isConstantElt)) {
8842 ExtractElementInst *newEI0 =
8843 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8844 EI.getName()+".lhs");
8845 ExtractElementInst *newEI1 =
8846 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8847 EI.getName()+".rhs");
8848 InsertNewInstBefore(newEI0, EI);
8849 InsertNewInstBefore(newEI1, EI);
8850 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8851 }
Reid Spencerde46e482006-11-02 20:25:50 +00008852 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008853 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008854 PointerType::get(EI.getType()), EI);
8855 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008856 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008857 InsertNewInstBefore(GEP, EI);
8858 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008859 }
8860 }
8861 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8862 // Extracting the inserted element?
8863 if (IE->getOperand(2) == EI.getOperand(1))
8864 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8865 // If the inserted and extracted elements are constants, they must not
8866 // be the same value, extract from the pre-inserted value instead.
8867 if (isa<Constant>(IE->getOperand(2)) &&
8868 isa<Constant>(EI.getOperand(1))) {
8869 AddUsesToWorkList(EI);
8870 EI.setOperand(0, IE->getOperand(0));
8871 return &EI;
8872 }
8873 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8874 // If this is extracting an element from a shufflevector, figure out where
8875 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008876 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8877 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008878 Value *Src;
8879 if (SrcIdx < SVI->getType()->getNumElements())
8880 Src = SVI->getOperand(0);
8881 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8882 SrcIdx -= SVI->getType()->getNumElements();
8883 Src = SVI->getOperand(1);
8884 } else {
8885 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008886 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008887 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008888 }
8889 }
Chris Lattner83f65782006-05-25 22:53:38 +00008890 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008891 return 0;
8892}
8893
Chris Lattner90951862006-04-16 00:51:47 +00008894/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8895/// elements from either LHS or RHS, return the shuffle mask and true.
8896/// Otherwise, return false.
8897static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8898 std::vector<Constant*> &Mask) {
8899 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8900 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008901 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008902
8903 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008904 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008905 return true;
8906 } else if (V == LHS) {
8907 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008908 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008909 return true;
8910 } else if (V == RHS) {
8911 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008912 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008913 return true;
8914 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8915 // If this is an insert of an extract from some other vector, include it.
8916 Value *VecOp = IEI->getOperand(0);
8917 Value *ScalarOp = IEI->getOperand(1);
8918 Value *IdxOp = IEI->getOperand(2);
8919
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008920 if (!isa<ConstantInt>(IdxOp))
8921 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008922 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008923
8924 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8925 // Okay, we can handle this if the vector we are insertinting into is
8926 // transitively ok.
8927 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8928 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008929 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008930 return true;
8931 }
8932 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8933 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008934 EI->getOperand(0)->getType() == V->getType()) {
8935 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008936 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008937
8938 // This must be extracting from either LHS or RHS.
8939 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8940 // Okay, we can handle this if the vector we are insertinting into is
8941 // transitively ok.
8942 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8943 // If so, update the mask to reflect the inserted value.
8944 if (EI->getOperand(0) == LHS) {
8945 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008946 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008947 } else {
8948 assert(EI->getOperand(0) == RHS);
8949 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008950 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008951
8952 }
8953 return true;
8954 }
8955 }
8956 }
8957 }
8958 }
8959 // TODO: Handle shufflevector here!
8960
8961 return false;
8962}
8963
8964/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8965/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8966/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008967static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008968 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008969 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00008970 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008971 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008972 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00008973
8974 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008975 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008976 return V;
8977 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008978 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008979 return V;
8980 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8981 // If this is an insert of an extract from some other vector, include it.
8982 Value *VecOp = IEI->getOperand(0);
8983 Value *ScalarOp = IEI->getOperand(1);
8984 Value *IdxOp = IEI->getOperand(2);
8985
8986 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8987 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8988 EI->getOperand(0)->getType() == V->getType()) {
8989 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008990 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8991 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008992
8993 // Either the extracted from or inserted into vector must be RHSVec,
8994 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008995 if (EI->getOperand(0) == RHS || RHS == 0) {
8996 RHS = EI->getOperand(0);
8997 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008998 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008999 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009000 return V;
9001 }
9002
Chris Lattner90951862006-04-16 00:51:47 +00009003 if (VecOp == RHS) {
9004 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009005 // Everything but the extracted element is replaced with the RHS.
9006 for (unsigned i = 0; i != NumElts; ++i) {
9007 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009008 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009009 }
9010 return V;
9011 }
Chris Lattner90951862006-04-16 00:51:47 +00009012
9013 // If this insertelement is a chain that comes from exactly these two
9014 // vectors, return the vector and the effective shuffle.
9015 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9016 return EI->getOperand(0);
9017
Chris Lattner39fac442006-04-15 01:39:45 +00009018 }
9019 }
9020 }
Chris Lattner90951862006-04-16 00:51:47 +00009021 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009022
9023 // Otherwise, can't do anything fancy. Return an identity vector.
9024 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009025 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009026 return V;
9027}
9028
9029Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9030 Value *VecOp = IE.getOperand(0);
9031 Value *ScalarOp = IE.getOperand(1);
9032 Value *IdxOp = IE.getOperand(2);
9033
9034 // If the inserted element was extracted from some other vector, and if the
9035 // indexes are constant, try to turn this into a shufflevector operation.
9036 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9037 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9038 EI->getOperand(0)->getType() == IE.getType()) {
9039 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009040 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9041 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009042
9043 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9044 return ReplaceInstUsesWith(IE, VecOp);
9045
9046 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9047 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9048
9049 // If we are extracting a value from a vector, then inserting it right
9050 // back into the same place, just use the input vector.
9051 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9052 return ReplaceInstUsesWith(IE, VecOp);
9053
9054 // We could theoretically do this for ANY input. However, doing so could
9055 // turn chains of insertelement instructions into a chain of shufflevector
9056 // instructions, and right now we do not merge shufflevectors. As such,
9057 // only do this in a situation where it is clear that there is benefit.
9058 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9059 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9060 // the values of VecOp, except then one read from EIOp0.
9061 // Build a new shuffle mask.
9062 std::vector<Constant*> Mask;
9063 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009064 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009065 else {
9066 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009067 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009068 NumVectorElts));
9069 }
Reid Spencerc635f472006-12-31 05:48:39 +00009070 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009071 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009072 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009073 }
9074
9075 // If this insertelement isn't used by some other insertelement, turn it
9076 // (and any insertelements it points to), into one big shuffle.
9077 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9078 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009079 Value *RHS = 0;
9080 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9081 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9082 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009083 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009084 }
9085 }
9086 }
9087
9088 return 0;
9089}
9090
9091
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009092Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9093 Value *LHS = SVI.getOperand(0);
9094 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009095 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009096
9097 bool MadeChange = false;
9098
Chris Lattner2deeaea2006-10-05 06:55:50 +00009099 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009100 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009101 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9102
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009103 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009104 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009105 if (isa<UndefValue>(SVI.getOperand(1))) {
9106 // Scan to see if there are any references to the RHS. If so, replace them
9107 // with undef element refs and set MadeChange to true.
9108 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9109 if (Mask[i] >= e && Mask[i] != 2*e) {
9110 Mask[i] = 2*e;
9111 MadeChange = true;
9112 }
9113 }
9114
9115 if (MadeChange) {
9116 // Remap any references to RHS to use LHS.
9117 std::vector<Constant*> Elts;
9118 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9119 if (Mask[i] == 2*e)
9120 Elts.push_back(UndefValue::get(Type::Int32Ty));
9121 else
9122 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9123 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009124 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009125 }
9126 }
Chris Lattner39fac442006-04-15 01:39:45 +00009127
Chris Lattner12249be2006-05-25 23:48:38 +00009128 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9129 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9130 if (LHS == RHS || isa<UndefValue>(LHS)) {
9131 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009132 // shuffle(undef,undef,mask) -> undef.
9133 return ReplaceInstUsesWith(SVI, LHS);
9134 }
9135
Chris Lattner12249be2006-05-25 23:48:38 +00009136 // Remap any references to RHS to use LHS.
9137 std::vector<Constant*> Elts;
9138 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009139 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009140 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009141 else {
9142 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9143 (Mask[i] < e && isa<UndefValue>(LHS)))
9144 Mask[i] = 2*e; // Turn into undef.
9145 else
9146 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009147 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009148 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009149 }
Chris Lattner12249be2006-05-25 23:48:38 +00009150 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009151 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009152 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009153 LHS = SVI.getOperand(0);
9154 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009155 MadeChange = true;
9156 }
9157
Chris Lattner0e477162006-05-26 00:29:06 +00009158 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009159 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009160
Chris Lattner12249be2006-05-25 23:48:38 +00009161 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9162 if (Mask[i] >= e*2) continue; // Ignore undef values.
9163 // Is this an identity shuffle of the LHS value?
9164 isLHSID &= (Mask[i] == i);
9165
9166 // Is this an identity shuffle of the RHS value?
9167 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009168 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009169
Chris Lattner12249be2006-05-25 23:48:38 +00009170 // Eliminate identity shuffles.
9171 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9172 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009173
Chris Lattner0e477162006-05-26 00:29:06 +00009174 // If the LHS is a shufflevector itself, see if we can combine it with this
9175 // one without producing an unusual shuffle. Here we are really conservative:
9176 // we are absolutely afraid of producing a shuffle mask not in the input
9177 // program, because the code gen may not be smart enough to turn a merged
9178 // shuffle into two specific shuffles: it may produce worse code. As such,
9179 // we only merge two shuffles if the result is one of the two input shuffle
9180 // masks. In this case, merging the shuffles just removes one instruction,
9181 // which we know is safe. This is good for things like turning:
9182 // (splat(splat)) -> splat.
9183 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9184 if (isa<UndefValue>(RHS)) {
9185 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9186
9187 std::vector<unsigned> NewMask;
9188 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9189 if (Mask[i] >= 2*e)
9190 NewMask.push_back(2*e);
9191 else
9192 NewMask.push_back(LHSMask[Mask[i]]);
9193
9194 // If the result mask is equal to the src shuffle or this shuffle mask, do
9195 // the replacement.
9196 if (NewMask == LHSMask || NewMask == Mask) {
9197 std::vector<Constant*> Elts;
9198 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9199 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009200 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009201 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009202 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009203 }
9204 }
9205 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9206 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009207 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009208 }
9209 }
9210 }
Chris Lattner4284f642007-01-30 22:32:46 +00009211
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009212 return MadeChange ? &SVI : 0;
9213}
9214
9215
Robert Bocchinoa8352962006-01-13 22:48:06 +00009216
Chris Lattner39c98bb2004-12-08 23:43:58 +00009217
9218/// TryToSinkInstruction - Try to move the specified instruction from its
9219/// current block into the beginning of DestBlock, which can only happen if it's
9220/// safe to move the instruction past all of the instructions between it and the
9221/// end of its block.
9222static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9223 assert(I->hasOneUse() && "Invariants didn't hold!");
9224
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009225 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9226 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009227
Chris Lattner39c98bb2004-12-08 23:43:58 +00009228 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009229 if (isa<AllocaInst>(I) && I->getParent() ==
9230 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009231 return false;
9232
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009233 // We can only sink load instructions if there is nothing between the load and
9234 // the end of block that could change the value.
9235 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009236 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9237 Scan != E; ++Scan)
9238 if (Scan->mayWriteToMemory())
9239 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009240 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009241
9242 BasicBlock::iterator InsertPos = DestBlock->begin();
9243 while (isa<PHINode>(InsertPos)) ++InsertPos;
9244
Chris Lattner9f269e42005-08-08 19:11:57 +00009245 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009246 ++NumSunkInst;
9247 return true;
9248}
9249
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009250
9251/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9252/// all reachable code to the worklist.
9253///
9254/// This has a couple of tricks to make the code faster and more powerful. In
9255/// particular, we constant fold and DCE instructions as we go, to avoid adding
9256/// them to the worklist (this significantly speeds up instcombine on code where
9257/// many instructions are dead or constant). Additionally, if we find a branch
9258/// whose condition is a known constant, we only visit the reachable successors.
9259///
9260static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009261 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009262 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009263 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009264 std::vector<BasicBlock*> Worklist;
9265 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009266
Chris Lattner12b89cc2007-03-23 19:17:18 +00009267 while (!Worklist.empty()) {
9268 BB = Worklist.back();
9269 Worklist.pop_back();
9270
9271 // We have now visited this block! If we've already been here, ignore it.
9272 if (!Visited.insert(BB)) continue;
9273
9274 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9275 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009276
Chris Lattner12b89cc2007-03-23 19:17:18 +00009277 // DCE instruction if trivially dead.
9278 if (isInstructionTriviallyDead(Inst)) {
9279 ++NumDeadInst;
9280 DOUT << "IC: DCE: " << *Inst;
9281 Inst->eraseFromParent();
9282 continue;
9283 }
9284
9285 // ConstantProp instruction if trivially constant.
9286 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9287 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9288 Inst->replaceAllUsesWith(C);
9289 ++NumConstProp;
9290 Inst->eraseFromParent();
9291 continue;
9292 }
9293
9294 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009295 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009296
9297 // Recursively visit successors. If this is a branch or switch on a
9298 // constant, only visit the reachable successor.
9299 TerminatorInst *TI = BB->getTerminator();
9300 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9301 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9302 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9303 Worklist.push_back(BI->getSuccessor(!CondVal));
9304 continue;
9305 }
9306 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9307 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9308 // See if this is an explicit destination.
9309 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9310 if (SI->getCaseValue(i) == Cond) {
9311 Worklist.push_back(SI->getSuccessor(i));
9312 continue;
9313 }
9314
9315 // Otherwise it is the default destination.
9316 Worklist.push_back(SI->getSuccessor(0));
9317 continue;
9318 }
9319 }
9320
9321 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9322 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009323 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009324}
9325
Chris Lattner960a5432007-03-03 02:04:50 +00009326bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009327 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009328 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009329
9330 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9331 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009332
Chris Lattner4ed40f72005-07-07 20:40:38 +00009333 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009334 // Do a depth-first traversal of the function, populate the worklist with
9335 // the reachable instructions. Ignore blocks that are not reachable. Keep
9336 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009337 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009338 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009339
Chris Lattner4ed40f72005-07-07 20:40:38 +00009340 // Do a quick scan over the function. If we find any blocks that are
9341 // unreachable, remove any instructions inside of them. This prevents
9342 // the instcombine code from having to deal with some bad special cases.
9343 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9344 if (!Visited.count(BB)) {
9345 Instruction *Term = BB->getTerminator();
9346 while (Term != BB->begin()) { // Remove instrs bottom-up
9347 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009348
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009349 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009350 ++NumDeadInst;
9351
9352 if (!I->use_empty())
9353 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9354 I->eraseFromParent();
9355 }
9356 }
9357 }
Chris Lattnerca081252001-12-14 16:52:21 +00009358
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009359 while (!Worklist.empty()) {
9360 Instruction *I = RemoveOneFromWorkList();
9361 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009362
Chris Lattner1443bc52006-05-11 17:11:52 +00009363 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009364 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009365 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009366 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009367 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009368 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009369
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009370 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009371
9372 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009373 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009374 continue;
9375 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009376
Chris Lattner1443bc52006-05-11 17:11:52 +00009377 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009378 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009379 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009380
Chris Lattner1443bc52006-05-11 17:11:52 +00009381 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009382 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009383 ReplaceInstUsesWith(*I, C);
9384
Chris Lattner99f48c62002-09-02 04:59:56 +00009385 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009386 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009387 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009388 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009389 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009390
Chris Lattner39c98bb2004-12-08 23:43:58 +00009391 // See if we can trivially sink this instruction to a successor basic block.
9392 if (I->hasOneUse()) {
9393 BasicBlock *BB = I->getParent();
9394 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9395 if (UserParent != BB) {
9396 bool UserIsSuccessor = false;
9397 // See if the user is one of our successors.
9398 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9399 if (*SI == UserParent) {
9400 UserIsSuccessor = true;
9401 break;
9402 }
9403
9404 // If the user is one of our immediate successors, and if that successor
9405 // only has us as a predecessors (we'd have to split the critical edge
9406 // otherwise), we can keep going.
9407 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9408 next(pred_begin(UserParent)) == pred_end(UserParent))
9409 // Okay, the CFG is simple enough, try to sink this instruction.
9410 Changed |= TryToSinkInstruction(I, UserParent);
9411 }
9412 }
9413
Chris Lattnerca081252001-12-14 16:52:21 +00009414 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009415 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009416 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009417 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009418 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009419 DOUT << "IC: Old = " << *I
9420 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009421
Chris Lattner396dbfe2004-06-09 05:08:07 +00009422 // Everything uses the new instruction now.
9423 I->replaceAllUsesWith(Result);
9424
9425 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009426 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009427 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009428
Chris Lattner6e0123b2007-02-11 01:23:03 +00009429 // Move the name to the new instruction first.
9430 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009431
9432 // Insert the new instruction into the basic block...
9433 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009434 BasicBlock::iterator InsertPos = I;
9435
9436 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9437 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9438 ++InsertPos;
9439
9440 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009441
Chris Lattner63d75af2004-05-01 23:27:23 +00009442 // Make sure that we reprocess all operands now that we reduced their
9443 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009444 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009445
Chris Lattner396dbfe2004-06-09 05:08:07 +00009446 // Instructions can end up on the worklist more than once. Make sure
9447 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009448 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009449
9450 // Erase the old instruction.
9451 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009452 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009453 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009454
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009455 // If the instruction was modified, it's possible that it is now dead.
9456 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009457 if (isInstructionTriviallyDead(I)) {
9458 // Make sure we process all operands now that we are reducing their
9459 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009460 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009461
Chris Lattner63d75af2004-05-01 23:27:23 +00009462 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009463 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009464 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009465 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009466 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009467 AddToWorkList(I);
9468 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009469 }
Chris Lattner053c0932002-05-14 15:24:07 +00009470 }
Chris Lattner260ab202002-04-18 17:39:14 +00009471 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009472 }
9473 }
9474
Chris Lattner960a5432007-03-03 02:04:50 +00009475 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009476 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009477}
9478
Chris Lattner960a5432007-03-03 02:04:50 +00009479
9480bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009481 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9482
Chris Lattner960a5432007-03-03 02:04:50 +00009483 bool EverMadeChange = false;
9484
9485 // Iterate while there is work to do.
9486 unsigned Iteration = 0;
9487 while (DoOneIteration(F, Iteration++))
9488 EverMadeChange = true;
9489 return EverMadeChange;
9490}
9491
Brian Gaeke38b79e82004-07-27 17:43:21 +00009492FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009493 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009494}
Brian Gaeke960707c2003-11-11 22:41:34 +00009495